blob: 3c14b6ba50fb6cf828376dc11e295e45a8722111 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000044
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000045#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000046#include <windows.h>
47#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000048
Victor Stinnerce5faf62011-10-05 00:42:43 +020049#ifdef Py_DEBUG
50# define DONT_MAKE_RESULT_READY
51#endif
52
Guido van Rossumd57fd912000-03-10 22:53:23 +000053/* Endianness switches; defaults to little endian */
54
55#ifdef WORDS_BIGENDIAN
56# define BYTEORDER_IS_BIG_ENDIAN
57#else
58# define BYTEORDER_IS_LITTLE_ENDIAN
59#endif
60
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000061/* --- Globals ------------------------------------------------------------
62
63 The globals are initialized by the _PyUnicode_Init() API and should
64 not be used before calling that API.
65
66*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000067
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000068
69#ifdef __cplusplus
70extern "C" {
71#endif
72
Victor Stinner910337b2011-10-03 03:20:16 +020073#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020074# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020075#else
76# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
77#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020078
Victor Stinnere90fe6a2011-10-01 16:48:13 +020079#define _PyUnicode_UTF8(op) \
80 (((PyCompactUnicodeObject*)(op))->utf8)
81#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020082 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020083 assert(PyUnicode_IS_READY(op)), \
84 PyUnicode_IS_COMPACT_ASCII(op) ? \
85 ((char*)((PyASCIIObject*)(op) + 1)) : \
86 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020087#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020088 (((PyCompactUnicodeObject*)(op))->utf8_length)
89#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020090 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020091 assert(PyUnicode_IS_READY(op)), \
92 PyUnicode_IS_COMPACT_ASCII(op) ? \
93 ((PyASCIIObject*)(op))->length : \
94 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020095#define _PyUnicode_WSTR(op) \
96 (((PyASCIIObject*)(op))->wstr)
97#define _PyUnicode_WSTR_LENGTH(op) \
98 (((PyCompactUnicodeObject*)(op))->wstr_length)
99#define _PyUnicode_LENGTH(op) \
100 (((PyASCIIObject *)(op))->length)
101#define _PyUnicode_STATE(op) \
102 (((PyASCIIObject *)(op))->state)
103#define _PyUnicode_HASH(op) \
104 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200105#define _PyUnicode_KIND(op) \
106 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200107 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200108#define _PyUnicode_GET_LENGTH(op) \
109 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200110 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200111#define _PyUnicode_DATA_ANY(op) \
112 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200113
Victor Stinner910337b2011-10-03 03:20:16 +0200114#undef PyUnicode_READY
115#define PyUnicode_READY(op) \
116 (assert(_PyUnicode_CHECK(op)), \
117 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200118 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100119 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200120
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200121#define _PyUnicode_READY_REPLACE(p_obj) \
122 (assert(_PyUnicode_CHECK(*p_obj)), \
123 (PyUnicode_IS_READY(*p_obj) ? \
124 0 : _PyUnicode_ReadyReplace((PyObject **)(p_obj))))
125
Victor Stinnerc379ead2011-10-03 12:52:27 +0200126#define _PyUnicode_SHARE_UTF8(op) \
127 (assert(_PyUnicode_CHECK(op)), \
128 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
129 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
130#define _PyUnicode_SHARE_WSTR(op) \
131 (assert(_PyUnicode_CHECK(op)), \
132 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
133
Victor Stinner829c0ad2011-10-03 01:08:02 +0200134/* true if the Unicode object has an allocated UTF-8 memory block
135 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200136#define _PyUnicode_HAS_UTF8_MEMORY(op) \
137 (assert(_PyUnicode_CHECK(op)), \
138 (!PyUnicode_IS_COMPACT_ASCII(op) \
139 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200140 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
141
Victor Stinner03490912011-10-03 23:45:12 +0200142/* true if the Unicode object has an allocated wstr memory block
143 (not shared with other data) */
144#define _PyUnicode_HAS_WSTR_MEMORY(op) \
145 (assert(_PyUnicode_CHECK(op)), \
146 (_PyUnicode_WSTR(op) && \
147 (!PyUnicode_IS_READY(op) || \
148 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
149
Victor Stinner910337b2011-10-03 03:20:16 +0200150/* Generic helper macro to convert characters of different types.
151 from_type and to_type have to be valid type names, begin and end
152 are pointers to the source characters which should be of type
153 "from_type *". to is a pointer of type "to_type *" and points to the
154 buffer where the result characters are written to. */
155#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
156 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200157 to_type *_to = (to_type *) to; \
158 const from_type *_iter = (begin); \
159 const from_type *_end = (end); \
160 Py_ssize_t n = (_end) - (_iter); \
161 const from_type *_unrolled_end = \
162 _iter + (n & ~ (Py_ssize_t) 3); \
163 while (_iter < (_unrolled_end)) { \
164 _to[0] = (to_type) _iter[0]; \
165 _to[1] = (to_type) _iter[1]; \
166 _to[2] = (to_type) _iter[2]; \
167 _to[3] = (to_type) _iter[3]; \
168 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200169 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_end)) \
171 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200172 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200173
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200174/* The Unicode string has been modified: reset the hash */
175#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
176
Walter Dörwald16807132007-05-25 13:52:07 +0000177/* This dictionary holds all interned unicode strings. Note that references
178 to strings in this dictionary are *not* counted in the string's ob_refcnt.
179 When the interned string reaches a refcnt of 0 the string deallocation
180 function will delete the reference from this dictionary.
181
182 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000183 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000184*/
185static PyObject *interned;
186
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000187/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200188static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000189
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200190/* List of static strings. */
191static _Py_Identifier *static_strings;
192
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000193/* Single character Unicode strings in the Latin-1 range are being
194 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200195static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000196
Christian Heimes190d79e2008-01-30 11:58:22 +0000197/* Fast detection of the most frequent whitespace characters */
198const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000199 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000200/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000201/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000202/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000203/* case 0x000C: * FORM FEED */
204/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000205 0, 1, 1, 1, 1, 1, 0, 0,
206 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000207/* case 0x001C: * FILE SEPARATOR */
208/* case 0x001D: * GROUP SEPARATOR */
209/* case 0x001E: * RECORD SEPARATOR */
210/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000211 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000213 1, 0, 0, 0, 0, 0, 0, 0,
214 0, 0, 0, 0, 0, 0, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000217
Benjamin Peterson14339b62009-01-31 16:36:08 +0000218 0, 0, 0, 0, 0, 0, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0,
220 0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0,
223 0, 0, 0, 0, 0, 0, 0, 0,
224 0, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000226};
227
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200228/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200229static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200230static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200231static void copy_characters(
232 PyObject *to, Py_ssize_t to_start,
233 PyObject *from, Py_ssize_t from_start,
234 Py_ssize_t how_many);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200235#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200236static int unicode_is_singleton(PyObject *unicode);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200237#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200238
Alexander Belopolsky40018472011-02-26 01:02:56 +0000239static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200240unicode_fromascii(const unsigned char *s, Py_ssize_t size);
241static PyObject *
242_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
243static PyObject *
244_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
245static PyObject *
246_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
247
248static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000249unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000250 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100251 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000252 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
253
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254static void
255raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300256 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100257 PyObject *unicode,
258 Py_ssize_t startpos, Py_ssize_t endpos,
259 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000260
Christian Heimes190d79e2008-01-30 11:58:22 +0000261/* Same for linebreaks */
262static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000263 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000264/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000265/* 0x000B, * LINE TABULATION */
266/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000267/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000268 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000269 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000270/* 0x001C, * FILE SEPARATOR */
271/* 0x001D, * GROUP SEPARATOR */
272/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 0, 0, 0, 0, 1, 1, 1, 0,
274 0, 0, 0, 0, 0, 0, 0, 0,
275 0, 0, 0, 0, 0, 0, 0, 0,
276 0, 0, 0, 0, 0, 0, 0, 0,
277 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000278
Benjamin Peterson14339b62009-01-31 16:36:08 +0000279 0, 0, 0, 0, 0, 0, 0, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
282 0, 0, 0, 0, 0, 0, 0, 0,
283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000287};
288
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300289/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
290 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000291Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000292PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000293{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000294#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000295 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000296#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000297 /* This is actually an illegal character, so it should
298 not be passed to unichr. */
299 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000300#endif
301}
302
Victor Stinner910337b2011-10-03 03:20:16 +0200303#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200304int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100305_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200306{
307 PyASCIIObject *ascii;
308 unsigned int kind;
309
310 assert(PyUnicode_Check(op));
311
312 ascii = (PyASCIIObject *)op;
313 kind = ascii->state.kind;
314
Victor Stinnera3b334d2011-10-03 13:53:37 +0200315 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200316 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200317 assert(ascii->state.ready == 1);
318 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200319 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200320 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200321 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200322
Victor Stinnera41463c2011-10-04 01:05:08 +0200323 if (ascii->state.compact == 1) {
324 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200325 assert(kind == PyUnicode_1BYTE_KIND
326 || kind == PyUnicode_2BYTE_KIND
327 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200328 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200329 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200330 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100331 }
332 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200333 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
334
335 data = unicode->data.any;
336 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100337 assert(ascii->length == 0);
338 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200339 assert(ascii->state.compact == 0);
340 assert(ascii->state.ascii == 0);
341 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100342 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200343 assert(ascii->wstr != NULL);
344 assert(data == NULL);
345 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200346 }
347 else {
348 assert(kind == PyUnicode_1BYTE_KIND
349 || kind == PyUnicode_2BYTE_KIND
350 || kind == PyUnicode_4BYTE_KIND);
351 assert(ascii->state.compact == 0);
352 assert(ascii->state.ready == 1);
353 assert(data != NULL);
354 if (ascii->state.ascii) {
355 assert (compact->utf8 == data);
356 assert (compact->utf8_length == ascii->length);
357 }
358 else
359 assert (compact->utf8 != data);
360 }
361 }
362 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200363 if (
364#if SIZEOF_WCHAR_T == 2
365 kind == PyUnicode_2BYTE_KIND
366#else
367 kind == PyUnicode_4BYTE_KIND
368#endif
369 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200370 {
371 assert(ascii->wstr == data);
372 assert(compact->wstr_length == ascii->length);
373 } else
374 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200375 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200376
377 if (compact->utf8 == NULL)
378 assert(compact->utf8_length == 0);
379 if (ascii->wstr == NULL)
380 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200381 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200382 /* check that the best kind is used */
383 if (check_content && kind != PyUnicode_WCHAR_KIND)
384 {
385 Py_ssize_t i;
386 Py_UCS4 maxchar = 0;
387 void *data = PyUnicode_DATA(ascii);
388 for (i=0; i < ascii->length; i++)
389 {
390 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
391 if (ch > maxchar)
392 maxchar = ch;
393 }
394 if (kind == PyUnicode_1BYTE_KIND) {
395 if (ascii->state.ascii == 0)
396 assert(maxchar >= 128);
397 else
398 assert(maxchar < 128);
399 }
400 else if (kind == PyUnicode_2BYTE_KIND)
401 assert(maxchar >= 0x100);
402 else
403 assert(maxchar >= 0x10000);
404 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100405 if (check_content && !unicode_is_singleton(op))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200406 assert(ascii->hash == -1);
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400407 return 1;
408}
Victor Stinner910337b2011-10-03 03:20:16 +0200409#endif
410
Victor Stinner3a50e702011-10-18 21:21:00 +0200411#ifdef HAVE_MBCS
412static OSVERSIONINFOEX winver;
413#endif
414
Thomas Wouters477c8d52006-05-27 19:21:47 +0000415/* --- Bloom Filters ----------------------------------------------------- */
416
417/* stuff to implement simple "bloom filters" for Unicode characters.
418 to keep things simple, we use a single bitmask, using the least 5
419 bits from each unicode characters as the bit index. */
420
421/* the linebreak mask is set up by Unicode_Init below */
422
Antoine Pitrouf068f942010-01-13 14:19:12 +0000423#if LONG_BIT >= 128
424#define BLOOM_WIDTH 128
425#elif LONG_BIT >= 64
426#define BLOOM_WIDTH 64
427#elif LONG_BIT >= 32
428#define BLOOM_WIDTH 32
429#else
430#error "LONG_BIT is smaller than 32"
431#endif
432
Thomas Wouters477c8d52006-05-27 19:21:47 +0000433#define BLOOM_MASK unsigned long
434
435static BLOOM_MASK bloom_linebreak;
436
Antoine Pitrouf068f942010-01-13 14:19:12 +0000437#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
438#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000439
Benjamin Peterson29060642009-01-31 22:14:21 +0000440#define BLOOM_LINEBREAK(ch) \
441 ((ch) < 128U ? ascii_linebreak[(ch)] : \
442 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000443
Alexander Belopolsky40018472011-02-26 01:02:56 +0000444Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200445make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000446{
447 /* calculate simple bloom-style bitmask for a given unicode string */
448
Antoine Pitrouf068f942010-01-13 14:19:12 +0000449 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000450 Py_ssize_t i;
451
452 mask = 0;
453 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200454 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000455
456 return mask;
457}
458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200459#define BLOOM_MEMBER(mask, chr, str) \
460 (BLOOM(mask, chr) \
461 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000462
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200463/* Compilation of templated routines */
464
465#include "stringlib/asciilib.h"
466#include "stringlib/fastsearch.h"
467#include "stringlib/partition.h"
468#include "stringlib/split.h"
469#include "stringlib/count.h"
470#include "stringlib/find.h"
471#include "stringlib/find_max_char.h"
472#include "stringlib/localeutil.h"
473#include "stringlib/undef.h"
474
475#include "stringlib/ucs1lib.h"
476#include "stringlib/fastsearch.h"
477#include "stringlib/partition.h"
478#include "stringlib/split.h"
479#include "stringlib/count.h"
480#include "stringlib/find.h"
481#include "stringlib/find_max_char.h"
482#include "stringlib/localeutil.h"
483#include "stringlib/undef.h"
484
485#include "stringlib/ucs2lib.h"
486#include "stringlib/fastsearch.h"
487#include "stringlib/partition.h"
488#include "stringlib/split.h"
489#include "stringlib/count.h"
490#include "stringlib/find.h"
491#include "stringlib/find_max_char.h"
492#include "stringlib/localeutil.h"
493#include "stringlib/undef.h"
494
495#include "stringlib/ucs4lib.h"
496#include "stringlib/fastsearch.h"
497#include "stringlib/partition.h"
498#include "stringlib/split.h"
499#include "stringlib/count.h"
500#include "stringlib/find.h"
501#include "stringlib/find_max_char.h"
502#include "stringlib/localeutil.h"
503#include "stringlib/undef.h"
504
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200505#include "stringlib/unicodedefs.h"
506#include "stringlib/fastsearch.h"
507#include "stringlib/count.h"
508#include "stringlib/find.h"
509
Guido van Rossumd57fd912000-03-10 22:53:23 +0000510/* --- Unicode Object ----------------------------------------------------- */
511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200512static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200513fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200514
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200515Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
516 Py_ssize_t size, Py_UCS4 ch,
517 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200518{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200519 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
520
521 switch (kind) {
522 case PyUnicode_1BYTE_KIND:
523 {
524 Py_UCS1 ch1 = (Py_UCS1) ch;
525 if (ch1 == ch)
526 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
527 else
528 return -1;
529 }
530 case PyUnicode_2BYTE_KIND:
531 {
532 Py_UCS2 ch2 = (Py_UCS2) ch;
533 if (ch2 == ch)
534 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
535 else
536 return -1;
537 }
538 case PyUnicode_4BYTE_KIND:
539 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
540 default:
541 assert(0);
542 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200543 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200544}
545
Victor Stinnerfe226c02011-10-03 03:52:20 +0200546static PyObject*
547resize_compact(PyObject *unicode, Py_ssize_t length)
548{
549 Py_ssize_t char_size;
550 Py_ssize_t struct_size;
551 Py_ssize_t new_size;
552 int share_wstr;
553
554 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200555 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200556 if (PyUnicode_IS_COMPACT_ASCII(unicode))
557 struct_size = sizeof(PyASCIIObject);
558 else
559 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200560 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200561
562 _Py_DEC_REFTOTAL;
563 _Py_ForgetReference(unicode);
564
565 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
566 PyErr_NoMemory();
567 return NULL;
568 }
569 new_size = (struct_size + (length + 1) * char_size);
570
571 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
572 if (unicode == NULL) {
573 PyObject_Del(unicode);
574 PyErr_NoMemory();
575 return NULL;
576 }
577 _Py_NewReference(unicode);
578 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200579 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200580 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200581 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
582 _PyUnicode_WSTR_LENGTH(unicode) = length;
583 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200584 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
585 length, 0);
586 return unicode;
587}
588
Alexander Belopolsky40018472011-02-26 01:02:56 +0000589static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200590resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000591{
Victor Stinner95663112011-10-04 01:03:50 +0200592 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200593 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200594 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000595
Victor Stinner95663112011-10-04 01:03:50 +0200596 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200597
598 if (PyUnicode_IS_READY(unicode)) {
599 Py_ssize_t char_size;
600 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200601 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200602 void *data;
603
604 data = _PyUnicode_DATA_ANY(unicode);
605 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200606 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200607 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
608 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200609 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
610 {
611 PyObject_DEL(_PyUnicode_UTF8(unicode));
612 _PyUnicode_UTF8(unicode) = NULL;
613 _PyUnicode_UTF8_LENGTH(unicode) = 0;
614 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200615
616 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
617 PyErr_NoMemory();
618 return -1;
619 }
620 new_size = (length + 1) * char_size;
621
622 data = (PyObject *)PyObject_REALLOC(data, new_size);
623 if (data == NULL) {
624 PyErr_NoMemory();
625 return -1;
626 }
627 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200628 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200629 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200630 _PyUnicode_WSTR_LENGTH(unicode) = length;
631 }
632 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200633 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200634 _PyUnicode_UTF8_LENGTH(unicode) = length;
635 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200636 _PyUnicode_LENGTH(unicode) = length;
637 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200638 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200639 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200640 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200641 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200642 }
Victor Stinner95663112011-10-04 01:03:50 +0200643 assert(_PyUnicode_WSTR(unicode) != NULL);
644
645 /* check for integer overflow */
646 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
647 PyErr_NoMemory();
648 return -1;
649 }
650 wstr = _PyUnicode_WSTR(unicode);
651 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
652 if (!wstr) {
653 PyErr_NoMemory();
654 return -1;
655 }
656 _PyUnicode_WSTR(unicode) = wstr;
657 _PyUnicode_WSTR(unicode)[length] = 0;
658 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200659 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000660 return 0;
661}
662
Victor Stinnerfe226c02011-10-03 03:52:20 +0200663static PyObject*
664resize_copy(PyObject *unicode, Py_ssize_t length)
665{
666 Py_ssize_t copy_length;
667 if (PyUnicode_IS_COMPACT(unicode)) {
668 PyObject *copy;
669 assert(PyUnicode_IS_READY(unicode));
670
671 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
672 if (copy == NULL)
673 return NULL;
674
675 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200676 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200677 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200678 }
679 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200680 PyObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200681 assert(_PyUnicode_WSTR(unicode) != NULL);
682 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200683 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200684 if (w == NULL)
685 return NULL;
686 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
687 copy_length = Py_MIN(copy_length, length);
688 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
689 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200690 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200691 }
692}
693
Guido van Rossumd57fd912000-03-10 22:53:23 +0000694/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000695 Ux0000 terminated; some code (e.g. new_identifier)
696 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000697
698 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000699 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000700
701*/
702
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200703#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200704static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200705#endif
706
Alexander Belopolsky40018472011-02-26 01:02:56 +0000707static PyUnicodeObject *
708_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000709{
710 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200711 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000712
Thomas Wouters477c8d52006-05-27 19:21:47 +0000713 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000714 if (length == 0 && unicode_empty != NULL) {
715 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200716 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000717 }
718
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000719 /* Ensure we won't overflow the size. */
720 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
721 return (PyUnicodeObject *)PyErr_NoMemory();
722 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200723 if (length < 0) {
724 PyErr_SetString(PyExc_SystemError,
725 "Negative size passed to _PyUnicode_New");
726 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000727 }
728
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200729#ifdef Py_DEBUG
730 ++unicode_old_new_calls;
731#endif
732
733 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
734 if (unicode == NULL)
735 return NULL;
736 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
737 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
738 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000739 PyErr_NoMemory();
740 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000741 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200742
Jeremy Hyltond8082792003-09-16 19:41:39 +0000743 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000744 * the caller fails before initializing str -- unicode_resize()
745 * reads str[0], and the Keep-Alive optimization can keep memory
746 * allocated for str alive across a call to unicode_dealloc(unicode).
747 * We don't want unicode_resize to read uninitialized memory in
748 * that case.
749 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200750 _PyUnicode_WSTR(unicode)[0] = 0;
751 _PyUnicode_WSTR(unicode)[length] = 0;
752 _PyUnicode_WSTR_LENGTH(unicode) = length;
753 _PyUnicode_HASH(unicode) = -1;
754 _PyUnicode_STATE(unicode).interned = 0;
755 _PyUnicode_STATE(unicode).kind = 0;
756 _PyUnicode_STATE(unicode).compact = 0;
757 _PyUnicode_STATE(unicode).ready = 0;
758 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200759 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200760 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200761 _PyUnicode_UTF8(unicode) = NULL;
762 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100763 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000764 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000765
Benjamin Peterson29060642009-01-31 22:14:21 +0000766 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000767 /* XXX UNREF/NEWREF interface should be more symmetrical */
768 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000769 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000770 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000771 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000772}
773
Victor Stinnerf42dc442011-10-02 23:33:16 +0200774static const char*
775unicode_kind_name(PyObject *unicode)
776{
Victor Stinner42dfd712011-10-03 14:41:45 +0200777 /* don't check consistency: unicode_kind_name() is called from
778 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200779 if (!PyUnicode_IS_COMPACT(unicode))
780 {
781 if (!PyUnicode_IS_READY(unicode))
782 return "wstr";
783 switch(PyUnicode_KIND(unicode))
784 {
785 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200786 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200787 return "legacy ascii";
788 else
789 return "legacy latin1";
790 case PyUnicode_2BYTE_KIND:
791 return "legacy UCS2";
792 case PyUnicode_4BYTE_KIND:
793 return "legacy UCS4";
794 default:
795 return "<legacy invalid kind>";
796 }
797 }
798 assert(PyUnicode_IS_READY(unicode));
799 switch(PyUnicode_KIND(unicode))
800 {
801 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200802 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200803 return "ascii";
804 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200805 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200806 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200807 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200808 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200809 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200810 default:
811 return "<invalid compact kind>";
812 }
813}
814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200815#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200816static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200817
818/* Functions wrapping macros for use in debugger */
819char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200820 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200821}
822
823void *_PyUnicode_compact_data(void *unicode) {
824 return _PyUnicode_COMPACT_DATA(unicode);
825}
826void *_PyUnicode_data(void *unicode){
827 printf("obj %p\n", unicode);
828 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
829 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
830 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
831 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
832 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
833 return PyUnicode_DATA(unicode);
834}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200835
836void
837_PyUnicode_Dump(PyObject *op)
838{
839 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200840 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
841 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
842 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200843
Victor Stinnera849a4b2011-10-03 12:12:11 +0200844 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200845 {
846 if (ascii->state.ascii)
847 data = (ascii + 1);
848 else
849 data = (compact + 1);
850 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200851 else
852 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200853 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
854
Victor Stinnera849a4b2011-10-03 12:12:11 +0200855 if (ascii->wstr == data)
856 printf("shared ");
857 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200858
Victor Stinnera3b334d2011-10-03 13:53:37 +0200859 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200860 printf(" (%zu), ", compact->wstr_length);
861 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
862 printf("shared ");
863 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200864 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200865 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200866}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200867#endif
868
869PyObject *
870PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
871{
872 PyObject *obj;
873 PyCompactUnicodeObject *unicode;
874 void *data;
875 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200876 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200877 Py_ssize_t char_size;
878 Py_ssize_t struct_size;
879
880 /* Optimization for empty strings */
881 if (size == 0 && unicode_empty != NULL) {
882 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200883 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200884 }
885
886#ifdef Py_DEBUG
887 ++unicode_new_new_calls;
888#endif
889
Victor Stinner9e9d6892011-10-04 01:02:02 +0200890 is_ascii = 0;
891 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200892 struct_size = sizeof(PyCompactUnicodeObject);
893 if (maxchar < 128) {
894 kind_state = PyUnicode_1BYTE_KIND;
895 char_size = 1;
896 is_ascii = 1;
897 struct_size = sizeof(PyASCIIObject);
898 }
899 else if (maxchar < 256) {
900 kind_state = PyUnicode_1BYTE_KIND;
901 char_size = 1;
902 }
903 else if (maxchar < 65536) {
904 kind_state = PyUnicode_2BYTE_KIND;
905 char_size = 2;
906 if (sizeof(wchar_t) == 2)
907 is_sharing = 1;
908 }
909 else {
910 kind_state = PyUnicode_4BYTE_KIND;
911 char_size = 4;
912 if (sizeof(wchar_t) == 4)
913 is_sharing = 1;
914 }
915
916 /* Ensure we won't overflow the size. */
917 if (size < 0) {
918 PyErr_SetString(PyExc_SystemError,
919 "Negative size passed to PyUnicode_New");
920 return NULL;
921 }
922 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
923 return PyErr_NoMemory();
924
925 /* Duplicated allocation code from _PyObject_New() instead of a call to
926 * PyObject_New() so we are able to allocate space for the object and
927 * it's data buffer.
928 */
929 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
930 if (obj == NULL)
931 return PyErr_NoMemory();
932 obj = PyObject_INIT(obj, &PyUnicode_Type);
933 if (obj == NULL)
934 return NULL;
935
936 unicode = (PyCompactUnicodeObject *)obj;
937 if (is_ascii)
938 data = ((PyASCIIObject*)obj) + 1;
939 else
940 data = unicode + 1;
941 _PyUnicode_LENGTH(unicode) = size;
942 _PyUnicode_HASH(unicode) = -1;
943 _PyUnicode_STATE(unicode).interned = 0;
944 _PyUnicode_STATE(unicode).kind = kind_state;
945 _PyUnicode_STATE(unicode).compact = 1;
946 _PyUnicode_STATE(unicode).ready = 1;
947 _PyUnicode_STATE(unicode).ascii = is_ascii;
948 if (is_ascii) {
949 ((char*)data)[size] = 0;
950 _PyUnicode_WSTR(unicode) = NULL;
951 }
952 else if (kind_state == PyUnicode_1BYTE_KIND) {
953 ((char*)data)[size] = 0;
954 _PyUnicode_WSTR(unicode) = NULL;
955 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200956 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200957 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200958 }
959 else {
960 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200961 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200962 if (kind_state == PyUnicode_2BYTE_KIND)
963 ((Py_UCS2*)data)[size] = 0;
964 else /* kind_state == PyUnicode_4BYTE_KIND */
965 ((Py_UCS4*)data)[size] = 0;
966 if (is_sharing) {
967 _PyUnicode_WSTR_LENGTH(unicode) = size;
968 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
969 }
970 else {
971 _PyUnicode_WSTR_LENGTH(unicode) = 0;
972 _PyUnicode_WSTR(unicode) = NULL;
973 }
974 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100975 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200976 return obj;
977}
978
979#if SIZEOF_WCHAR_T == 2
980/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
981 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +0200982 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200983
984 This function assumes that unicode can hold one more code point than wstr
985 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200986static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200988 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200989{
990 const wchar_t *iter;
991 Py_UCS4 *ucs4_out;
992
Victor Stinner910337b2011-10-03 03:20:16 +0200993 assert(unicode != NULL);
994 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200995 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
996 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
997
998 for (iter = begin; iter < end; ) {
999 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1000 _PyUnicode_GET_LENGTH(unicode)));
1001 if (*iter >= 0xD800 && *iter <= 0xDBFF
1002 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1003 {
1004 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
1005 iter += 2;
1006 }
1007 else {
1008 *ucs4_out++ = *iter;
1009 iter++;
1010 }
1011 }
1012 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1013 _PyUnicode_GET_LENGTH(unicode)));
1014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001015}
1016#endif
1017
Victor Stinnercd9950f2011-10-02 00:34:53 +02001018static int
1019_PyUnicode_Dirty(PyObject *unicode)
1020{
Victor Stinner910337b2011-10-03 03:20:16 +02001021 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001022 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001023 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001024 "Cannot modify a string having more than 1 reference");
1025 return -1;
1026 }
1027 _PyUnicode_DIRTY(unicode);
1028 return 0;
1029}
1030
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001031static int
1032_copy_characters(PyObject *to, Py_ssize_t to_start,
1033 PyObject *from, Py_ssize_t from_start,
1034 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001035{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001036 unsigned int from_kind, to_kind;
1037 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001038 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001039
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001040 assert(PyUnicode_Check(from));
1041 assert(PyUnicode_Check(to));
1042 assert(PyUnicode_IS_READY(from));
1043 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001044
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001045 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1046 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1047 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001048
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001049 if (how_many == 0)
1050 return 0;
1051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001053 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001055 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001056
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001057#ifdef Py_DEBUG
1058 if (!check_maxchar
1059 && (from_kind > to_kind
1060 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001061 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001062 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1063 Py_UCS4 ch;
1064 Py_ssize_t i;
1065 for (i=0; i < how_many; i++) {
1066 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1067 assert(ch <= to_maxchar);
1068 }
1069 }
1070#endif
1071 fast = (from_kind == to_kind);
1072 if (check_maxchar
1073 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1074 {
1075 /* deny latin1 => ascii */
1076 fast = 0;
1077 }
1078
1079 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001080 Py_MEMCPY((char*)to_data + to_kind * to_start,
1081 (char*)from_data + from_kind * from_start,
1082 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001083 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001084 else if (from_kind == PyUnicode_1BYTE_KIND
1085 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001086 {
1087 _PyUnicode_CONVERT_BYTES(
1088 Py_UCS1, Py_UCS2,
1089 PyUnicode_1BYTE_DATA(from) + from_start,
1090 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1091 PyUnicode_2BYTE_DATA(to) + to_start
1092 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001093 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001094 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001095 && to_kind == PyUnicode_4BYTE_KIND)
1096 {
1097 _PyUnicode_CONVERT_BYTES(
1098 Py_UCS1, Py_UCS4,
1099 PyUnicode_1BYTE_DATA(from) + from_start,
1100 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1101 PyUnicode_4BYTE_DATA(to) + to_start
1102 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001103 }
1104 else if (from_kind == PyUnicode_2BYTE_KIND
1105 && to_kind == PyUnicode_4BYTE_KIND)
1106 {
1107 _PyUnicode_CONVERT_BYTES(
1108 Py_UCS2, Py_UCS4,
1109 PyUnicode_2BYTE_DATA(from) + from_start,
1110 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1111 PyUnicode_4BYTE_DATA(to) + to_start
1112 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001113 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001114 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001115 /* check if max_char(from substring) <= max_char(to) */
1116 if (from_kind > to_kind
1117 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001118 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001119 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001120 /* slow path to check for character overflow */
1121 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001122 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001123 Py_ssize_t i;
1124
Victor Stinner56c161a2011-10-06 02:47:11 +02001125#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001126 for (i=0; i < how_many; i++) {
1127 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001128 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001129 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1130 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001131#else
1132 if (!check_maxchar) {
1133 for (i=0; i < how_many; i++) {
1134 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1135 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1136 }
1137 }
1138 else {
1139 for (i=0; i < how_many; i++) {
1140 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1141 if (ch > to_maxchar)
1142 return 1;
1143 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1144 }
1145 }
1146#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001147 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001148 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001149 assert(0 && "inconsistent state");
1150 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001151 }
1152 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001153 return 0;
1154}
1155
1156static void
1157copy_characters(PyObject *to, Py_ssize_t to_start,
1158 PyObject *from, Py_ssize_t from_start,
1159 Py_ssize_t how_many)
1160{
1161 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1162}
1163
1164Py_ssize_t
1165PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1166 PyObject *from, Py_ssize_t from_start,
1167 Py_ssize_t how_many)
1168{
1169 int err;
1170
1171 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1172 PyErr_BadInternalCall();
1173 return -1;
1174 }
1175
1176 if (PyUnicode_READY(from))
1177 return -1;
1178 if (PyUnicode_READY(to))
1179 return -1;
1180
1181 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1182 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1183 PyErr_Format(PyExc_SystemError,
1184 "Cannot write %zi characters at %zi "
1185 "in a string of %zi characters",
1186 how_many, to_start, PyUnicode_GET_LENGTH(to));
1187 return -1;
1188 }
1189
1190 if (how_many == 0)
1191 return 0;
1192
1193 if (_PyUnicode_Dirty(to))
1194 return -1;
1195
1196 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1197 if (err) {
1198 PyErr_Format(PyExc_SystemError,
1199 "Cannot copy %s characters "
1200 "into a string of %s characters",
1201 unicode_kind_name(from),
1202 unicode_kind_name(to));
1203 return -1;
1204 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001205 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001206}
1207
Victor Stinner17222162011-09-28 22:15:37 +02001208/* Find the maximum code point and count the number of surrogate pairs so a
1209 correct string length can be computed before converting a string to UCS4.
1210 This function counts single surrogates as a character and not as a pair.
1211
1212 Return 0 on success, or -1 on error. */
1213static int
1214find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1215 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001216{
1217 const wchar_t *iter;
1218
Victor Stinnerc53be962011-10-02 21:33:54 +02001219 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001220 *num_surrogates = 0;
1221 *maxchar = 0;
1222
1223 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001224 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001225 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001226#if SIZEOF_WCHAR_T != 2
1227 if (*maxchar >= 0x10000)
1228 return 0;
1229#endif
1230 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001231#if SIZEOF_WCHAR_T == 2
1232 if (*iter >= 0xD800 && *iter <= 0xDBFF
1233 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1234 {
1235 Py_UCS4 surrogate_val;
1236 surrogate_val = (((iter[0] & 0x3FF)<<10)
1237 | (iter[1] & 0x3FF)) + 0x10000;
1238 ++(*num_surrogates);
1239 if (surrogate_val > *maxchar)
1240 *maxchar = surrogate_val;
1241 iter += 2;
1242 }
1243 else
1244 iter++;
1245#else
1246 iter++;
1247#endif
1248 }
1249 return 0;
1250}
1251
1252#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001253static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001254#endif
1255
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001256static int
1257unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001258{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001259 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001260 wchar_t *end;
1261 Py_UCS4 maxchar = 0;
1262 Py_ssize_t num_surrogates;
1263#if SIZEOF_WCHAR_T == 2
1264 Py_ssize_t length_wo_surrogates;
1265#endif
1266
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001267 assert(p_obj != NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001268 unicode = *p_obj;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001269
Georg Brandl7597add2011-10-05 16:36:47 +02001270 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001271 strings were created using _PyObject_New() and where no canonical
1272 representation (the str field) has been set yet aka strings
1273 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001274 assert(_PyUnicode_CHECK(unicode));
1275 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001276 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001277 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001278 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001279 /* Actually, it should neither be interned nor be anything else: */
1280 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001281
1282#ifdef Py_DEBUG
1283 ++unicode_ready_calls;
1284#endif
1285
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001286#ifdef Py_DEBUG
1287 assert(!replace || Py_REFCNT(unicode) == 1);
1288#else
1289 if (replace && Py_REFCNT(unicode) != 1)
1290 replace = 0;
1291#endif
1292 if (replace) {
1293 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1294 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1295 /* Optimization for empty strings */
1296 if (len == 0) {
1297 Py_INCREF(unicode_empty);
1298 Py_DECREF(*p_obj);
1299 *p_obj = unicode_empty;
1300 return 0;
1301 }
1302 if (len == 1 && wstr[0] < 256) {
1303 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1304 if (latin1_char == NULL)
1305 return -1;
1306 Py_DECREF(*p_obj);
1307 *p_obj = latin1_char;
1308 return 0;
1309 }
1310 }
1311
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001312 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001313 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001314 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001315 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316
1317 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001318 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1319 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320 PyErr_NoMemory();
1321 return -1;
1322 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001323 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324 _PyUnicode_WSTR(unicode), end,
1325 PyUnicode_1BYTE_DATA(unicode));
1326 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1327 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1328 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1329 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001330 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001331 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001332 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001333 }
1334 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001335 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001336 _PyUnicode_UTF8(unicode) = NULL;
1337 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001338 }
1339 PyObject_FREE(_PyUnicode_WSTR(unicode));
1340 _PyUnicode_WSTR(unicode) = NULL;
1341 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1342 }
1343 /* In this case we might have to convert down from 4-byte native
1344 wchar_t to 2-byte unicode. */
1345 else if (maxchar < 65536) {
1346 assert(num_surrogates == 0 &&
1347 "FindMaxCharAndNumSurrogatePairs() messed up");
1348
Victor Stinner506f5922011-09-28 22:34:18 +02001349#if SIZEOF_WCHAR_T == 2
1350 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001351 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001352 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1353 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1354 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001355 _PyUnicode_UTF8(unicode) = NULL;
1356 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001357#else
1358 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001359 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001360 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001361 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001362 PyErr_NoMemory();
1363 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001364 }
Victor Stinner506f5922011-09-28 22:34:18 +02001365 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1366 _PyUnicode_WSTR(unicode), end,
1367 PyUnicode_2BYTE_DATA(unicode));
1368 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1369 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1370 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001371 _PyUnicode_UTF8(unicode) = NULL;
1372 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001373 PyObject_FREE(_PyUnicode_WSTR(unicode));
1374 _PyUnicode_WSTR(unicode) = NULL;
1375 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1376#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001377 }
1378 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1379 else {
1380#if SIZEOF_WCHAR_T == 2
1381 /* in case the native representation is 2-bytes, we need to allocate a
1382 new normalized 4-byte version. */
1383 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001384 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1385 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001386 PyErr_NoMemory();
1387 return -1;
1388 }
1389 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1390 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001391 _PyUnicode_UTF8(unicode) = NULL;
1392 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001393 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1394 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001395 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001396 PyObject_FREE(_PyUnicode_WSTR(unicode));
1397 _PyUnicode_WSTR(unicode) = NULL;
1398 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1399#else
1400 assert(num_surrogates == 0);
1401
Victor Stinnerc3c74152011-10-02 20:39:55 +02001402 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001403 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001404 _PyUnicode_UTF8(unicode) = NULL;
1405 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1407#endif
1408 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1409 }
1410 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001411 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001412 return 0;
1413}
1414
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001415int
1416_PyUnicode_ReadyReplace(PyObject **op)
1417{
1418 return unicode_ready(op, 1);
1419}
1420
1421int
1422_PyUnicode_Ready(PyObject *op)
1423{
1424 return unicode_ready(&op, 0);
1425}
1426
Alexander Belopolsky40018472011-02-26 01:02:56 +00001427static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001428unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001429{
Walter Dörwald16807132007-05-25 13:52:07 +00001430 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001431 case SSTATE_NOT_INTERNED:
1432 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001433
Benjamin Peterson29060642009-01-31 22:14:21 +00001434 case SSTATE_INTERNED_MORTAL:
1435 /* revive dead object temporarily for DelItem */
1436 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001437 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001438 Py_FatalError(
1439 "deletion of interned string failed");
1440 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001441
Benjamin Peterson29060642009-01-31 22:14:21 +00001442 case SSTATE_INTERNED_IMMORTAL:
1443 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001444
Benjamin Peterson29060642009-01-31 22:14:21 +00001445 default:
1446 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001447 }
1448
Victor Stinner03490912011-10-03 23:45:12 +02001449 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001450 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001451 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001452 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001453
1454 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01001455 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001456 }
1457 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001458 if (_PyUnicode_DATA_ANY(unicode))
1459 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Victor Stinner7931d9a2011-11-04 00:22:48 +01001460 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001461 }
1462}
1463
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001464#ifdef Py_DEBUG
1465static int
1466unicode_is_singleton(PyObject *unicode)
1467{
1468 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1469 if (unicode == unicode_empty)
1470 return 1;
1471 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1472 {
1473 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1474 if (ch < 256 && unicode_latin1[ch] == unicode)
1475 return 1;
1476 }
1477 return 0;
1478}
1479#endif
1480
Alexander Belopolsky40018472011-02-26 01:02:56 +00001481static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001482unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001483{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001484 if (Py_REFCNT(unicode) != 1)
1485 return 0;
1486 if (PyUnicode_CHECK_INTERNED(unicode))
1487 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001488#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001489 /* singleton refcount is greater than 1 */
1490 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001491#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001492 return 1;
1493}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001494
Victor Stinnerfe226c02011-10-03 03:52:20 +02001495static int
1496unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1497{
1498 PyObject *unicode;
1499 Py_ssize_t old_length;
1500
1501 assert(p_unicode != NULL);
1502 unicode = *p_unicode;
1503
1504 assert(unicode != NULL);
1505 assert(PyUnicode_Check(unicode));
1506 assert(0 <= length);
1507
Victor Stinner910337b2011-10-03 03:20:16 +02001508 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001509 old_length = PyUnicode_WSTR_LENGTH(unicode);
1510 else
1511 old_length = PyUnicode_GET_LENGTH(unicode);
1512 if (old_length == length)
1513 return 0;
1514
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001515 if (length == 0) {
1516 Py_DECREF(*p_unicode);
1517 *p_unicode = unicode_empty;
1518 Py_INCREF(*p_unicode);
1519 return 0;
1520 }
1521
Victor Stinnerfe226c02011-10-03 03:52:20 +02001522 if (!unicode_resizable(unicode)) {
1523 PyObject *copy = resize_copy(unicode, length);
1524 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001525 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001526 Py_DECREF(*p_unicode);
1527 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001528 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001529 }
1530
Victor Stinnerfe226c02011-10-03 03:52:20 +02001531 if (PyUnicode_IS_COMPACT(unicode)) {
1532 *p_unicode = resize_compact(unicode, length);
1533 if (*p_unicode == NULL)
1534 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001535 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001536 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001537 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001538 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001539}
1540
Alexander Belopolsky40018472011-02-26 01:02:56 +00001541int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001542PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001543{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001544 PyObject *unicode;
1545 if (p_unicode == NULL) {
1546 PyErr_BadInternalCall();
1547 return -1;
1548 }
1549 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001550 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001551 {
1552 PyErr_BadInternalCall();
1553 return -1;
1554 }
1555 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001556}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001557
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001558static int
1559unicode_widen(PyObject **p_unicode, int maxchar)
1560{
1561 PyObject *result;
1562 assert(PyUnicode_IS_READY(*p_unicode));
1563 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1564 return 0;
1565 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1566 maxchar);
1567 if (result == NULL)
1568 return -1;
1569 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1570 PyUnicode_GET_LENGTH(*p_unicode));
1571 Py_DECREF(*p_unicode);
1572 *p_unicode = result;
1573 return 0;
1574}
1575
1576static int
1577unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1578 Py_UCS4 ch)
1579{
1580 if (unicode_widen(p_unicode, ch) < 0)
1581 return -1;
1582 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1583 PyUnicode_DATA(*p_unicode),
1584 (*pos)++, ch);
1585 return 0;
1586}
1587
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001588static PyObject*
1589get_latin1_char(unsigned char ch)
1590{
Victor Stinnera464fc12011-10-02 20:39:30 +02001591 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001592 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001593 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001594 if (!unicode)
1595 return NULL;
1596 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001597 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001598 unicode_latin1[ch] = unicode;
1599 }
1600 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001601 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001602}
1603
Alexander Belopolsky40018472011-02-26 01:02:56 +00001604PyObject *
1605PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001606{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001607 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001608 Py_UCS4 maxchar = 0;
1609 Py_ssize_t num_surrogates;
1610
1611 if (u == NULL)
1612 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001613
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001614 /* If the Unicode data is known at construction time, we can apply
1615 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001616
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001617 /* Optimization for empty strings */
1618 if (size == 0 && unicode_empty != NULL) {
1619 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001620 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001621 }
Tim Petersced69f82003-09-16 20:30:58 +00001622
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001623 /* Single character Unicode objects in the Latin-1 range are
1624 shared when using this constructor */
1625 if (size == 1 && *u < 256)
1626 return get_latin1_char((unsigned char)*u);
1627
1628 /* If not empty and not single character, copy the Unicode data
1629 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001630 if (find_maxchar_surrogates(u, u + size,
1631 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001632 return NULL;
1633
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001634 unicode = PyUnicode_New(size - num_surrogates,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001635 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001636 if (!unicode)
1637 return NULL;
1638
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001639 switch (PyUnicode_KIND(unicode)) {
1640 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001641 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001642 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1643 break;
1644 case PyUnicode_2BYTE_KIND:
1645#if Py_UNICODE_SIZE == 2
1646 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1647#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001648 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001649 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1650#endif
1651 break;
1652 case PyUnicode_4BYTE_KIND:
1653#if SIZEOF_WCHAR_T == 2
1654 /* This is the only case which has to process surrogates, thus
1655 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001656 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657#else
1658 assert(num_surrogates == 0);
1659 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1660#endif
1661 break;
1662 default:
1663 assert(0 && "Impossible state");
1664 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001665
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001666 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001667 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001668}
1669
Alexander Belopolsky40018472011-02-26 01:02:56 +00001670PyObject *
1671PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001672{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001673 if (size < 0) {
1674 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001675 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001676 return NULL;
1677 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001678
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001679 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001680 some optimizations which share commonly used objects.
1681 Also, this means the input must be UTF-8, so fall back to the
1682 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001683 if (u != NULL) {
1684
Benjamin Peterson29060642009-01-31 22:14:21 +00001685 /* Optimization for empty strings */
1686 if (size == 0 && unicode_empty != NULL) {
1687 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001688 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001689 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001690
1691 /* Single characters are shared when using this constructor.
1692 Restrict to ASCII, since the input must be UTF-8. */
Victor Stinner9faa3842011-10-23 20:06:00 +02001693 if (size == 1 && (unsigned char)*u < 128)
1694 return get_latin1_char((unsigned char)*u);
Martin v. Löwis9c121062007-08-05 20:26:11 +00001695
1696 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001697 }
1698
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001699 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001700}
1701
Alexander Belopolsky40018472011-02-26 01:02:56 +00001702PyObject *
1703PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001704{
1705 size_t size = strlen(u);
1706 if (size > PY_SSIZE_T_MAX) {
1707 PyErr_SetString(PyExc_OverflowError, "input too long");
1708 return NULL;
1709 }
1710
1711 return PyUnicode_FromStringAndSize(u, size);
1712}
1713
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001714PyObject *
1715_PyUnicode_FromId(_Py_Identifier *id)
1716{
1717 if (!id->object) {
1718 id->object = PyUnicode_FromString(id->string);
1719 if (!id->object)
1720 return NULL;
1721 PyUnicode_InternInPlace(&id->object);
1722 assert(!id->next);
1723 id->next = static_strings;
1724 static_strings = id;
1725 }
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;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003625 Py_ssize_t outsize = PyUnicode_GET_LENGTH(*output);
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;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003630 Py_ssize_t replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003631 int res = -1;
3632
3633 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003634 *errorHandler = PyCodec_LookupError(errors);
3635 if (*errorHandler == NULL)
3636 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003637 }
3638
Victor Stinner554f3f02010-06-16 23:33:54 +00003639 make_decode_exception(exceptionObject,
3640 encoding,
3641 *input, *inend - *input,
3642 *startinpos, *endinpos,
3643 reason);
3644 if (*exceptionObject == NULL)
3645 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003646
3647 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3648 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003649 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003650 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003651 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003652 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003653 }
3654 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003655 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003656 if (PyUnicode_READY(repunicode) < 0)
3657 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003658
3659 /* Copy back the bytes variables, which might have been modified by the
3660 callback */
3661 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3662 if (!inputobj)
3663 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003664 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003665 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003666 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003667 *input = PyBytes_AS_STRING(inputobj);
3668 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003669 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003670 /* we can DECREF safely, as the exception has another reference,
3671 so the object won't go away. */
3672 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003673
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003674 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003675 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003676 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003677 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3678 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003679 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003680
3681 /* need more space? (at least enough for what we
3682 have+the replacement+the rest of the string (starting
3683 at the new input position), so we won't have to check space
3684 when there are no errors in the rest of the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003685 replen = PyUnicode_GET_LENGTH(repunicode);
3686 requiredsize = *outpos + replen + insize-newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003687 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003688 if (requiredsize<2*outsize)
3689 requiredsize = 2*outsize;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003690 if (unicode_resize(output, requiredsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003691 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003692 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003693 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
3694 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003695 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003696 *inptr = *input + newpos;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003697 PyUnicode_CopyCharacters(*output, *outpos, repunicode, 0, replen);
3698 *outpos += replen;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003699
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003700 /* we made it! */
3701 res = 0;
3702
Benjamin Peterson29060642009-01-31 22:14:21 +00003703 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003704 Py_XDECREF(restuple);
3705 return res;
3706}
3707
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003708/* --- UTF-7 Codec -------------------------------------------------------- */
3709
Antoine Pitrou244651a2009-05-04 18:56:13 +00003710/* See RFC2152 for details. We encode conservatively and decode liberally. */
3711
3712/* Three simple macros defining base-64. */
3713
3714/* Is c a base-64 character? */
3715
3716#define IS_BASE64(c) \
3717 (((c) >= 'A' && (c) <= 'Z') || \
3718 ((c) >= 'a' && (c) <= 'z') || \
3719 ((c) >= '0' && (c) <= '9') || \
3720 (c) == '+' || (c) == '/')
3721
3722/* given that c is a base-64 character, what is its base-64 value? */
3723
3724#define FROM_BASE64(c) \
3725 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3726 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3727 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3728 (c) == '+' ? 62 : 63)
3729
3730/* What is the base-64 character of the bottom 6 bits of n? */
3731
3732#define TO_BASE64(n) \
3733 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3734
3735/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3736 * decoded as itself. We are permissive on decoding; the only ASCII
3737 * byte not decoding to itself is the + which begins a base64
3738 * string. */
3739
3740#define DECODE_DIRECT(c) \
3741 ((c) <= 127 && (c) != '+')
3742
3743/* The UTF-7 encoder treats ASCII characters differently according to
3744 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3745 * the above). See RFC2152. This array identifies these different
3746 * sets:
3747 * 0 : "Set D"
3748 * alphanumeric and '(),-./:?
3749 * 1 : "Set O"
3750 * !"#$%&*;<=>@[]^_`{|}
3751 * 2 : "whitespace"
3752 * ht nl cr sp
3753 * 3 : special (must be base64 encoded)
3754 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3755 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003756
Tim Petersced69f82003-09-16 20:30:58 +00003757static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003758char utf7_category[128] = {
3759/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3760 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3761/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3762 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3763/* sp ! " # $ % & ' ( ) * + , - . / */
3764 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3765/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3766 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3767/* @ A B C D E F G H I J K L M N O */
3768 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3769/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3770 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3771/* ` a b c d e f g h i j k l m n o */
3772 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3773/* p q r s t u v w x y z { | } ~ del */
3774 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003775};
3776
Antoine Pitrou244651a2009-05-04 18:56:13 +00003777/* ENCODE_DIRECT: this character should be encoded as itself. The
3778 * answer depends on whether we are encoding set O as itself, and also
3779 * on whether we are encoding whitespace as itself. RFC2152 makes it
3780 * clear that the answers to these questions vary between
3781 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003782
Antoine Pitrou244651a2009-05-04 18:56:13 +00003783#define ENCODE_DIRECT(c, directO, directWS) \
3784 ((c) < 128 && (c) > 0 && \
3785 ((utf7_category[(c)] == 0) || \
3786 (directWS && (utf7_category[(c)] == 2)) || \
3787 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003788
Alexander Belopolsky40018472011-02-26 01:02:56 +00003789PyObject *
3790PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003791 Py_ssize_t size,
3792 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003793{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003794 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3795}
3796
Antoine Pitrou244651a2009-05-04 18:56:13 +00003797/* The decoder. The only state we preserve is our read position,
3798 * i.e. how many characters we have consumed. So if we end in the
3799 * middle of a shift sequence we have to back off the read position
3800 * and the output to the beginning of the sequence, otherwise we lose
3801 * all the shift state (seen bits, number of bits seen, high
3802 * surrogate). */
3803
Alexander Belopolsky40018472011-02-26 01:02:56 +00003804PyObject *
3805PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003806 Py_ssize_t size,
3807 const char *errors,
3808 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003809{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003810 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003811 Py_ssize_t startinpos;
3812 Py_ssize_t endinpos;
3813 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003814 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003815 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003816 const char *errmsg = "";
3817 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003818 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003819 unsigned int base64bits = 0;
3820 unsigned long base64buffer = 0;
3821 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003822 PyObject *errorHandler = NULL;
3823 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003824
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003825 /* Start off assuming it's all ASCII. Widen later as necessary. */
3826 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003827 if (!unicode)
3828 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003829 if (size == 0) {
3830 if (consumed)
3831 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003832 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003833 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003834
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003835 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003836 e = s + size;
3837
3838 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003839 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003840 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003841 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003842
Antoine Pitrou244651a2009-05-04 18:56:13 +00003843 if (inShift) { /* in a base-64 section */
3844 if (IS_BASE64(ch)) { /* consume a base-64 character */
3845 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3846 base64bits += 6;
3847 s++;
3848 if (base64bits >= 16) {
3849 /* we have enough bits for a UTF-16 value */
3850 Py_UNICODE outCh = (Py_UNICODE)
3851 (base64buffer >> (base64bits-16));
3852 base64bits -= 16;
3853 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3854 if (surrogate) {
3855 /* expecting a second surrogate */
3856 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003857 Py_UCS4 ch2 = (((surrogate & 0x3FF)<<10)
3858 | (outCh & 0x3FF)) + 0x10000;
3859 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
3860 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003861 surrogate = 0;
3862 }
3863 else {
3864 surrogate = 0;
3865 errmsg = "second surrogate missing";
3866 goto utf7Error;
3867 }
3868 }
3869 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3870 /* first surrogate */
3871 surrogate = outCh;
3872 }
3873 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3874 errmsg = "unexpected second surrogate";
3875 goto utf7Error;
3876 }
3877 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003878 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
3879 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003880 }
3881 }
3882 }
3883 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003884 inShift = 0;
3885 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003886 if (surrogate) {
3887 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003888 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003889 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003890 if (base64bits > 0) { /* left-over bits */
3891 if (base64bits >= 6) {
3892 /* We've seen at least one base-64 character */
3893 errmsg = "partial character in shift sequence";
3894 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003895 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003896 else {
3897 /* Some bits remain; they should be zero */
3898 if (base64buffer != 0) {
3899 errmsg = "non-zero padding bits in shift sequence";
3900 goto utf7Error;
3901 }
3902 }
3903 }
3904 if (ch != '-') {
3905 /* '-' is absorbed; other terminating
3906 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003907 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3908 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003909 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003910 }
3911 }
3912 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003913 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003914 s++; /* consume '+' */
3915 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003916 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003917 if (unicode_putchar(&unicode, &outpos, '+') < 0)
3918 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003919 }
3920 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003921 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003922 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003923 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003924 }
3925 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003926 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003927 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3928 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003929 s++;
3930 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003931 else {
3932 startinpos = s-starts;
3933 s++;
3934 errmsg = "unexpected special character";
3935 goto utf7Error;
3936 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003937 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003938utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003939 endinpos = s-starts;
3940 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003941 errors, &errorHandler,
3942 "utf7", errmsg,
3943 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003944 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003945 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003946 }
3947
Antoine Pitrou244651a2009-05-04 18:56:13 +00003948 /* end of string */
3949
3950 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3951 /* if we're in an inconsistent state, that's an error */
3952 if (surrogate ||
3953 (base64bits >= 6) ||
3954 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003955 endinpos = size;
3956 if (unicode_decode_call_errorhandler(
3957 errors, &errorHandler,
3958 "utf7", "unterminated shift sequence",
3959 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003960 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00003961 goto onError;
3962 if (s < e)
3963 goto restart;
3964 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003965 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003966
3967 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003968 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003969 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003970 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003971 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003972 }
3973 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003974 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003975 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003976 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003977
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003978 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003979 goto onError;
3980
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003981 Py_XDECREF(errorHandler);
3982 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02003983#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02003984 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003985 Py_DECREF(unicode);
3986 return NULL;
3987 }
Victor Stinner17efeed2011-10-04 20:05:46 +02003988#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003989 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01003990 return unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003991
Benjamin Peterson29060642009-01-31 22:14:21 +00003992 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003993 Py_XDECREF(errorHandler);
3994 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003995 Py_DECREF(unicode);
3996 return NULL;
3997}
3998
3999
Alexander Belopolsky40018472011-02-26 01:02:56 +00004000PyObject *
4001PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004002 Py_ssize_t size,
4003 int base64SetO,
4004 int base64WhiteSpace,
4005 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004006{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004007 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004008 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00004009 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004010 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004011 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004012 unsigned int base64bits = 0;
4013 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004014 char * out;
4015 char * start;
4016
4017 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004018 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004019
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00004020 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004021 return PyErr_NoMemory();
4022
Antoine Pitrou244651a2009-05-04 18:56:13 +00004023 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004024 if (v == NULL)
4025 return NULL;
4026
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004027 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004028 for (;i < size; ++i) {
4029 Py_UNICODE ch = s[i];
4030
Antoine Pitrou244651a2009-05-04 18:56:13 +00004031 if (inShift) {
4032 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4033 /* shifting out */
4034 if (base64bits) { /* output remaining bits */
4035 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4036 base64buffer = 0;
4037 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004038 }
4039 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004040 /* Characters not in the BASE64 set implicitly unshift the sequence
4041 so no '-' is required, except if the character is itself a '-' */
4042 if (IS_BASE64(ch) || ch == '-') {
4043 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004044 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004045 *out++ = (char) ch;
4046 }
4047 else {
4048 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004049 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004050 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004051 else { /* not in a shift sequence */
4052 if (ch == '+') {
4053 *out++ = '+';
4054 *out++ = '-';
4055 }
4056 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4057 *out++ = (char) ch;
4058 }
4059 else {
4060 *out++ = '+';
4061 inShift = 1;
4062 goto encode_char;
4063 }
4064 }
4065 continue;
4066encode_char:
4067#ifdef Py_UNICODE_WIDE
4068 if (ch >= 0x10000) {
4069 /* code first surrogate */
4070 base64bits += 16;
4071 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4072 while (base64bits >= 6) {
4073 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4074 base64bits -= 6;
4075 }
4076 /* prepare second surrogate */
4077 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4078 }
4079#endif
4080 base64bits += 16;
4081 base64buffer = (base64buffer << 16) | ch;
4082 while (base64bits >= 6) {
4083 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4084 base64bits -= 6;
4085 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004086 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004087 if (base64bits)
4088 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4089 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004090 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004091 if (_PyBytes_Resize(&v, out - start) < 0)
4092 return NULL;
4093 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004094}
4095
Antoine Pitrou244651a2009-05-04 18:56:13 +00004096#undef IS_BASE64
4097#undef FROM_BASE64
4098#undef TO_BASE64
4099#undef DECODE_DIRECT
4100#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004101
Guido van Rossumd57fd912000-03-10 22:53:23 +00004102/* --- UTF-8 Codec -------------------------------------------------------- */
4103
Tim Petersced69f82003-09-16 20:30:58 +00004104static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004105char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004106 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4107 illegal prefix. See RFC 3629 for details */
4108 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4109 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004110 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004111 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4112 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4113 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4114 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004115 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4116 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 +00004117 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4118 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4120 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4121 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4122 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4123 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 +00004124};
4125
Alexander Belopolsky40018472011-02-26 01:02:56 +00004126PyObject *
4127PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004128 Py_ssize_t size,
4129 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004130{
Walter Dörwald69652032004-09-07 20:24:22 +00004131 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4132}
4133
Antoine Pitrouab868312009-01-10 15:40:25 +00004134/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4135#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4136
4137/* Mask to quickly check whether a C 'long' contains a
4138 non-ASCII, UTF8-encoded char. */
4139#if (SIZEOF_LONG == 8)
4140# define ASCII_CHAR_MASK 0x8080808080808080L
4141#elif (SIZEOF_LONG == 4)
4142# define ASCII_CHAR_MASK 0x80808080L
4143#else
4144# error C 'long' size should be either 4 or 8!
4145#endif
4146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004147/* Scans a UTF-8 string and returns the maximum character to be expected,
4148 the size of the decoded unicode string and if any major errors were
4149 encountered.
4150
4151 This function does check basic UTF-8 sanity, it does however NOT CHECK
4152 if the string contains surrogates, and if all continuation bytes are
4153 within the correct ranges, these checks are performed in
4154 PyUnicode_DecodeUTF8Stateful.
4155
4156 If it sets has_errors to 1, it means the value of unicode_size and max_char
4157 will be bogus and you should not rely on useful information in them.
4158 */
4159static Py_UCS4
4160utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4161 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4162 int *has_errors)
4163{
4164 Py_ssize_t n;
4165 Py_ssize_t char_count = 0;
4166 Py_UCS4 max_char = 127, new_max;
4167 Py_UCS4 upper_bound;
4168 const unsigned char *p = (const unsigned char *)s;
4169 const unsigned char *end = p + string_size;
4170 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4171 int err = 0;
4172
4173 for (; p < end && !err; ++p, ++char_count) {
4174 /* Only check value if it's not a ASCII char... */
4175 if (*p < 0x80) {
4176 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4177 an explanation. */
4178 if (!((size_t) p & LONG_PTR_MASK)) {
4179 /* Help register allocation */
4180 register const unsigned char *_p = p;
4181 while (_p < aligned_end) {
4182 unsigned long value = *(unsigned long *) _p;
4183 if (value & ASCII_CHAR_MASK)
4184 break;
4185 _p += SIZEOF_LONG;
4186 char_count += SIZEOF_LONG;
4187 }
4188 p = _p;
4189 if (p == end)
4190 break;
4191 }
4192 }
4193 if (*p >= 0x80) {
4194 n = utf8_code_length[*p];
4195 new_max = max_char;
4196 switch (n) {
4197 /* invalid start byte */
4198 case 0:
4199 err = 1;
4200 break;
4201 case 2:
4202 /* Code points between 0x00FF and 0x07FF inclusive.
4203 Approximate the upper bound of the code point,
4204 if this flips over 255 we can be sure it will be more
4205 than 255 and the string will need 2 bytes per code coint,
4206 if it stays under or equal to 255, we can be sure 1 byte
4207 is enough.
4208 ((*p & 0b00011111) << 6) | 0b00111111 */
4209 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4210 if (max_char < upper_bound)
4211 new_max = upper_bound;
4212 /* Ensure we track at least that we left ASCII space. */
4213 if (new_max < 128)
4214 new_max = 128;
4215 break;
4216 case 3:
4217 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4218 always > 255 and <= 65535 and will always need 2 bytes. */
4219 if (max_char < 65535)
4220 new_max = 65535;
4221 break;
4222 case 4:
4223 /* Code point will be above 0xFFFF for sure in this case. */
4224 new_max = 65537;
4225 break;
4226 /* Internal error, this should be caught by the first if */
4227 case 1:
4228 default:
4229 assert(0 && "Impossible case in utf8_max_char_and_size");
4230 err = 1;
4231 }
4232 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004233 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004234 --n;
4235 /* Check if the follow up chars are all valid continuation bytes */
4236 if (n >= 1) {
4237 const unsigned char *cont;
4238 if ((p + n) >= end) {
4239 if (consumed == 0)
4240 /* incomplete data, non-incremental decoding */
4241 err = 1;
4242 break;
4243 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004244 for (cont = p + 1; cont <= (p + n); ++cont) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004245 if ((*cont & 0xc0) != 0x80) {
4246 err = 1;
4247 break;
4248 }
4249 }
4250 p += n;
4251 }
4252 else
4253 err = 1;
4254 max_char = new_max;
4255 }
4256 }
4257
4258 if (unicode_size)
4259 *unicode_size = char_count;
4260 if (has_errors)
4261 *has_errors = err;
4262 return max_char;
4263}
4264
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004265/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
4266 in case of errors. Implicit parameters: unicode, kind, data, has_errors,
4267 onError. Potential resizing overallocates, so the result needs to shrink
4268 at the end.
4269*/
4270#define WRITE_MAYBE_FAIL(index, value) \
4271 do { \
4272 if (has_errors) { \
4273 Py_ssize_t pos = index; \
4274 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4275 unicode_resize(&unicode, pos + pos/8) < 0) \
4276 goto onError; \
4277 if (unicode_putchar(&unicode, &pos, value) < 0) \
4278 goto onError; \
4279 } \
4280 else \
4281 PyUnicode_WRITE(kind, data, index, value); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004282 } while (0)
4283
Alexander Belopolsky40018472011-02-26 01:02:56 +00004284PyObject *
4285PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004286 Py_ssize_t size,
4287 const char *errors,
4288 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004289{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004290 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004291 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004292 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004293 Py_ssize_t startinpos;
4294 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004295 const char *e, *aligned_end;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004296 PyObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004297 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004298 PyObject *errorHandler = NULL;
4299 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004300 Py_UCS4 maxchar = 0;
4301 Py_ssize_t unicode_size;
4302 Py_ssize_t i;
4303 int kind;
4304 void *data;
4305 int has_errors;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004306
Walter Dörwald69652032004-09-07 20:24:22 +00004307 if (size == 0) {
4308 if (consumed)
4309 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004310 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004311 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004312 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4313 consumed, &has_errors);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004314 if (has_errors)
4315 /* maxchar and size computation might be incorrect;
4316 code below widens and resizes as necessary. */
4317 unicode = PyUnicode_New(size, 127);
4318 else
Victor Stinner7931d9a2011-11-04 00:22:48 +01004319 unicode = PyUnicode_New(unicode_size, maxchar);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004320 if (!unicode)
4321 return NULL;
4322 /* When the string is ASCII only, just use memcpy and return.
4323 unicode_size may be != size if there is an incomplete UTF-8
4324 sequence at the end of the ASCII block. */
4325 if (!has_errors && maxchar < 128 && size == unicode_size) {
4326 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4327 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004328 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004329 kind = PyUnicode_KIND(unicode);
4330 data = PyUnicode_DATA(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004331 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004332 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004333 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004334 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004335
4336 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004337 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004338
4339 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004340 /* Fast path for runs of ASCII characters. Given that common UTF-8
4341 input will consist of an overwhelming majority of ASCII
4342 characters, we try to optimize for this case by checking
4343 as many characters as a C 'long' can contain.
4344 First, check if we can do an aligned read, as most CPUs have
4345 a penalty for unaligned reads.
4346 */
4347 if (!((size_t) s & LONG_PTR_MASK)) {
4348 /* Help register allocation */
4349 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004350 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004351 while (_s < aligned_end) {
4352 /* Read a whole long at a time (either 4 or 8 bytes),
4353 and do a fast unrolled copy if it only contains ASCII
4354 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004355 unsigned long value = *(unsigned long *) _s;
4356 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004357 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004358 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4359 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4360 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4361 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004362#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004363 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4364 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4365 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4366 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004367#endif
4368 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004369 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004370 }
4371 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004372 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004373 if (s == e)
4374 break;
4375 ch = (unsigned char)*s;
4376 }
4377 }
4378
4379 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004380 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004381 s++;
4382 continue;
4383 }
4384
4385 n = utf8_code_length[ch];
4386
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004387 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004388 if (consumed)
4389 break;
4390 else {
4391 errmsg = "unexpected end of data";
4392 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004393 endinpos = startinpos+1;
4394 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4395 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004396 goto utf8Error;
4397 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004398 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004399
4400 switch (n) {
4401
4402 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004403 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004404 startinpos = s-starts;
4405 endinpos = startinpos+1;
4406 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004407
4408 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004409 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004410 startinpos = s-starts;
4411 endinpos = startinpos+1;
4412 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004413
4414 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004415 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004416 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004417 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004418 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004419 goto utf8Error;
4420 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004421 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004422 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004423 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004424 break;
4425
4426 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004427 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4428 will result in surrogates in range d800-dfff. Surrogates are
4429 not valid UTF-8 so they are rejected.
4430 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4431 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004432 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004433 (s[2] & 0xc0) != 0x80 ||
4434 ((unsigned char)s[0] == 0xE0 &&
4435 (unsigned char)s[1] < 0xA0) ||
4436 ((unsigned char)s[0] == 0xED &&
4437 (unsigned char)s[1] > 0x9F)) {
4438 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004439 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004440 endinpos = startinpos + 1;
4441
4442 /* if s[1] first two bits are 1 and 0, then the invalid
4443 continuation byte is s[2], so increment endinpos by 1,
4444 if not, s[1] is invalid and endinpos doesn't need to
4445 be incremented. */
4446 if ((s[1] & 0xC0) == 0x80)
4447 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004448 goto utf8Error;
4449 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004450 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004451 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004452 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004453 break;
4454
4455 case 4:
4456 if ((s[1] & 0xc0) != 0x80 ||
4457 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004458 (s[3] & 0xc0) != 0x80 ||
4459 ((unsigned char)s[0] == 0xF0 &&
4460 (unsigned char)s[1] < 0x90) ||
4461 ((unsigned char)s[0] == 0xF4 &&
4462 (unsigned char)s[1] > 0x8F)) {
4463 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004464 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004465 endinpos = startinpos + 1;
4466 if ((s[1] & 0xC0) == 0x80) {
4467 endinpos++;
4468 if ((s[2] & 0xC0) == 0x80)
4469 endinpos++;
4470 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004471 goto utf8Error;
4472 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004473 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004474 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4475 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4476
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004477 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004478 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004479 }
4480 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004481 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004482
Benjamin Peterson29060642009-01-31 22:14:21 +00004483 utf8Error:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004484 if (!has_errors) {
4485 PyObject *tmp;
4486 Py_ssize_t k;
4487 /* We encountered some error that wasn't detected in the original scan,
4488 e.g. an encoded surrogate character. The original maxchar computation may
4489 have been incorrect, so redo it now. */
4490 for (k = 0, maxchar = 0; k < i; k++)
4491 maxchar = Py_MAX(maxchar, PyUnicode_READ(kind, data, k));
4492 tmp = PyUnicode_New(PyUnicode_GET_LENGTH(unicode), maxchar);
4493 if (tmp == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004494 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004495 PyUnicode_CopyCharacters(tmp, 0, unicode, 0, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004496 Py_DECREF(unicode);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004497 unicode = tmp;
4498 has_errors = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004499 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004500 if (unicode_decode_call_errorhandler(
4501 errors, &errorHandler,
4502 "utf8", errmsg,
4503 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004504 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004505 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004506 /* Update data because unicode_decode_call_errorhandler might have
4507 re-created or resized the unicode object. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004508 data = PyUnicode_DATA(unicode);
4509 kind = PyUnicode_KIND(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004510 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004511 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004512 /* Ensure the unicode_size calculation above was correct: */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004513 assert(has_errors || i == unicode_size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004514
Walter Dörwald69652032004-09-07 20:24:22 +00004515 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004516 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004518 /* Adjust length and ready string when it contained errors and
4519 is of the old resizable kind. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004520 if (has_errors) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004521 if (PyUnicode_Resize(&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004522 goto onError;
4523 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004524
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004525 Py_XDECREF(errorHandler);
4526 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004527 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004528 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004529
Benjamin Peterson29060642009-01-31 22:14:21 +00004530 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004531 Py_XDECREF(errorHandler);
4532 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004533 Py_DECREF(unicode);
4534 return NULL;
4535}
4536
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004537#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004538
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004539#ifdef __APPLE__
4540
4541/* Simplified UTF-8 decoder using surrogateescape error handler,
4542 used to decode the command line arguments on Mac OS X. */
4543
4544wchar_t*
4545_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4546{
4547 int n;
4548 const char *e;
4549 wchar_t *unicode, *p;
4550
4551 /* Note: size will always be longer than the resulting Unicode
4552 character count */
4553 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4554 PyErr_NoMemory();
4555 return NULL;
4556 }
4557 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4558 if (!unicode)
4559 return NULL;
4560
4561 /* Unpack UTF-8 encoded data */
4562 p = unicode;
4563 e = s + size;
4564 while (s < e) {
4565 Py_UCS4 ch = (unsigned char)*s;
4566
4567 if (ch < 0x80) {
4568 *p++ = (wchar_t)ch;
4569 s++;
4570 continue;
4571 }
4572
4573 n = utf8_code_length[ch];
4574 if (s + n > e) {
4575 goto surrogateescape;
4576 }
4577
4578 switch (n) {
4579 case 0:
4580 case 1:
4581 goto surrogateescape;
4582
4583 case 2:
4584 if ((s[1] & 0xc0) != 0x80)
4585 goto surrogateescape;
4586 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4587 assert ((ch > 0x007F) && (ch <= 0x07FF));
4588 *p++ = (wchar_t)ch;
4589 break;
4590
4591 case 3:
4592 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4593 will result in surrogates in range d800-dfff. Surrogates are
4594 not valid UTF-8 so they are rejected.
4595 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4596 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4597 if ((s[1] & 0xc0) != 0x80 ||
4598 (s[2] & 0xc0) != 0x80 ||
4599 ((unsigned char)s[0] == 0xE0 &&
4600 (unsigned char)s[1] < 0xA0) ||
4601 ((unsigned char)s[0] == 0xED &&
4602 (unsigned char)s[1] > 0x9F)) {
4603
4604 goto surrogateescape;
4605 }
4606 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4607 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004608 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004609 break;
4610
4611 case 4:
4612 if ((s[1] & 0xc0) != 0x80 ||
4613 (s[2] & 0xc0) != 0x80 ||
4614 (s[3] & 0xc0) != 0x80 ||
4615 ((unsigned char)s[0] == 0xF0 &&
4616 (unsigned char)s[1] < 0x90) ||
4617 ((unsigned char)s[0] == 0xF4 &&
4618 (unsigned char)s[1] > 0x8F)) {
4619 goto surrogateescape;
4620 }
4621 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4622 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4623 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4624
4625#if SIZEOF_WCHAR_T == 4
4626 *p++ = (wchar_t)ch;
4627#else
4628 /* compute and append the two surrogates: */
4629
4630 /* translate from 10000..10FFFF to 0..FFFF */
4631 ch -= 0x10000;
4632
4633 /* high surrogate = top 10 bits added to D800 */
4634 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4635
4636 /* low surrogate = bottom 10 bits added to DC00 */
4637 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4638#endif
4639 break;
4640 }
4641 s += n;
4642 continue;
4643
4644 surrogateescape:
4645 *p++ = 0xDC00 + ch;
4646 s++;
4647 }
4648 *p = L'\0';
4649 return unicode;
4650}
4651
4652#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004653
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004654/* Primary internal function which creates utf8 encoded bytes objects.
4655
4656 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004657 and allocate exactly as much space needed at the end. Else allocate the
4658 maximum possible needed (4 result bytes per Unicode character), and return
4659 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004660*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004661PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004662_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004663{
Tim Peters602f7402002-04-27 18:03:26 +00004664#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004665
Guido van Rossum98297ee2007-11-06 21:34:58 +00004666 Py_ssize_t i; /* index into s of next input byte */
4667 PyObject *result; /* result string object */
4668 char *p; /* next free byte in output buffer */
4669 Py_ssize_t nallocated; /* number of result bytes allocated */
4670 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004671 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004672 PyObject *errorHandler = NULL;
4673 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004674 int kind;
4675 void *data;
4676 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004677
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004678 if (!PyUnicode_Check(unicode)) {
4679 PyErr_BadArgument();
4680 return NULL;
4681 }
4682
4683 if (PyUnicode_READY(unicode) == -1)
4684 return NULL;
4685
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004686 if (PyUnicode_UTF8(unicode))
4687 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4688 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004689
4690 kind = PyUnicode_KIND(unicode);
4691 data = PyUnicode_DATA(unicode);
4692 size = PyUnicode_GET_LENGTH(unicode);
4693
Tim Peters602f7402002-04-27 18:03:26 +00004694 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004695
Tim Peters602f7402002-04-27 18:03:26 +00004696 if (size <= MAX_SHORT_UNICHARS) {
4697 /* Write into the stack buffer; nallocated can't overflow.
4698 * At the end, we'll allocate exactly as much heap space as it
4699 * turns out we need.
4700 */
4701 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004702 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004703 p = stackbuf;
4704 }
4705 else {
4706 /* Overallocate on the heap, and give the excess back at the end. */
4707 nallocated = size * 4;
4708 if (nallocated / 4 != size) /* overflow! */
4709 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004710 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004711 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004712 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004713 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004714 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004715
Tim Peters602f7402002-04-27 18:03:26 +00004716 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004717 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004718
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004719 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004720 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004721 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004722
Guido van Rossumd57fd912000-03-10 22:53:23 +00004723 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004724 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004725 *p++ = (char)(0xc0 | (ch >> 6));
4726 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004727 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004728 Py_ssize_t newpos;
4729 PyObject *rep;
4730 Py_ssize_t repsize, k, startpos;
4731 startpos = i-1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004732 rep = unicode_encode_call_errorhandler(
4733 errors, &errorHandler, "utf-8", "surrogates not allowed",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004734 unicode, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004735 if (!rep)
4736 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004737
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004738 if (PyBytes_Check(rep))
4739 repsize = PyBytes_GET_SIZE(rep);
4740 else
4741 repsize = PyUnicode_GET_SIZE(rep);
4742
4743 if (repsize > 4) {
4744 Py_ssize_t offset;
4745
4746 if (result == NULL)
4747 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004748 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004749 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004750
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004751 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4752 /* integer overflow */
4753 PyErr_NoMemory();
4754 goto error;
4755 }
4756 nallocated += repsize - 4;
4757 if (result != NULL) {
4758 if (_PyBytes_Resize(&result, nallocated) < 0)
4759 goto error;
4760 } else {
4761 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004762 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004763 goto error;
4764 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4765 }
4766 p = PyBytes_AS_STRING(result) + offset;
4767 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004768
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004769 if (PyBytes_Check(rep)) {
4770 char *prep = PyBytes_AS_STRING(rep);
4771 for(k = repsize; k > 0; k--)
4772 *p++ = *prep++;
4773 } else /* rep is unicode */ {
4774 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4775 Py_UNICODE c;
4776
4777 for(k=0; k<repsize; k++) {
4778 c = prep[k];
4779 if (0x80 <= c) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01004780 raise_encode_exception(&exc, "utf-8",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004781 unicode,
Martin v. Löwis9e816682011-11-02 12:45:42 +01004782 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004783 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004784 goto error;
4785 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004786 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004787 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004788 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004789 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004790 } else if (ch < 0x10000) {
4791 *p++ = (char)(0xe0 | (ch >> 12));
4792 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4793 *p++ = (char)(0x80 | (ch & 0x3f));
4794 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004795 /* Encode UCS4 Unicode ordinals */
4796 *p++ = (char)(0xf0 | (ch >> 18));
4797 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4798 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4799 *p++ = (char)(0x80 | (ch & 0x3f));
4800 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004801 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004802
Guido van Rossum98297ee2007-11-06 21:34:58 +00004803 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004804 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004805 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004806 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004807 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004808 }
4809 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004810 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004811 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004812 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004813 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004814 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004815
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004816 Py_XDECREF(errorHandler);
4817 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004818 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004819 error:
4820 Py_XDECREF(errorHandler);
4821 Py_XDECREF(exc);
4822 Py_XDECREF(result);
4823 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004824
Tim Peters602f7402002-04-27 18:03:26 +00004825#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004826}
4827
Alexander Belopolsky40018472011-02-26 01:02:56 +00004828PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004829PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4830 Py_ssize_t size,
4831 const char *errors)
4832{
4833 PyObject *v, *unicode;
4834
4835 unicode = PyUnicode_FromUnicode(s, size);
4836 if (unicode == NULL)
4837 return NULL;
4838 v = _PyUnicode_AsUTF8String(unicode, errors);
4839 Py_DECREF(unicode);
4840 return v;
4841}
4842
4843PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004844PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004845{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004846 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004847}
4848
Walter Dörwald41980ca2007-08-16 21:55:45 +00004849/* --- UTF-32 Codec ------------------------------------------------------- */
4850
4851PyObject *
4852PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004853 Py_ssize_t size,
4854 const char *errors,
4855 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004856{
4857 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4858}
4859
4860PyObject *
4861PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004862 Py_ssize_t size,
4863 const char *errors,
4864 int *byteorder,
4865 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004866{
4867 const char *starts = s;
4868 Py_ssize_t startinpos;
4869 Py_ssize_t endinpos;
4870 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004871 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004872 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004873 int bo = 0; /* assume native ordering by default */
4874 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004875 /* Offsets from q for retrieving bytes in the right order. */
4876#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4877 int iorder[] = {0, 1, 2, 3};
4878#else
4879 int iorder[] = {3, 2, 1, 0};
4880#endif
4881 PyObject *errorHandler = NULL;
4882 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004883
Walter Dörwald41980ca2007-08-16 21:55:45 +00004884 q = (unsigned char *)s;
4885 e = q + size;
4886
4887 if (byteorder)
4888 bo = *byteorder;
4889
4890 /* Check for BOM marks (U+FEFF) in the input and adjust current
4891 byte order setting accordingly. In native mode, the leading BOM
4892 mark is skipped, in all other modes, it is copied to the output
4893 stream as-is (giving a ZWNBSP character). */
4894 if (bo == 0) {
4895 if (size >= 4) {
4896 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004897 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004898#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004899 if (bom == 0x0000FEFF) {
4900 q += 4;
4901 bo = -1;
4902 }
4903 else if (bom == 0xFFFE0000) {
4904 q += 4;
4905 bo = 1;
4906 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004907#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004908 if (bom == 0x0000FEFF) {
4909 q += 4;
4910 bo = 1;
4911 }
4912 else if (bom == 0xFFFE0000) {
4913 q += 4;
4914 bo = -1;
4915 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004916#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004917 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004918 }
4919
4920 if (bo == -1) {
4921 /* force LE */
4922 iorder[0] = 0;
4923 iorder[1] = 1;
4924 iorder[2] = 2;
4925 iorder[3] = 3;
4926 }
4927 else if (bo == 1) {
4928 /* force BE */
4929 iorder[0] = 3;
4930 iorder[1] = 2;
4931 iorder[2] = 1;
4932 iorder[3] = 0;
4933 }
4934
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004935 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004936 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004937 if (!unicode)
4938 return NULL;
4939 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01004940 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004941 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004942
Walter Dörwald41980ca2007-08-16 21:55:45 +00004943 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004944 Py_UCS4 ch;
4945 /* remaining bytes at the end? (size should be divisible by 4) */
4946 if (e-q<4) {
4947 if (consumed)
4948 break;
4949 errmsg = "truncated data";
4950 startinpos = ((const char *)q)-starts;
4951 endinpos = ((const char *)e)-starts;
4952 goto utf32Error;
4953 /* The remaining input chars are ignored if the callback
4954 chooses to skip the input */
4955 }
4956 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4957 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004958
Benjamin Peterson29060642009-01-31 22:14:21 +00004959 if (ch >= 0x110000)
4960 {
4961 errmsg = "codepoint not in range(0x110000)";
4962 startinpos = ((const char *)q)-starts;
4963 endinpos = startinpos+4;
4964 goto utf32Error;
4965 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004966 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4967 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00004968 q += 4;
4969 continue;
4970 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00004971 if (unicode_decode_call_errorhandler(
4972 errors, &errorHandler,
4973 "utf32", errmsg,
4974 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004975 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004976 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004977 }
4978
4979 if (byteorder)
4980 *byteorder = bo;
4981
4982 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004983 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004984
4985 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004986 if (PyUnicode_Resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004987 goto onError;
4988
4989 Py_XDECREF(errorHandler);
4990 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004991#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004992 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004993 Py_DECREF(unicode);
4994 return NULL;
4995 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004996#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004997 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004998 return unicode;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004999
Benjamin Peterson29060642009-01-31 22:14:21 +00005000 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005001 Py_DECREF(unicode);
5002 Py_XDECREF(errorHandler);
5003 Py_XDECREF(exc);
5004 return NULL;
5005}
5006
5007PyObject *
5008PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005009 Py_ssize_t size,
5010 const char *errors,
5011 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005012{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005013 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005014 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005015 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005016#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005017 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005018#else
5019 const int pairs = 0;
5020#endif
5021 /* Offsets from p for storing byte pairs in the right order. */
5022#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5023 int iorder[] = {0, 1, 2, 3};
5024#else
5025 int iorder[] = {3, 2, 1, 0};
5026#endif
5027
Benjamin Peterson29060642009-01-31 22:14:21 +00005028#define STORECHAR(CH) \
5029 do { \
5030 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5031 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5032 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5033 p[iorder[0]] = (CH) & 0xff; \
5034 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005035 } while(0)
5036
5037 /* In narrow builds we can output surrogate pairs as one codepoint,
5038 so we need less space. */
5039#ifndef Py_UNICODE_WIDE
5040 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005041 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
5042 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
5043 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005044#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005045 nsize = (size - pairs + (byteorder == 0));
5046 bytesize = nsize * 4;
5047 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005048 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005049 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005050 if (v == NULL)
5051 return NULL;
5052
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005053 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005054 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005055 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005056 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005057 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005058
5059 if (byteorder == -1) {
5060 /* force LE */
5061 iorder[0] = 0;
5062 iorder[1] = 1;
5063 iorder[2] = 2;
5064 iorder[3] = 3;
5065 }
5066 else if (byteorder == 1) {
5067 /* force BE */
5068 iorder[0] = 3;
5069 iorder[1] = 2;
5070 iorder[2] = 1;
5071 iorder[3] = 0;
5072 }
5073
5074 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005075 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005076#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005077 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
5078 Py_UCS4 ch2 = *s;
5079 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
5080 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
5081 s++;
5082 size--;
5083 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005084 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005085#endif
5086 STORECHAR(ch);
5087 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005088
5089 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005090 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005091#undef STORECHAR
5092}
5093
Alexander Belopolsky40018472011-02-26 01:02:56 +00005094PyObject *
5095PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005096{
5097 if (!PyUnicode_Check(unicode)) {
5098 PyErr_BadArgument();
5099 return NULL;
5100 }
5101 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005102 PyUnicode_GET_SIZE(unicode),
5103 NULL,
5104 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005105}
5106
Guido van Rossumd57fd912000-03-10 22:53:23 +00005107/* --- UTF-16 Codec ------------------------------------------------------- */
5108
Tim Peters772747b2001-08-09 22:21:55 +00005109PyObject *
5110PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005111 Py_ssize_t size,
5112 const char *errors,
5113 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005114{
Walter Dörwald69652032004-09-07 20:24:22 +00005115 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5116}
5117
Antoine Pitrouab868312009-01-10 15:40:25 +00005118/* Two masks for fast checking of whether a C 'long' may contain
5119 UTF16-encoded surrogate characters. This is an efficient heuristic,
5120 assuming that non-surrogate characters with a code point >= 0x8000 are
5121 rare in most input.
5122 FAST_CHAR_MASK is used when the input is in native byte ordering,
5123 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005124*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005125#if (SIZEOF_LONG == 8)
5126# define FAST_CHAR_MASK 0x8000800080008000L
5127# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5128#elif (SIZEOF_LONG == 4)
5129# define FAST_CHAR_MASK 0x80008000L
5130# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5131#else
5132# error C 'long' size should be either 4 or 8!
5133#endif
5134
Walter Dörwald69652032004-09-07 20:24:22 +00005135PyObject *
5136PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005137 Py_ssize_t size,
5138 const char *errors,
5139 int *byteorder,
5140 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005141{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005142 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005143 Py_ssize_t startinpos;
5144 Py_ssize_t endinpos;
5145 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005146 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005147 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005148 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005149 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005150 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005151 /* Offsets from q for retrieving byte pairs in the right order. */
5152#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5153 int ihi = 1, ilo = 0;
5154#else
5155 int ihi = 0, ilo = 1;
5156#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005157 PyObject *errorHandler = NULL;
5158 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005159
5160 /* Note: size will always be longer than the resulting Unicode
5161 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005162 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005163 if (!unicode)
5164 return NULL;
5165 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005166 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005167 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005168
Tim Peters772747b2001-08-09 22:21:55 +00005169 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005170 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005171
5172 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005173 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005174
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005175 /* Check for BOM marks (U+FEFF) in the input and adjust current
5176 byte order setting accordingly. In native mode, the leading BOM
5177 mark is skipped, in all other modes, it is copied to the output
5178 stream as-is (giving a ZWNBSP character). */
5179 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005180 if (size >= 2) {
5181 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005182#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005183 if (bom == 0xFEFF) {
5184 q += 2;
5185 bo = -1;
5186 }
5187 else if (bom == 0xFFFE) {
5188 q += 2;
5189 bo = 1;
5190 }
Tim Petersced69f82003-09-16 20:30:58 +00005191#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005192 if (bom == 0xFEFF) {
5193 q += 2;
5194 bo = 1;
5195 }
5196 else if (bom == 0xFFFE) {
5197 q += 2;
5198 bo = -1;
5199 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005200#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005201 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005202 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005203
Tim Peters772747b2001-08-09 22:21:55 +00005204 if (bo == -1) {
5205 /* force LE */
5206 ihi = 1;
5207 ilo = 0;
5208 }
5209 else if (bo == 1) {
5210 /* force BE */
5211 ihi = 0;
5212 ilo = 1;
5213 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005214#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5215 native_ordering = ilo < ihi;
5216#else
5217 native_ordering = ilo > ihi;
5218#endif
Tim Peters772747b2001-08-09 22:21:55 +00005219
Antoine Pitrouab868312009-01-10 15:40:25 +00005220 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005221 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005222 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005223 /* First check for possible aligned read of a C 'long'. Unaligned
5224 reads are more expensive, better to defer to another iteration. */
5225 if (!((size_t) q & LONG_PTR_MASK)) {
5226 /* Fast path for runs of non-surrogate chars. */
5227 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005228 int kind = PyUnicode_KIND(unicode);
5229 void *data = PyUnicode_DATA(unicode);
5230 while (_q < aligned_end) {
5231 unsigned long block = * (unsigned long *) _q;
5232 unsigned short *pblock = (unsigned short*)&block;
5233 Py_UCS4 maxch;
5234 if (native_ordering) {
5235 /* Can use buffer directly */
5236 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005237 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005238 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005239 else {
5240 /* Need to byte-swap */
5241 unsigned char *_p = (unsigned char*)pblock;
5242 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005243 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005244 _p[0] = _q[1];
5245 _p[1] = _q[0];
5246 _p[2] = _q[3];
5247 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005248#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005249 _p[4] = _q[5];
5250 _p[5] = _q[4];
5251 _p[6] = _q[7];
5252 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005253#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005254 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005255 maxch = Py_MAX(pblock[0], pblock[1]);
5256#if SIZEOF_LONG == 8
5257 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5258#endif
5259 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5260 if (unicode_widen(&unicode, maxch) < 0)
5261 goto onError;
5262 kind = PyUnicode_KIND(unicode);
5263 data = PyUnicode_DATA(unicode);
5264 }
5265 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5266 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5267#if SIZEOF_LONG == 8
5268 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5269 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5270#endif
5271 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005272 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005273 q = _q;
5274 if (q >= e)
5275 break;
5276 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005277 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005278
Benjamin Peterson14339b62009-01-31 16:36:08 +00005279 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005280
5281 if (ch < 0xD800 || ch > 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005282 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5283 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005284 continue;
5285 }
5286
5287 /* UTF-16 code pair: */
5288 if (q > e) {
5289 errmsg = "unexpected end of data";
5290 startinpos = (((const char *)q) - 2) - starts;
5291 endinpos = ((const char *)e) + 1 - starts;
5292 goto utf16Error;
5293 }
5294 if (0xD800 <= ch && ch <= 0xDBFF) {
5295 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5296 q += 2;
5297 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005298 if (unicode_putchar(&unicode, &outpos,
5299 (((ch & 0x3FF)<<10) |
5300 (ch2 & 0x3FF)) + 0x10000) < 0)
5301 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005302 continue;
5303 }
5304 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005305 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005306 startinpos = (((const char *)q)-4)-starts;
5307 endinpos = startinpos+2;
5308 goto utf16Error;
5309 }
5310
Benjamin Peterson14339b62009-01-31 16:36:08 +00005311 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005312 errmsg = "illegal encoding";
5313 startinpos = (((const char *)q)-2)-starts;
5314 endinpos = startinpos+2;
5315 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005316
Benjamin Peterson29060642009-01-31 22:14:21 +00005317 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005318 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005319 errors,
5320 &errorHandler,
5321 "utf16", errmsg,
5322 &starts,
5323 (const char **)&e,
5324 &startinpos,
5325 &endinpos,
5326 &exc,
5327 (const char **)&q,
5328 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005329 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005330 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005331 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005332 /* remaining byte at the end? (size should be even) */
5333 if (e == q) {
5334 if (!consumed) {
5335 errmsg = "truncated data";
5336 startinpos = ((const char *)q) - starts;
5337 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005338 if (unicode_decode_call_errorhandler(
5339 errors,
5340 &errorHandler,
5341 "utf16", errmsg,
5342 &starts,
5343 (const char **)&e,
5344 &startinpos,
5345 &endinpos,
5346 &exc,
5347 (const char **)&q,
5348 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005349 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005350 goto onError;
5351 /* The remaining input chars are ignored if the callback
5352 chooses to skip the input */
5353 }
5354 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005355
5356 if (byteorder)
5357 *byteorder = bo;
5358
Walter Dörwald69652032004-09-07 20:24:22 +00005359 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005360 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005361
Guido van Rossumd57fd912000-03-10 22:53:23 +00005362 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005363 if (PyUnicode_Resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005364 goto onError;
5365
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005366 Py_XDECREF(errorHandler);
5367 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005368 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005369 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005370
Benjamin Peterson29060642009-01-31 22:14:21 +00005371 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005372 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005373 Py_XDECREF(errorHandler);
5374 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005375 return NULL;
5376}
5377
Antoine Pitrouab868312009-01-10 15:40:25 +00005378#undef FAST_CHAR_MASK
5379#undef SWAPPED_FAST_CHAR_MASK
5380
Tim Peters772747b2001-08-09 22:21:55 +00005381PyObject *
5382PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005383 Py_ssize_t size,
5384 const char *errors,
5385 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005386{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005387 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005388 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005389 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005390#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005391 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005392#else
5393 const int pairs = 0;
5394#endif
Tim Peters772747b2001-08-09 22:21:55 +00005395 /* Offsets from p for storing byte pairs in the right order. */
5396#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5397 int ihi = 1, ilo = 0;
5398#else
5399 int ihi = 0, ilo = 1;
5400#endif
5401
Benjamin Peterson29060642009-01-31 22:14:21 +00005402#define STORECHAR(CH) \
5403 do { \
5404 p[ihi] = ((CH) >> 8) & 0xff; \
5405 p[ilo] = (CH) & 0xff; \
5406 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005407 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005408
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005409#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005410 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005411 if (s[i] >= 0x10000)
5412 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005413#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005414 /* 2 * (size + pairs + (byteorder == 0)) */
5415 if (size > PY_SSIZE_T_MAX ||
5416 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005417 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005418 nsize = size + pairs + (byteorder == 0);
5419 bytesize = nsize * 2;
5420 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005421 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005422 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005423 if (v == NULL)
5424 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005425
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005426 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005427 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005428 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005429 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005430 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005431
5432 if (byteorder == -1) {
5433 /* force LE */
5434 ihi = 1;
5435 ilo = 0;
5436 }
5437 else if (byteorder == 1) {
5438 /* force BE */
5439 ihi = 0;
5440 ilo = 1;
5441 }
5442
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005443 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005444 Py_UNICODE ch = *s++;
5445 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005446#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005447 if (ch >= 0x10000) {
5448 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5449 ch = 0xD800 | ((ch-0x10000) >> 10);
5450 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005451#endif
Tim Peters772747b2001-08-09 22:21:55 +00005452 STORECHAR(ch);
5453 if (ch2)
5454 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005455 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005456
5457 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005458 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005459#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005460}
5461
Alexander Belopolsky40018472011-02-26 01:02:56 +00005462PyObject *
5463PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005464{
5465 if (!PyUnicode_Check(unicode)) {
5466 PyErr_BadArgument();
5467 return NULL;
5468 }
5469 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005470 PyUnicode_GET_SIZE(unicode),
5471 NULL,
5472 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005473}
5474
5475/* --- Unicode Escape Codec ----------------------------------------------- */
5476
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005477/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5478 if all the escapes in the string make it still a valid ASCII string.
5479 Returns -1 if any escapes were found which cause the string to
5480 pop out of ASCII range. Otherwise returns the length of the
5481 required buffer to hold the string.
5482 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005483static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005484length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5485{
5486 const unsigned char *p = (const unsigned char *)s;
5487 const unsigned char *end = p + size;
5488 Py_ssize_t length = 0;
5489
5490 if (size < 0)
5491 return -1;
5492
5493 for (; p < end; ++p) {
5494 if (*p > 127) {
5495 /* Non-ASCII */
5496 return -1;
5497 }
5498 else if (*p != '\\') {
5499 /* Normal character */
5500 ++length;
5501 }
5502 else {
5503 /* Backslash-escape, check next char */
5504 ++p;
5505 /* Escape sequence reaches till end of string or
5506 non-ASCII follow-up. */
5507 if (p >= end || *p > 127)
5508 return -1;
5509 switch (*p) {
5510 case '\n':
5511 /* backslash + \n result in zero characters */
5512 break;
5513 case '\\': case '\'': case '\"':
5514 case 'b': case 'f': case 't':
5515 case 'n': case 'r': case 'v': case 'a':
5516 ++length;
5517 break;
5518 case '0': case '1': case '2': case '3':
5519 case '4': case '5': case '6': case '7':
5520 case 'x': case 'u': case 'U': case 'N':
5521 /* these do not guarantee ASCII characters */
5522 return -1;
5523 default:
5524 /* count the backslash + the other character */
5525 length += 2;
5526 }
5527 }
5528 }
5529 return length;
5530}
5531
5532/* Similar to PyUnicode_WRITE but either write into wstr field
5533 or treat string as ASCII. */
5534#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5535 do { \
5536 if ((kind) != PyUnicode_WCHAR_KIND) \
5537 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5538 else \
5539 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5540 } while (0)
5541
5542#define WRITE_WSTR(buf, index, value) \
5543 assert(kind == PyUnicode_WCHAR_KIND), \
5544 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5545
5546
Fredrik Lundh06d12682001-01-24 07:59:11 +00005547static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005548
Alexander Belopolsky40018472011-02-26 01:02:56 +00005549PyObject *
5550PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005551 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005552 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005553{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005554 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005555 Py_ssize_t startinpos;
5556 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005557 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005558 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005559 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005560 char* message;
5561 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005562 PyObject *errorHandler = NULL;
5563 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005564 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005565 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005566
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005567 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005568
5569 /* After length_of_escaped_ascii_string() there are two alternatives,
5570 either the string is pure ASCII with named escapes like \n, etc.
5571 and we determined it's exact size (common case)
5572 or it contains \x, \u, ... escape sequences. then we create a
5573 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005574 if (len >= 0) {
5575 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005576 if (!v)
5577 goto onError;
5578 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005579 }
5580 else {
5581 /* Escaped strings will always be longer than the resulting
5582 Unicode string, so we start with size here and then reduce the
5583 length after conversion to the true value.
5584 (but if the error callback returns a long replacement string
5585 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005586 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005587 if (!v)
5588 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005589 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005590 }
5591
Guido van Rossumd57fd912000-03-10 22:53:23 +00005592 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005593 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005594 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005595 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005596
Guido van Rossumd57fd912000-03-10 22:53:23 +00005597 while (s < end) {
5598 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005599 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005600 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005601
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005602 /* The only case in which i == ascii_length is a backslash
5603 followed by a newline. */
5604 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005605
Guido van Rossumd57fd912000-03-10 22:53:23 +00005606 /* Non-escape characters are interpreted as Unicode ordinals */
5607 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005608 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5609 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005610 continue;
5611 }
5612
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005613 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005614 /* \ - Escapes */
5615 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005616 c = *s++;
5617 if (s > end)
5618 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005619
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005620 /* The only case in which i == ascii_length is a backslash
5621 followed by a newline. */
5622 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005623
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005624 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005625
Benjamin Peterson29060642009-01-31 22:14:21 +00005626 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005627#define WRITECHAR(ch) \
5628 do { \
5629 if (unicode_putchar(&v, &i, ch) < 0) \
5630 goto onError; \
5631 }while(0)
5632
Guido van Rossumd57fd912000-03-10 22:53:23 +00005633 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005634 case '\\': WRITECHAR('\\'); break;
5635 case '\'': WRITECHAR('\''); break;
5636 case '\"': WRITECHAR('\"'); break;
5637 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005638 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005639 case 'f': WRITECHAR('\014'); break;
5640 case 't': WRITECHAR('\t'); break;
5641 case 'n': WRITECHAR('\n'); break;
5642 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005643 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005644 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005645 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005646 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005647
Benjamin Peterson29060642009-01-31 22:14:21 +00005648 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005649 case '0': case '1': case '2': case '3':
5650 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005651 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005652 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005653 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005654 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005655 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005656 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005657 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005658 break;
5659
Benjamin Peterson29060642009-01-31 22:14:21 +00005660 /* hex escapes */
5661 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005662 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005663 digits = 2;
5664 message = "truncated \\xXX escape";
5665 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005666
Benjamin Peterson29060642009-01-31 22:14:21 +00005667 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005668 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005669 digits = 4;
5670 message = "truncated \\uXXXX escape";
5671 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005672
Benjamin Peterson29060642009-01-31 22:14:21 +00005673 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005674 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005675 digits = 8;
5676 message = "truncated \\UXXXXXXXX escape";
5677 hexescape:
5678 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005679 if (s+digits>end) {
5680 endinpos = size;
5681 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005682 errors, &errorHandler,
5683 "unicodeescape", "end of string in escape sequence",
5684 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005685 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005686 goto onError;
5687 goto nextByte;
5688 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005689 for (j = 0; j < digits; ++j) {
5690 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005691 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005692 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005693 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005694 errors, &errorHandler,
5695 "unicodeescape", message,
5696 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005697 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005698 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005699 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005700 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005701 }
5702 chr = (chr<<4) & ~0xF;
5703 if (c >= '0' && c <= '9')
5704 chr += c - '0';
5705 else if (c >= 'a' && c <= 'f')
5706 chr += 10 + c - 'a';
5707 else
5708 chr += 10 + c - 'A';
5709 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005710 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005711 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005712 /* _decoding_error will have already written into the
5713 target buffer. */
5714 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005715 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005716 /* when we get here, chr is a 32-bit unicode character */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005717 if (chr <= 0x10ffff) {
5718 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005719 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005720 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005721 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005722 errors, &errorHandler,
5723 "unicodeescape", "illegal Unicode character",
5724 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005725 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005726 goto onError;
5727 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005728 break;
5729
Benjamin Peterson29060642009-01-31 22:14:21 +00005730 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005731 case 'N':
5732 message = "malformed \\N character escape";
5733 if (ucnhash_CAPI == NULL) {
5734 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005735 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5736 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005737 if (ucnhash_CAPI == NULL)
5738 goto ucnhashError;
5739 }
5740 if (*s == '{') {
5741 const char *start = s+1;
5742 /* look for the closing brace */
5743 while (*s != '}' && s < end)
5744 s++;
5745 if (s > start && s < end && *s == '}') {
5746 /* found a name. look it up in the unicode database */
5747 message = "unknown Unicode character name";
5748 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005749 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005750 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005751 goto store;
5752 }
5753 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005754 endinpos = s-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 Lundhccc74732001-02-18 22:13:49 +00005760 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005761 break;
5762
5763 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005764 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005765 message = "\\ at end of string";
5766 s--;
5767 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005768 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005769 errors, &errorHandler,
5770 "unicodeescape", message,
5771 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005772 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005773 goto onError;
5774 }
5775 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005776 WRITECHAR('\\');
5777 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005778 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005779 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005780 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005781 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005782 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005783 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005784#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005785
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005786 if (PyUnicode_Resize(&v, i) < 0)
5787 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005788 Py_XDECREF(errorHandler);
5789 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005790#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005791 if (_PyUnicode_READY_REPLACE(&v)) {
5792 Py_DECREF(v);
5793 return NULL;
5794 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005795#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005796 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005797 return v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005798
Benjamin Peterson29060642009-01-31 22:14:21 +00005799 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005800 PyErr_SetString(
5801 PyExc_UnicodeError,
5802 "\\N escapes not supported (can't load unicodedata module)"
5803 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005804 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005805 Py_XDECREF(errorHandler);
5806 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005807 return NULL;
5808
Benjamin Peterson29060642009-01-31 22:14:21 +00005809 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005810 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005811 Py_XDECREF(errorHandler);
5812 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005813 return NULL;
5814}
5815
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005816#undef WRITE_ASCII_OR_WSTR
5817#undef WRITE_WSTR
5818
Guido van Rossumd57fd912000-03-10 22:53:23 +00005819/* Return a Unicode-Escape string version of the Unicode object.
5820
5821 If quotes is true, the string is enclosed in u"" or u'' quotes as
5822 appropriate.
5823
5824*/
5825
Alexander Belopolsky40018472011-02-26 01:02:56 +00005826PyObject *
5827PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005828 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005829{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005830 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005831 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005832
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005833#ifdef Py_UNICODE_WIDE
5834 const Py_ssize_t expandsize = 10;
5835#else
5836 const Py_ssize_t expandsize = 6;
5837#endif
5838
Thomas Wouters89f507f2006-12-13 04:49:30 +00005839 /* XXX(nnorwitz): rather than over-allocating, it would be
5840 better to choose a different scheme. Perhaps scan the
5841 first N-chars of the string and allocate based on that size.
5842 */
5843 /* Initial allocation is based on the longest-possible unichr
5844 escape.
5845
5846 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5847 unichr, so in this case it's the longest unichr escape. In
5848 narrow (UTF-16) builds this is five chars per source unichr
5849 since there are two unichrs in the surrogate pair, so in narrow
5850 (UTF-16) builds it's not the longest unichr escape.
5851
5852 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5853 so in the narrow (UTF-16) build case it's the longest unichr
5854 escape.
5855 */
5856
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005857 if (size == 0)
5858 return PyBytes_FromStringAndSize(NULL, 0);
5859
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005860 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005861 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005862
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005863 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005864 2
5865 + expandsize*size
5866 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005867 if (repr == NULL)
5868 return NULL;
5869
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005870 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005871
Guido van Rossumd57fd912000-03-10 22:53:23 +00005872 while (size-- > 0) {
5873 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005874
Walter Dörwald79e913e2007-05-12 11:08:06 +00005875 /* Escape backslashes */
5876 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005877 *p++ = '\\';
5878 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005879 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005880 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005881
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005882#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005883 /* Map 21-bit characters to '\U00xxxxxx' */
5884 else if (ch >= 0x10000) {
5885 *p++ = '\\';
5886 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005887 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5888 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5889 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5890 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5891 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5892 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5893 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5894 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005895 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005896 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005897#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005898 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5899 else if (ch >= 0xD800 && ch < 0xDC00) {
5900 Py_UNICODE ch2;
5901 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00005902
Benjamin Peterson29060642009-01-31 22:14:21 +00005903 ch2 = *s++;
5904 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00005905 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005906 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
5907 *p++ = '\\';
5908 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005909 *p++ = Py_hexdigits[(ucs >> 28) & 0x0000000F];
5910 *p++ = Py_hexdigits[(ucs >> 24) & 0x0000000F];
5911 *p++ = Py_hexdigits[(ucs >> 20) & 0x0000000F];
5912 *p++ = Py_hexdigits[(ucs >> 16) & 0x0000000F];
5913 *p++ = Py_hexdigits[(ucs >> 12) & 0x0000000F];
5914 *p++ = Py_hexdigits[(ucs >> 8) & 0x0000000F];
5915 *p++ = Py_hexdigits[(ucs >> 4) & 0x0000000F];
5916 *p++ = Py_hexdigits[ucs & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005917 continue;
5918 }
5919 /* Fall through: isolated surrogates are copied as-is */
5920 s--;
5921 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005922 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005923#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005924
Guido van Rossumd57fd912000-03-10 22:53:23 +00005925 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005926 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005927 *p++ = '\\';
5928 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005929 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5930 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5931 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5932 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005934
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005935 /* Map special whitespace to '\t', \n', '\r' */
5936 else if (ch == '\t') {
5937 *p++ = '\\';
5938 *p++ = 't';
5939 }
5940 else if (ch == '\n') {
5941 *p++ = '\\';
5942 *p++ = 'n';
5943 }
5944 else if (ch == '\r') {
5945 *p++ = '\\';
5946 *p++ = 'r';
5947 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005948
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005949 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005950 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005951 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005952 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005953 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5954 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005955 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005956
Guido van Rossumd57fd912000-03-10 22:53:23 +00005957 /* Copy everything else as-is */
5958 else
5959 *p++ = (char) ch;
5960 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005961
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005962 assert(p - PyBytes_AS_STRING(repr) > 0);
5963 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5964 return NULL;
5965 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005966}
5967
Alexander Belopolsky40018472011-02-26 01:02:56 +00005968PyObject *
5969PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005970{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005971 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005972 if (!PyUnicode_Check(unicode)) {
5973 PyErr_BadArgument();
5974 return NULL;
5975 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00005976 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
5977 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005978 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005979}
5980
5981/* --- Raw Unicode Escape Codec ------------------------------------------- */
5982
Alexander Belopolsky40018472011-02-26 01:02:56 +00005983PyObject *
5984PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005985 Py_ssize_t size,
5986 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005987{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005988 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005989 Py_ssize_t startinpos;
5990 Py_ssize_t endinpos;
5991 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005992 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005993 const char *end;
5994 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005995 PyObject *errorHandler = NULL;
5996 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005997
Guido van Rossumd57fd912000-03-10 22:53:23 +00005998 /* Escaped strings will always be longer than the resulting
5999 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006000 length after conversion to the true value. (But decoding error
6001 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006002 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006003 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006004 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006005 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006006 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006007 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006008 end = s + size;
6009 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006010 unsigned char c;
6011 Py_UCS4 x;
6012 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006013 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006014
Benjamin Peterson29060642009-01-31 22:14:21 +00006015 /* Non-escape characters are interpreted as Unicode ordinals */
6016 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006017 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6018 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006019 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006020 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006021 startinpos = s-starts;
6022
6023 /* \u-escapes are only interpreted iff the number of leading
6024 backslashes if odd */
6025 bs = s;
6026 for (;s < end;) {
6027 if (*s != '\\')
6028 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006029 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6030 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006031 }
6032 if (((s - bs) & 1) == 0 ||
6033 s >= end ||
6034 (*s != 'u' && *s != 'U')) {
6035 continue;
6036 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006037 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006038 count = *s=='u' ? 4 : 8;
6039 s++;
6040
6041 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006042 for (x = 0, i = 0; i < count; ++i, ++s) {
6043 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006044 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006045 endinpos = s-starts;
6046 if (unicode_decode_call_errorhandler(
6047 errors, &errorHandler,
6048 "rawunicodeescape", "truncated \\uXXXX",
6049 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006050 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006051 goto onError;
6052 goto nextByte;
6053 }
6054 x = (x<<4) & ~0xF;
6055 if (c >= '0' && c <= '9')
6056 x += c - '0';
6057 else if (c >= 'a' && c <= 'f')
6058 x += 10 + c - 'a';
6059 else
6060 x += 10 + c - 'A';
6061 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006062 if (x <= 0x10ffff) {
6063 if (unicode_putchar(&v, &outpos, x) < 0)
6064 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006065 } else {
6066 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006067 if (unicode_decode_call_errorhandler(
6068 errors, &errorHandler,
6069 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006070 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006071 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006072 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006073 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006074 nextByte:
6075 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006076 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006077 if (PyUnicode_Resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006078 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006079 Py_XDECREF(errorHandler);
6080 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006081 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006082 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006083
Benjamin Peterson29060642009-01-31 22:14:21 +00006084 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006085 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006086 Py_XDECREF(errorHandler);
6087 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006088 return NULL;
6089}
6090
Alexander Belopolsky40018472011-02-26 01:02:56 +00006091PyObject *
6092PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006093 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006094{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006095 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006096 char *p;
6097 char *q;
6098
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006099#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006100 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006101#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006102 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006103#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00006104
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006105 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006106 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006107
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006108 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006109 if (repr == NULL)
6110 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00006111 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006112 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006113
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006114 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006115 while (size-- > 0) {
6116 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006117#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006118 /* Map 32-bit characters to '\Uxxxxxxxx' */
6119 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006120 *p++ = '\\';
6121 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006122 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6123 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6124 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6125 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6126 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6127 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6128 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6129 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006130 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006131 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00006132#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006133 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
6134 if (ch >= 0xD800 && ch < 0xDC00) {
6135 Py_UNICODE ch2;
6136 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006137
Benjamin Peterson29060642009-01-31 22:14:21 +00006138 ch2 = *s++;
6139 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006140 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006141 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6142 *p++ = '\\';
6143 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006144 *p++ = Py_hexdigits[(ucs >> 28) & 0xf];
6145 *p++ = Py_hexdigits[(ucs >> 24) & 0xf];
6146 *p++ = Py_hexdigits[(ucs >> 20) & 0xf];
6147 *p++ = Py_hexdigits[(ucs >> 16) & 0xf];
6148 *p++ = Py_hexdigits[(ucs >> 12) & 0xf];
6149 *p++ = Py_hexdigits[(ucs >> 8) & 0xf];
6150 *p++ = Py_hexdigits[(ucs >> 4) & 0xf];
6151 *p++ = Py_hexdigits[ucs & 0xf];
Benjamin Peterson29060642009-01-31 22:14:21 +00006152 continue;
6153 }
6154 /* Fall through: isolated surrogates are copied as-is */
6155 s--;
6156 size++;
6157 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006158#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006159 /* Map 16-bit characters to '\uxxxx' */
6160 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006161 *p++ = '\\';
6162 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006163 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6164 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6165 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6166 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006167 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006168 /* Copy everything else as-is */
6169 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006170 *p++ = (char) ch;
6171 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006172 size = p - q;
6173
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006174 assert(size > 0);
6175 if (_PyBytes_Resize(&repr, size) < 0)
6176 return NULL;
6177 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006178}
6179
Alexander Belopolsky40018472011-02-26 01:02:56 +00006180PyObject *
6181PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006182{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006183 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006184 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00006185 PyErr_BadArgument();
6186 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006187 }
Walter Dörwald711005d2007-05-12 12:03:26 +00006188 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6189 PyUnicode_GET_SIZE(unicode));
6190
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006191 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006192}
6193
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006194/* --- Unicode Internal Codec ------------------------------------------- */
6195
Alexander Belopolsky40018472011-02-26 01:02:56 +00006196PyObject *
6197_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006198 Py_ssize_t size,
6199 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006200{
6201 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006202 Py_ssize_t startinpos;
6203 Py_ssize_t endinpos;
6204 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006205 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006206 const char *end;
6207 const char *reason;
6208 PyObject *errorHandler = NULL;
6209 PyObject *exc = NULL;
6210
Thomas Wouters89f507f2006-12-13 04:49:30 +00006211 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006212 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006213 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006214 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006215 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006216 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006217 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006218 end = s + size;
6219
6220 while (s < end) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006221 Py_UCS4 ch = *(Py_UNICODE*)s;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006222 /* We have to sanity check the raw data, otherwise doom looms for
6223 some malformed UCS-4 data. */
6224 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006225#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006226 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006227#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006228 end-s < Py_UNICODE_SIZE
6229 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006230 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006231 startinpos = s - starts;
6232 if (end-s < Py_UNICODE_SIZE) {
6233 endinpos = end-starts;
6234 reason = "truncated input";
6235 }
6236 else {
6237 endinpos = s - starts + Py_UNICODE_SIZE;
6238 reason = "illegal code point (> 0x10FFFF)";
6239 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006240 if (unicode_decode_call_errorhandler(
6241 errors, &errorHandler,
6242 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006243 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006244 &v, &outpos)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006245 goto onError;
6246 }
6247 }
6248 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006249 if (unicode_putchar(&v, &outpos, ch) < 0)
6250 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006251 s += Py_UNICODE_SIZE;
6252 }
6253 }
6254
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006255 if (PyUnicode_Resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006256 goto onError;
6257 Py_XDECREF(errorHandler);
6258 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006259 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006260 return v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006261
Benjamin Peterson29060642009-01-31 22:14:21 +00006262 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006263 Py_XDECREF(v);
6264 Py_XDECREF(errorHandler);
6265 Py_XDECREF(exc);
6266 return NULL;
6267}
6268
Guido van Rossumd57fd912000-03-10 22:53:23 +00006269/* --- Latin-1 Codec ------------------------------------------------------ */
6270
Alexander Belopolsky40018472011-02-26 01:02:56 +00006271PyObject *
6272PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006273 Py_ssize_t size,
6274 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006275{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006276 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006277 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006278}
6279
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006280/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006281static void
6282make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006283 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006284 PyObject *unicode,
6285 Py_ssize_t startpos, Py_ssize_t endpos,
6286 const char *reason)
6287{
6288 if (*exceptionObject == NULL) {
6289 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006290 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006291 encoding, unicode, startpos, endpos, reason);
6292 }
6293 else {
6294 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6295 goto onError;
6296 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6297 goto onError;
6298 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6299 goto onError;
6300 return;
6301 onError:
6302 Py_DECREF(*exceptionObject);
6303 *exceptionObject = NULL;
6304 }
6305}
6306
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006307/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006308static void
6309raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006310 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006311 PyObject *unicode,
6312 Py_ssize_t startpos, Py_ssize_t endpos,
6313 const char *reason)
6314{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006315 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006316 encoding, unicode, startpos, endpos, reason);
6317 if (*exceptionObject != NULL)
6318 PyCodec_StrictErrors(*exceptionObject);
6319}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006320
6321/* error handling callback helper:
6322 build arguments, call the callback and check the arguments,
6323 put the result into newpos and return the replacement string, which
6324 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006325static PyObject *
6326unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006327 PyObject **errorHandler,
6328 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006329 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006330 Py_ssize_t startpos, Py_ssize_t endpos,
6331 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006332{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006333 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006334 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006335 PyObject *restuple;
6336 PyObject *resunicode;
6337
6338 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006339 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006340 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006341 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006342 }
6343
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006344 if (PyUnicode_READY(unicode) < 0)
6345 return NULL;
6346 len = PyUnicode_GET_LENGTH(unicode);
6347
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006348 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006349 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006350 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006351 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006352
6353 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006354 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006355 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006356 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006357 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006358 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006359 Py_DECREF(restuple);
6360 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006361 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006362 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006363 &resunicode, newpos)) {
6364 Py_DECREF(restuple);
6365 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006366 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006367 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6368 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6369 Py_DECREF(restuple);
6370 return NULL;
6371 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006372 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006373 *newpos = len + *newpos;
6374 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006375 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6376 Py_DECREF(restuple);
6377 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006378 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006379 Py_INCREF(resunicode);
6380 Py_DECREF(restuple);
6381 return resunicode;
6382}
6383
Alexander Belopolsky40018472011-02-26 01:02:56 +00006384static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006385unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006386 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006387 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006388{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006389 /* input state */
6390 Py_ssize_t pos=0, size;
6391 int kind;
6392 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006393 /* output object */
6394 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006395 /* pointer into the output */
6396 char *str;
6397 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006398 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006399 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6400 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006401 PyObject *errorHandler = NULL;
6402 PyObject *exc = NULL;
6403 /* the following variable is used for caching string comparisons
6404 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6405 int known_errorHandler = -1;
6406
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006407 if (PyUnicode_READY(unicode) < 0)
6408 return NULL;
6409 size = PyUnicode_GET_LENGTH(unicode);
6410 kind = PyUnicode_KIND(unicode);
6411 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006412 /* allocate enough for a simple encoding without
6413 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006414 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006415 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006416 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006417 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006418 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006419 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006420 ressize = size;
6421
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006422 while (pos < size) {
6423 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006424
Benjamin Peterson29060642009-01-31 22:14:21 +00006425 /* can we encode this? */
6426 if (c<limit) {
6427 /* no overflow check, because we know that the space is enough */
6428 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006429 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006430 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006431 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006432 Py_ssize_t requiredsize;
6433 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006434 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006435 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006436 Py_ssize_t collstart = pos;
6437 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006438 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006439 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006440 ++collend;
6441 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6442 if (known_errorHandler==-1) {
6443 if ((errors==NULL) || (!strcmp(errors, "strict")))
6444 known_errorHandler = 1;
6445 else if (!strcmp(errors, "replace"))
6446 known_errorHandler = 2;
6447 else if (!strcmp(errors, "ignore"))
6448 known_errorHandler = 3;
6449 else if (!strcmp(errors, "xmlcharrefreplace"))
6450 known_errorHandler = 4;
6451 else
6452 known_errorHandler = 0;
6453 }
6454 switch (known_errorHandler) {
6455 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006456 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006457 goto onError;
6458 case 2: /* replace */
6459 while (collstart++<collend)
6460 *str++ = '?'; /* fall through */
6461 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006462 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006463 break;
6464 case 4: /* xmlcharrefreplace */
6465 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006466 /* determine replacement size */
6467 for (i = collstart, repsize = 0; i < collend; ++i) {
6468 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6469 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006470 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006471 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006472 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006473 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006474 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006475 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006476 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006477#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006478 else
6479 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006480#else
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006481 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006482 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006483 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006484 repsize += 2+6+1;
6485 else
6486 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006487#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006488 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006489 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006490 if (requiredsize > ressize) {
6491 if (requiredsize<2*ressize)
6492 requiredsize = 2*ressize;
6493 if (_PyBytes_Resize(&res, requiredsize))
6494 goto onError;
6495 str = PyBytes_AS_STRING(res) + respos;
6496 ressize = requiredsize;
6497 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006498 /* generate replacement */
6499 for (i = collstart; i < collend; ++i) {
6500 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006501 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006502 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006503 break;
6504 default:
6505 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006506 encoding, reason, unicode, &exc,
6507 collstart, collend, &newpos);
6508 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6509 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006510 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006511 if (PyBytes_Check(repunicode)) {
6512 /* Directly copy bytes result to output. */
6513 repsize = PyBytes_Size(repunicode);
6514 if (repsize > 1) {
6515 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006516 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006517 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6518 Py_DECREF(repunicode);
6519 goto onError;
6520 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006521 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006522 ressize += repsize-1;
6523 }
6524 memcpy(str, PyBytes_AsString(repunicode), repsize);
6525 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006526 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006527 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006528 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006529 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006530 /* need more space? (at least enough for what we
6531 have+the replacement+the rest of the string, so
6532 we won't have to check space for encodable characters) */
6533 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006534 repsize = PyUnicode_GET_LENGTH(repunicode);
6535 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006536 if (requiredsize > ressize) {
6537 if (requiredsize<2*ressize)
6538 requiredsize = 2*ressize;
6539 if (_PyBytes_Resize(&res, requiredsize)) {
6540 Py_DECREF(repunicode);
6541 goto onError;
6542 }
6543 str = PyBytes_AS_STRING(res) + respos;
6544 ressize = requiredsize;
6545 }
6546 /* check if there is anything unencodable in the replacement
6547 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006548 for (i = 0; repsize-->0; ++i, ++str) {
6549 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006550 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006551 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006552 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006553 Py_DECREF(repunicode);
6554 goto onError;
6555 }
6556 *str = (char)c;
6557 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006558 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006559 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006560 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006561 }
6562 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006563 /* Resize if we allocated to much */
6564 size = str - PyBytes_AS_STRING(res);
6565 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006566 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006567 if (_PyBytes_Resize(&res, size) < 0)
6568 goto onError;
6569 }
6570
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006571 Py_XDECREF(errorHandler);
6572 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006573 return res;
6574
6575 onError:
6576 Py_XDECREF(res);
6577 Py_XDECREF(errorHandler);
6578 Py_XDECREF(exc);
6579 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006580}
6581
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006582/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006583PyObject *
6584PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006585 Py_ssize_t size,
6586 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006587{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006588 PyObject *result;
6589 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6590 if (unicode == NULL)
6591 return NULL;
6592 result = unicode_encode_ucs1(unicode, errors, 256);
6593 Py_DECREF(unicode);
6594 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006595}
6596
Alexander Belopolsky40018472011-02-26 01:02:56 +00006597PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006598_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006599{
6600 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006601 PyErr_BadArgument();
6602 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006603 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006604 if (PyUnicode_READY(unicode) == -1)
6605 return NULL;
6606 /* Fast path: if it is a one-byte string, construct
6607 bytes object directly. */
6608 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6609 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6610 PyUnicode_GET_LENGTH(unicode));
6611 /* Non-Latin-1 characters present. Defer to above function to
6612 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006613 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006614}
6615
6616PyObject*
6617PyUnicode_AsLatin1String(PyObject *unicode)
6618{
6619 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006620}
6621
6622/* --- 7-bit ASCII Codec -------------------------------------------------- */
6623
Alexander Belopolsky40018472011-02-26 01:02:56 +00006624PyObject *
6625PyUnicode_DecodeASCII(const char *s,
6626 Py_ssize_t size,
6627 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006628{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006629 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006630 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006631 int kind;
6632 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006633 Py_ssize_t startinpos;
6634 Py_ssize_t endinpos;
6635 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006636 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006637 int has_error;
6638 const unsigned char *p = (const unsigned char *)s;
6639 const unsigned char *end = p + size;
6640 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006641 PyObject *errorHandler = NULL;
6642 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006643
Guido van Rossumd57fd912000-03-10 22:53:23 +00006644 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006645 if (size == 1 && (unsigned char)s[0] < 128)
6646 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006647
Victor Stinner702c7342011-10-05 13:50:52 +02006648 has_error = 0;
6649 while (p < end && !has_error) {
6650 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6651 an explanation. */
6652 if (!((size_t) p & LONG_PTR_MASK)) {
6653 /* Help register allocation */
6654 register const unsigned char *_p = p;
6655 while (_p < aligned_end) {
6656 unsigned long value = *(unsigned long *) _p;
6657 if (value & ASCII_CHAR_MASK) {
6658 has_error = 1;
6659 break;
6660 }
6661 _p += SIZEOF_LONG;
6662 }
6663 if (_p == end)
6664 break;
6665 if (has_error)
6666 break;
6667 p = _p;
6668 }
6669 if (*p & 0x80) {
6670 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006671 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006672 }
6673 else {
6674 ++p;
6675 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006676 }
Victor Stinner702c7342011-10-05 13:50:52 +02006677 if (!has_error)
6678 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006679
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006680 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006681 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006682 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006683 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006684 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006685 kind = PyUnicode_KIND(v);
6686 data = PyUnicode_DATA(v);
6687 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006688 e = s + size;
6689 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006690 register unsigned char c = (unsigned char)*s;
6691 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006692 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006693 ++s;
6694 }
6695 else {
6696 startinpos = s-starts;
6697 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006698 if (unicode_decode_call_errorhandler(
6699 errors, &errorHandler,
6700 "ascii", "ordinal not in range(128)",
6701 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006702 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006703 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006704 kind = PyUnicode_KIND(v);
6705 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006706 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006707 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006708 if (PyUnicode_Resize(&v, outpos) < 0)
6709 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006710 Py_XDECREF(errorHandler);
6711 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006712 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006713 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006714
Benjamin Peterson29060642009-01-31 22:14:21 +00006715 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006716 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006717 Py_XDECREF(errorHandler);
6718 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006719 return NULL;
6720}
6721
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006722/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006723PyObject *
6724PyUnicode_EncodeASCII(const Py_UNICODE *p,
6725 Py_ssize_t size,
6726 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006727{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006728 PyObject *result;
6729 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6730 if (unicode == NULL)
6731 return NULL;
6732 result = unicode_encode_ucs1(unicode, errors, 128);
6733 Py_DECREF(unicode);
6734 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006735}
6736
Alexander Belopolsky40018472011-02-26 01:02:56 +00006737PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006738_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006739{
6740 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006741 PyErr_BadArgument();
6742 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006743 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006744 if (PyUnicode_READY(unicode) == -1)
6745 return NULL;
6746 /* Fast path: if it is an ASCII-only string, construct bytes object
6747 directly. Else defer to above function to raise the exception. */
6748 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6749 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6750 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006751 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006752}
6753
6754PyObject *
6755PyUnicode_AsASCIIString(PyObject *unicode)
6756{
6757 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006758}
6759
Victor Stinner99b95382011-07-04 14:23:54 +02006760#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006761
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006762/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006763
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006764#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006765#define NEED_RETRY
6766#endif
6767
Victor Stinner3a50e702011-10-18 21:21:00 +02006768#ifndef WC_ERR_INVALID_CHARS
6769# define WC_ERR_INVALID_CHARS 0x0080
6770#endif
6771
6772static char*
6773code_page_name(UINT code_page, PyObject **obj)
6774{
6775 *obj = NULL;
6776 if (code_page == CP_ACP)
6777 return "mbcs";
6778 if (code_page == CP_UTF7)
6779 return "CP_UTF7";
6780 if (code_page == CP_UTF8)
6781 return "CP_UTF8";
6782
6783 *obj = PyBytes_FromFormat("cp%u", code_page);
6784 if (*obj == NULL)
6785 return NULL;
6786 return PyBytes_AS_STRING(*obj);
6787}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006788
Alexander Belopolsky40018472011-02-26 01:02:56 +00006789static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006790is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006791{
6792 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006793 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006794
Victor Stinner3a50e702011-10-18 21:21:00 +02006795 if (!IsDBCSLeadByteEx(code_page, *curr))
6796 return 0;
6797
6798 prev = CharPrevExA(code_page, s, curr, 0);
6799 if (prev == curr)
6800 return 1;
6801 /* FIXME: This code is limited to "true" double-byte encodings,
6802 as it assumes an incomplete character consists of a single
6803 byte. */
6804 if (curr - prev == 2)
6805 return 1;
6806 if (!IsDBCSLeadByteEx(code_page, *prev))
6807 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006808 return 0;
6809}
6810
Victor Stinner3a50e702011-10-18 21:21:00 +02006811static DWORD
6812decode_code_page_flags(UINT code_page)
6813{
6814 if (code_page == CP_UTF7) {
6815 /* The CP_UTF7 decoder only supports flags=0 */
6816 return 0;
6817 }
6818 else
6819 return MB_ERR_INVALID_CHARS;
6820}
6821
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006822/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006823 * Decode a byte string from a Windows code page into unicode object in strict
6824 * mode.
6825 *
6826 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6827 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006828 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006829static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006830decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006831 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006832 const char *in,
6833 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006834{
Victor Stinner3a50e702011-10-18 21:21:00 +02006835 const DWORD flags = decode_code_page_flags(code_page);
6836 Py_UNICODE *out;
6837 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006838
6839 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006840 assert(insize > 0);
6841 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6842 if (outsize <= 0)
6843 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006844
6845 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006846 /* Create unicode object */
Victor Stinner76a31a62011-11-04 00:05:13 +01006847 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006848 if (*v == NULL)
6849 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006850 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006851 }
6852 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006853 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006854 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner76a31a62011-11-04 00:05:13 +01006855 if (PyUnicode_Resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006856 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006857 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006858 }
6859
6860 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006861 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6862 if (outsize <= 0)
6863 goto error;
6864 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006865
Victor Stinner3a50e702011-10-18 21:21:00 +02006866error:
6867 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6868 return -2;
6869 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006870 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006871}
6872
Victor Stinner3a50e702011-10-18 21:21:00 +02006873/*
6874 * Decode a byte string from a code page into unicode object with an error
6875 * handler.
6876 *
6877 * Returns consumed size if succeed, or raise a WindowsError or
6878 * UnicodeDecodeError exception and returns -1 on error.
6879 */
6880static int
6881decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006882 PyObject **v,
6883 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006884 const char *errors)
6885{
6886 const char *startin = in;
6887 const char *endin = in + size;
6888 const DWORD flags = decode_code_page_flags(code_page);
6889 /* Ideally, we should get reason from FormatMessage. This is the Windows
6890 2000 English version of the message. */
6891 const char *reason = "No mapping for the Unicode character exists "
6892 "in the target code page.";
6893 /* each step cannot decode more than 1 character, but a character can be
6894 represented as a surrogate pair */
6895 wchar_t buffer[2], *startout, *out;
6896 int insize, outsize;
6897 PyObject *errorHandler = NULL;
6898 PyObject *exc = NULL;
6899 PyObject *encoding_obj = NULL;
6900 char *encoding;
6901 DWORD err;
6902 int ret = -1;
6903
6904 assert(size > 0);
6905
6906 encoding = code_page_name(code_page, &encoding_obj);
6907 if (encoding == NULL)
6908 return -1;
6909
6910 if (errors == NULL || strcmp(errors, "strict") == 0) {
6911 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6912 UnicodeDecodeError. */
6913 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6914 if (exc != NULL) {
6915 PyCodec_StrictErrors(exc);
6916 Py_CLEAR(exc);
6917 }
6918 goto error;
6919 }
6920
6921 if (*v == NULL) {
6922 /* Create unicode object */
6923 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6924 PyErr_NoMemory();
6925 goto error;
6926 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006927 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006928 if (*v == NULL)
6929 goto error;
6930 startout = PyUnicode_AS_UNICODE(*v);
6931 }
6932 else {
6933 /* Extend unicode object */
6934 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6935 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6936 PyErr_NoMemory();
6937 goto error;
6938 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006939 if (PyUnicode_Resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006940 goto error;
6941 startout = PyUnicode_AS_UNICODE(*v) + n;
6942 }
6943
6944 /* Decode the byte string character per character */
6945 out = startout;
6946 while (in < endin)
6947 {
6948 /* Decode a character */
6949 insize = 1;
6950 do
6951 {
6952 outsize = MultiByteToWideChar(code_page, flags,
6953 in, insize,
6954 buffer, Py_ARRAY_LENGTH(buffer));
6955 if (outsize > 0)
6956 break;
6957 err = GetLastError();
6958 if (err != ERROR_NO_UNICODE_TRANSLATION
6959 && err != ERROR_INSUFFICIENT_BUFFER)
6960 {
6961 PyErr_SetFromWindowsErr(0);
6962 goto error;
6963 }
6964 insize++;
6965 }
6966 /* 4=maximum length of a UTF-8 sequence */
6967 while (insize <= 4 && (in + insize) <= endin);
6968
6969 if (outsize <= 0) {
6970 Py_ssize_t startinpos, endinpos, outpos;
6971
6972 startinpos = in - startin;
6973 endinpos = startinpos + 1;
6974 outpos = out - PyUnicode_AS_UNICODE(*v);
6975 if (unicode_decode_call_errorhandler(
6976 errors, &errorHandler,
6977 encoding, reason,
6978 &startin, &endin, &startinpos, &endinpos, &exc, &in,
6979 v, &outpos, &out))
6980 {
6981 goto error;
6982 }
6983 }
6984 else {
6985 in += insize;
6986 memcpy(out, buffer, outsize * sizeof(wchar_t));
6987 out += outsize;
6988 }
6989 }
6990
6991 /* write a NUL character at the end */
6992 *out = 0;
6993
6994 /* Extend unicode object */
6995 outsize = out - startout;
6996 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner76a31a62011-11-04 00:05:13 +01006997 if (PyUnicode_Resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006998 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01006999 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007000
7001error:
7002 Py_XDECREF(encoding_obj);
7003 Py_XDECREF(errorHandler);
7004 Py_XDECREF(exc);
7005 return ret;
7006}
7007
Victor Stinner3a50e702011-10-18 21:21:00 +02007008static PyObject *
7009decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007010 const char *s, Py_ssize_t size,
7011 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007012{
Victor Stinner76a31a62011-11-04 00:05:13 +01007013 PyObject *v = NULL;
7014 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007015
Victor Stinner3a50e702011-10-18 21:21:00 +02007016 if (code_page < 0) {
7017 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7018 return NULL;
7019 }
7020
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007021 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007022 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007023
Victor Stinner76a31a62011-11-04 00:05:13 +01007024 do
7025 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007026#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007027 if (size > INT_MAX) {
7028 chunk_size = INT_MAX;
7029 final = 0;
7030 done = 0;
7031 }
7032 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007033#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007034 {
7035 chunk_size = (int)size;
7036 final = (consumed == NULL);
7037 done = 1;
7038 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007039
Victor Stinner76a31a62011-11-04 00:05:13 +01007040 /* Skip trailing lead-byte unless 'final' is set */
7041 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7042 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007043
Victor Stinner76a31a62011-11-04 00:05:13 +01007044 if (chunk_size == 0 && done) {
7045 if (v != NULL)
7046 break;
7047 Py_INCREF(unicode_empty);
7048 return unicode_empty;
7049 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007050
Victor Stinner76a31a62011-11-04 00:05:13 +01007051
7052 converted = decode_code_page_strict(code_page, &v,
7053 s, chunk_size);
7054 if (converted == -2)
7055 converted = decode_code_page_errors(code_page, &v,
7056 s, chunk_size,
7057 errors);
7058 assert(converted != 0);
7059
7060 if (converted < 0) {
7061 Py_XDECREF(v);
7062 return NULL;
7063 }
7064
7065 if (consumed)
7066 *consumed += converted;
7067
7068 s += converted;
7069 size -= converted;
7070 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007071
Victor Stinner17efeed2011-10-04 20:05:46 +02007072#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007073 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007074 Py_DECREF(v);
7075 return NULL;
7076 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007077#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007078 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner76a31a62011-11-04 00:05:13 +01007079 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007080}
7081
Alexander Belopolsky40018472011-02-26 01:02:56 +00007082PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007083PyUnicode_DecodeCodePageStateful(int code_page,
7084 const char *s,
7085 Py_ssize_t size,
7086 const char *errors,
7087 Py_ssize_t *consumed)
7088{
7089 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7090}
7091
7092PyObject *
7093PyUnicode_DecodeMBCSStateful(const char *s,
7094 Py_ssize_t size,
7095 const char *errors,
7096 Py_ssize_t *consumed)
7097{
7098 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7099}
7100
7101PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007102PyUnicode_DecodeMBCS(const char *s,
7103 Py_ssize_t size,
7104 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007105{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007106 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7107}
7108
Victor Stinner3a50e702011-10-18 21:21:00 +02007109static DWORD
7110encode_code_page_flags(UINT code_page, const char *errors)
7111{
7112 if (code_page == CP_UTF8) {
7113 if (winver.dwMajorVersion >= 6)
7114 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7115 and later */
7116 return WC_ERR_INVALID_CHARS;
7117 else
7118 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7119 return 0;
7120 }
7121 else if (code_page == CP_UTF7) {
7122 /* CP_UTF7 only supports flags=0 */
7123 return 0;
7124 }
7125 else {
7126 if (errors != NULL && strcmp(errors, "replace") == 0)
7127 return 0;
7128 else
7129 return WC_NO_BEST_FIT_CHARS;
7130 }
7131}
7132
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007133/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007134 * Encode a Unicode string to a Windows code page into a byte string in strict
7135 * mode.
7136 *
7137 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7138 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007139 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007140static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007141encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007142 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007143 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007144{
Victor Stinner554f3f02010-06-16 23:33:54 +00007145 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007146 BOOL *pusedDefaultChar = &usedDefaultChar;
7147 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007148 PyObject *exc = NULL;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007149 Py_UNICODE *p;
7150 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007151 const DWORD flags = encode_code_page_flags(code_page, NULL);
7152 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007153 /* Create a substring so that we can get the UTF-16 representation
7154 of just the slice under consideration. */
7155 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007156
Martin v. Löwis3d325192011-11-04 18:23:06 +01007157 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007158
Victor Stinner3a50e702011-10-18 21:21:00 +02007159 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007160 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007161 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007162 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007163
Victor Stinner2fc507f2011-11-04 20:06:39 +01007164 substring = PyUnicode_Substring(unicode, offset, offset+len);
7165 if (substring == NULL)
7166 return -1;
7167 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7168 if (p == NULL) {
7169 Py_DECREF(substring);
7170 return -1;
7171 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007172
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007173 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007174 outsize = WideCharToMultiByte(code_page, flags,
7175 p, size,
7176 NULL, 0,
7177 NULL, pusedDefaultChar);
7178 if (outsize <= 0)
7179 goto error;
7180 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007181 if (pusedDefaultChar && *pusedDefaultChar) {
7182 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007183 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007184 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007185
Victor Stinner3a50e702011-10-18 21:21:00 +02007186 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007187 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007188 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007189 if (*outbytes == NULL) {
7190 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007191 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007192 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007193 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007194 }
7195 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007196 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007197 const Py_ssize_t n = PyBytes_Size(*outbytes);
7198 if (outsize > PY_SSIZE_T_MAX - n) {
7199 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007200 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007201 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007202 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007203 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7204 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007205 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007206 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007208 }
7209
7210 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007211 outsize = WideCharToMultiByte(code_page, flags,
7212 p, size,
7213 out, outsize,
7214 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007215 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007216 if (outsize <= 0)
7217 goto error;
7218 if (pusedDefaultChar && *pusedDefaultChar)
7219 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007220 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007221
Victor Stinner3a50e702011-10-18 21:21:00 +02007222error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007223 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007224 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7225 return -2;
7226 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007227 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007228}
7229
Victor Stinner3a50e702011-10-18 21:21:00 +02007230/*
7231 * Encode a Unicode string to a Windows code page into a byte string using a
7232 * error handler.
7233 *
7234 * Returns consumed characters if succeed, or raise a WindowsError and returns
7235 * -1 on other error.
7236 */
7237static int
7238encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007239 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007240 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007241{
Victor Stinner3a50e702011-10-18 21:21:00 +02007242 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007243 Py_ssize_t pos = unicode_offset;
7244 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007245 /* Ideally, we should get reason from FormatMessage. This is the Windows
7246 2000 English version of the message. */
7247 const char *reason = "invalid character";
7248 /* 4=maximum length of a UTF-8 sequence */
7249 char buffer[4];
7250 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7251 Py_ssize_t outsize;
7252 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007253 PyObject *errorHandler = NULL;
7254 PyObject *exc = NULL;
7255 PyObject *encoding_obj = NULL;
7256 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007257 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007258 PyObject *rep;
7259 int ret = -1;
7260
7261 assert(insize > 0);
7262
7263 encoding = code_page_name(code_page, &encoding_obj);
7264 if (encoding == NULL)
7265 return -1;
7266
7267 if (errors == NULL || strcmp(errors, "strict") == 0) {
7268 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7269 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007270 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007271 if (exc != NULL) {
7272 PyCodec_StrictErrors(exc);
7273 Py_DECREF(exc);
7274 }
7275 Py_XDECREF(encoding_obj);
7276 return -1;
7277 }
7278
7279 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7280 pusedDefaultChar = &usedDefaultChar;
7281 else
7282 pusedDefaultChar = NULL;
7283
7284 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7285 PyErr_NoMemory();
7286 goto error;
7287 }
7288 outsize = insize * Py_ARRAY_LENGTH(buffer);
7289
7290 if (*outbytes == NULL) {
7291 /* Create string object */
7292 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7293 if (*outbytes == NULL)
7294 goto error;
7295 out = PyBytes_AS_STRING(*outbytes);
7296 }
7297 else {
7298 /* Extend string object */
7299 Py_ssize_t n = PyBytes_Size(*outbytes);
7300 if (n > PY_SSIZE_T_MAX - outsize) {
7301 PyErr_NoMemory();
7302 goto error;
7303 }
7304 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7305 goto error;
7306 out = PyBytes_AS_STRING(*outbytes) + n;
7307 }
7308
7309 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007310 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007311 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007312 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7313 wchar_t chars[2];
7314 int charsize;
7315 if (ch < 0x10000) {
7316 chars[0] = (wchar_t)ch;
7317 charsize = 1;
7318 }
7319 else {
7320 ch -= 0x10000;
7321 chars[0] = 0xd800 + (ch >> 10);
7322 chars[1] = 0xdc00 + (ch & 0x3ff);
7323 charsize = 2;
7324 }
7325
Victor Stinner3a50e702011-10-18 21:21:00 +02007326 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007327 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007328 buffer, Py_ARRAY_LENGTH(buffer),
7329 NULL, pusedDefaultChar);
7330 if (outsize > 0) {
7331 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7332 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007333 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007334 memcpy(out, buffer, outsize);
7335 out += outsize;
7336 continue;
7337 }
7338 }
7339 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7340 PyErr_SetFromWindowsErr(0);
7341 goto error;
7342 }
7343
Victor Stinner3a50e702011-10-18 21:21:00 +02007344 rep = unicode_encode_call_errorhandler(
7345 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007346 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007347 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007348 if (rep == NULL)
7349 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007350 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007351
7352 if (PyBytes_Check(rep)) {
7353 outsize = PyBytes_GET_SIZE(rep);
7354 if (outsize != 1) {
7355 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7356 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7357 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7358 Py_DECREF(rep);
7359 goto error;
7360 }
7361 out = PyBytes_AS_STRING(*outbytes) + offset;
7362 }
7363 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7364 out += outsize;
7365 }
7366 else {
7367 Py_ssize_t i;
7368 enum PyUnicode_Kind kind;
7369 void *data;
7370
7371 if (PyUnicode_READY(rep) < 0) {
7372 Py_DECREF(rep);
7373 goto error;
7374 }
7375
7376 outsize = PyUnicode_GET_LENGTH(rep);
7377 if (outsize != 1) {
7378 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7379 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7380 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7381 Py_DECREF(rep);
7382 goto error;
7383 }
7384 out = PyBytes_AS_STRING(*outbytes) + offset;
7385 }
7386 kind = PyUnicode_KIND(rep);
7387 data = PyUnicode_DATA(rep);
7388 for (i=0; i < outsize; i++) {
7389 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7390 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007391 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007392 encoding, unicode,
7393 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007394 "unable to encode error handler result to ASCII");
7395 Py_DECREF(rep);
7396 goto error;
7397 }
7398 *out = (unsigned char)ch;
7399 out++;
7400 }
7401 }
7402 Py_DECREF(rep);
7403 }
7404 /* write a NUL byte */
7405 *out = 0;
7406 outsize = out - PyBytes_AS_STRING(*outbytes);
7407 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7408 if (_PyBytes_Resize(outbytes, outsize) < 0)
7409 goto error;
7410 ret = 0;
7411
7412error:
7413 Py_XDECREF(encoding_obj);
7414 Py_XDECREF(errorHandler);
7415 Py_XDECREF(exc);
7416 return ret;
7417}
7418
Victor Stinner3a50e702011-10-18 21:21:00 +02007419static PyObject *
7420encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007421 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007422 const char *errors)
7423{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007424 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007425 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007426 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007427 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007428
Victor Stinner2fc507f2011-11-04 20:06:39 +01007429 if (PyUnicode_READY(unicode) < 0)
7430 return NULL;
7431 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007432
Victor Stinner3a50e702011-10-18 21:21:00 +02007433 if (code_page < 0) {
7434 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7435 return NULL;
7436 }
7437
Martin v. Löwis3d325192011-11-04 18:23:06 +01007438 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007439 return PyBytes_FromStringAndSize(NULL, 0);
7440
Victor Stinner7581cef2011-11-03 22:32:33 +01007441 offset = 0;
7442 do
7443 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007444#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007445 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007446 chunks. */
7447 if (len > INT_MAX/2) {
7448 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007449 done = 0;
7450 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007451 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007452#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007453 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007454 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007455 done = 1;
7456 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007457
Victor Stinner76a31a62011-11-04 00:05:13 +01007458 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007459 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007460 errors);
7461 if (ret == -2)
7462 ret = encode_code_page_errors(code_page, &outbytes,
7463 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007464 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007465 if (ret < 0) {
7466 Py_XDECREF(outbytes);
7467 return NULL;
7468 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007469
Victor Stinner7581cef2011-11-03 22:32:33 +01007470 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007471 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007472 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007473
Victor Stinner3a50e702011-10-18 21:21:00 +02007474 return outbytes;
7475}
7476
7477PyObject *
7478PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7479 Py_ssize_t size,
7480 const char *errors)
7481{
Victor Stinner7581cef2011-11-03 22:32:33 +01007482 PyObject *unicode, *res;
7483 unicode = PyUnicode_FromUnicode(p, size);
7484 if (unicode == NULL)
7485 return NULL;
7486 res = encode_code_page(CP_ACP, unicode, errors);
7487 Py_DECREF(unicode);
7488 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007489}
7490
7491PyObject *
7492PyUnicode_EncodeCodePage(int code_page,
7493 PyObject *unicode,
7494 const char *errors)
7495{
Victor Stinner7581cef2011-11-03 22:32:33 +01007496 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007497}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007498
Alexander Belopolsky40018472011-02-26 01:02:56 +00007499PyObject *
7500PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007501{
7502 if (!PyUnicode_Check(unicode)) {
7503 PyErr_BadArgument();
7504 return NULL;
7505 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007506 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007507}
7508
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007509#undef NEED_RETRY
7510
Victor Stinner99b95382011-07-04 14:23:54 +02007511#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007512
Guido van Rossumd57fd912000-03-10 22:53:23 +00007513/* --- Character Mapping Codec -------------------------------------------- */
7514
Alexander Belopolsky40018472011-02-26 01:02:56 +00007515PyObject *
7516PyUnicode_DecodeCharmap(const char *s,
7517 Py_ssize_t size,
7518 PyObject *mapping,
7519 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007520{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007521 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007522 Py_ssize_t startinpos;
7523 Py_ssize_t endinpos;
7524 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007525 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007526 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007527 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007528 PyObject *errorHandler = NULL;
7529 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007530 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007531 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00007532
Guido van Rossumd57fd912000-03-10 22:53:23 +00007533 /* Default to Latin-1 */
7534 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007535 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007536
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007537 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007538 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007539 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007540 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007541 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007542 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007543 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007544 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007545 mapstring = PyUnicode_AS_UNICODE(mapping);
7546 maplen = PyUnicode_GET_SIZE(mapping);
7547 while (s < e) {
7548 unsigned char ch = *s;
7549 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007550
Benjamin Peterson29060642009-01-31 22:14:21 +00007551 if (ch < maplen)
7552 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00007553
Benjamin Peterson29060642009-01-31 22:14:21 +00007554 if (x == 0xfffe) {
7555 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007556 startinpos = s-starts;
7557 endinpos = startinpos+1;
7558 if (unicode_decode_call_errorhandler(
7559 errors, &errorHandler,
7560 "charmap", "character maps to <undefined>",
7561 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007562 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007563 goto onError;
7564 }
7565 continue;
7566 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007567 if (unicode_putchar(&v, &outpos, x) < 0)
7568 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007569 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007570 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007571 }
7572 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007573 while (s < e) {
7574 unsigned char ch = *s;
7575 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007576
Benjamin Peterson29060642009-01-31 22:14:21 +00007577 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7578 w = PyLong_FromLong((long)ch);
7579 if (w == NULL)
7580 goto onError;
7581 x = PyObject_GetItem(mapping, w);
7582 Py_DECREF(w);
7583 if (x == NULL) {
7584 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7585 /* No mapping found means: mapping is undefined. */
7586 PyErr_Clear();
7587 x = Py_None;
7588 Py_INCREF(x);
7589 } else
7590 goto onError;
7591 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007592
Benjamin Peterson29060642009-01-31 22:14:21 +00007593 /* Apply mapping */
7594 if (PyLong_Check(x)) {
7595 long value = PyLong_AS_LONG(x);
7596 if (value < 0 || value > 65535) {
7597 PyErr_SetString(PyExc_TypeError,
7598 "character mapping must be in range(65536)");
7599 Py_DECREF(x);
7600 goto onError;
7601 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007602 if (unicode_putchar(&v, &outpos, value) < 0)
7603 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007604 }
7605 else if (x == Py_None) {
7606 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007607 startinpos = s-starts;
7608 endinpos = startinpos+1;
7609 if (unicode_decode_call_errorhandler(
7610 errors, &errorHandler,
7611 "charmap", "character maps to <undefined>",
7612 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007613 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007614 Py_DECREF(x);
7615 goto onError;
7616 }
7617 Py_DECREF(x);
7618 continue;
7619 }
7620 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007621 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007622
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007623 if (PyUnicode_READY(x) < 0)
7624 goto onError;
7625 targetsize = PyUnicode_GET_LENGTH(x);
7626
7627 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007628 /* 1-1 mapping */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007629 if (unicode_putchar(&v, &outpos,
7630 PyUnicode_READ_CHAR(x, 0)) < 0)
7631 goto onError;
7632 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007633 else if (targetsize > 1) {
7634 /* 1-n mapping */
7635 if (targetsize > extrachars) {
7636 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007637 Py_ssize_t needed = (targetsize - extrachars) + \
7638 (targetsize << 2);
7639 extrachars += needed;
7640 /* XXX overflow detection missing */
Victor Stinner7931d9a2011-11-04 00:22:48 +01007641 if (PyUnicode_Resize(&v,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007642 PyUnicode_GET_LENGTH(v) + needed) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007643 Py_DECREF(x);
7644 goto onError;
7645 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007646 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007647 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7648 goto onError;
7649 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7650 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007651 extrachars -= targetsize;
7652 }
7653 /* 1-0 mapping: skip the character */
7654 }
7655 else {
7656 /* wrong return value */
7657 PyErr_SetString(PyExc_TypeError,
7658 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007659 Py_DECREF(x);
7660 goto onError;
7661 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007662 Py_DECREF(x);
7663 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007664 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007665 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007666 if (PyUnicode_Resize(&v, outpos) < 0)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007667 Py_XDECREF(errorHandler);
7668 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007669 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01007670 return v;
Tim Petersced69f82003-09-16 20:30:58 +00007671
Benjamin Peterson29060642009-01-31 22:14:21 +00007672 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007673 Py_XDECREF(errorHandler);
7674 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007675 Py_XDECREF(v);
7676 return NULL;
7677}
7678
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007679/* Charmap encoding: the lookup table */
7680
Alexander Belopolsky40018472011-02-26 01:02:56 +00007681struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007682 PyObject_HEAD
7683 unsigned char level1[32];
7684 int count2, count3;
7685 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007686};
7687
7688static PyObject*
7689encoding_map_size(PyObject *obj, PyObject* args)
7690{
7691 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007692 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007693 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007694}
7695
7696static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007697 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007698 PyDoc_STR("Return the size (in bytes) of this object") },
7699 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007700};
7701
7702static void
7703encoding_map_dealloc(PyObject* o)
7704{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007705 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007706}
7707
7708static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007709 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007710 "EncodingMap", /*tp_name*/
7711 sizeof(struct encoding_map), /*tp_basicsize*/
7712 0, /*tp_itemsize*/
7713 /* methods */
7714 encoding_map_dealloc, /*tp_dealloc*/
7715 0, /*tp_print*/
7716 0, /*tp_getattr*/
7717 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007718 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007719 0, /*tp_repr*/
7720 0, /*tp_as_number*/
7721 0, /*tp_as_sequence*/
7722 0, /*tp_as_mapping*/
7723 0, /*tp_hash*/
7724 0, /*tp_call*/
7725 0, /*tp_str*/
7726 0, /*tp_getattro*/
7727 0, /*tp_setattro*/
7728 0, /*tp_as_buffer*/
7729 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7730 0, /*tp_doc*/
7731 0, /*tp_traverse*/
7732 0, /*tp_clear*/
7733 0, /*tp_richcompare*/
7734 0, /*tp_weaklistoffset*/
7735 0, /*tp_iter*/
7736 0, /*tp_iternext*/
7737 encoding_map_methods, /*tp_methods*/
7738 0, /*tp_members*/
7739 0, /*tp_getset*/
7740 0, /*tp_base*/
7741 0, /*tp_dict*/
7742 0, /*tp_descr_get*/
7743 0, /*tp_descr_set*/
7744 0, /*tp_dictoffset*/
7745 0, /*tp_init*/
7746 0, /*tp_alloc*/
7747 0, /*tp_new*/
7748 0, /*tp_free*/
7749 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007750};
7751
7752PyObject*
7753PyUnicode_BuildEncodingMap(PyObject* string)
7754{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007755 PyObject *result;
7756 struct encoding_map *mresult;
7757 int i;
7758 int need_dict = 0;
7759 unsigned char level1[32];
7760 unsigned char level2[512];
7761 unsigned char *mlevel1, *mlevel2, *mlevel3;
7762 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007763 int kind;
7764 void *data;
7765 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007767 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007768 PyErr_BadArgument();
7769 return NULL;
7770 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007771 kind = PyUnicode_KIND(string);
7772 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007773 memset(level1, 0xFF, sizeof level1);
7774 memset(level2, 0xFF, sizeof level2);
7775
7776 /* If there isn't a one-to-one mapping of NULL to \0,
7777 or if there are non-BMP characters, we need to use
7778 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007779 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007780 need_dict = 1;
7781 for (i = 1; i < 256; i++) {
7782 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007783 ch = PyUnicode_READ(kind, data, i);
7784 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007785 need_dict = 1;
7786 break;
7787 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007788 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007789 /* unmapped character */
7790 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007791 l1 = ch >> 11;
7792 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007793 if (level1[l1] == 0xFF)
7794 level1[l1] = count2++;
7795 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007796 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007797 }
7798
7799 if (count2 >= 0xFF || count3 >= 0xFF)
7800 need_dict = 1;
7801
7802 if (need_dict) {
7803 PyObject *result = PyDict_New();
7804 PyObject *key, *value;
7805 if (!result)
7806 return NULL;
7807 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007808 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007809 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007810 if (!key || !value)
7811 goto failed1;
7812 if (PyDict_SetItem(result, key, value) == -1)
7813 goto failed1;
7814 Py_DECREF(key);
7815 Py_DECREF(value);
7816 }
7817 return result;
7818 failed1:
7819 Py_XDECREF(key);
7820 Py_XDECREF(value);
7821 Py_DECREF(result);
7822 return NULL;
7823 }
7824
7825 /* Create a three-level trie */
7826 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7827 16*count2 + 128*count3 - 1);
7828 if (!result)
7829 return PyErr_NoMemory();
7830 PyObject_Init(result, &EncodingMapType);
7831 mresult = (struct encoding_map*)result;
7832 mresult->count2 = count2;
7833 mresult->count3 = count3;
7834 mlevel1 = mresult->level1;
7835 mlevel2 = mresult->level23;
7836 mlevel3 = mresult->level23 + 16*count2;
7837 memcpy(mlevel1, level1, 32);
7838 memset(mlevel2, 0xFF, 16*count2);
7839 memset(mlevel3, 0, 128*count3);
7840 count3 = 0;
7841 for (i = 1; i < 256; i++) {
7842 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007843 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007844 /* unmapped character */
7845 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007846 o1 = PyUnicode_READ(kind, data, i)>>11;
7847 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007848 i2 = 16*mlevel1[o1] + o2;
7849 if (mlevel2[i2] == 0xFF)
7850 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007851 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007852 i3 = 128*mlevel2[i2] + o3;
7853 mlevel3[i3] = i;
7854 }
7855 return result;
7856}
7857
7858static int
7859encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
7860{
7861 struct encoding_map *map = (struct encoding_map*)mapping;
7862 int l1 = c>>11;
7863 int l2 = (c>>7) & 0xF;
7864 int l3 = c & 0x7F;
7865 int i;
7866
7867#ifdef Py_UNICODE_WIDE
7868 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007869 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007870 }
7871#endif
7872 if (c == 0)
7873 return 0;
7874 /* level 1*/
7875 i = map->level1[l1];
7876 if (i == 0xFF) {
7877 return -1;
7878 }
7879 /* level 2*/
7880 i = map->level23[16*i+l2];
7881 if (i == 0xFF) {
7882 return -1;
7883 }
7884 /* level 3 */
7885 i = map->level23[16*map->count2 + 128*i + l3];
7886 if (i == 0) {
7887 return -1;
7888 }
7889 return i;
7890}
7891
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007892/* Lookup the character ch in the mapping. If the character
7893 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007894 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007895static PyObject *
7896charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007897{
Christian Heimes217cfd12007-12-02 14:31:20 +00007898 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007899 PyObject *x;
7900
7901 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007902 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007903 x = PyObject_GetItem(mapping, w);
7904 Py_DECREF(w);
7905 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007906 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7907 /* No mapping found means: mapping is undefined. */
7908 PyErr_Clear();
7909 x = Py_None;
7910 Py_INCREF(x);
7911 return x;
7912 } else
7913 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007914 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007915 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007916 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007917 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007918 long value = PyLong_AS_LONG(x);
7919 if (value < 0 || value > 255) {
7920 PyErr_SetString(PyExc_TypeError,
7921 "character mapping must be in range(256)");
7922 Py_DECREF(x);
7923 return NULL;
7924 }
7925 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007926 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007927 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007928 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007929 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007930 /* wrong return value */
7931 PyErr_Format(PyExc_TypeError,
7932 "character mapping must return integer, bytes or None, not %.400s",
7933 x->ob_type->tp_name);
7934 Py_DECREF(x);
7935 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007936 }
7937}
7938
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007939static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007940charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007941{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007942 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7943 /* exponentially overallocate to minimize reallocations */
7944 if (requiredsize < 2*outsize)
7945 requiredsize = 2*outsize;
7946 if (_PyBytes_Resize(outobj, requiredsize))
7947 return -1;
7948 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007949}
7950
Benjamin Peterson14339b62009-01-31 16:36:08 +00007951typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007952 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007953} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007954/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007955 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007956 space is available. Return a new reference to the object that
7957 was put in the output buffer, or Py_None, if the mapping was undefined
7958 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007959 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007960static charmapencode_result
7961charmapencode_output(Py_UNICODE c, PyObject *mapping,
7962 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007963{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007964 PyObject *rep;
7965 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007966 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007967
Christian Heimes90aa7642007-12-19 02:45:37 +00007968 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007969 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007970 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007971 if (res == -1)
7972 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007973 if (outsize<requiredsize)
7974 if (charmapencode_resize(outobj, outpos, requiredsize))
7975 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007976 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007977 outstart[(*outpos)++] = (char)res;
7978 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007979 }
7980
7981 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007982 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007983 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007984 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007985 Py_DECREF(rep);
7986 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007987 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007988 if (PyLong_Check(rep)) {
7989 Py_ssize_t requiredsize = *outpos+1;
7990 if (outsize<requiredsize)
7991 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7992 Py_DECREF(rep);
7993 return enc_EXCEPTION;
7994 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007995 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007996 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007997 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007998 else {
7999 const char *repchars = PyBytes_AS_STRING(rep);
8000 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8001 Py_ssize_t requiredsize = *outpos+repsize;
8002 if (outsize<requiredsize)
8003 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8004 Py_DECREF(rep);
8005 return enc_EXCEPTION;
8006 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008007 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008008 memcpy(outstart + *outpos, repchars, repsize);
8009 *outpos += repsize;
8010 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008011 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008012 Py_DECREF(rep);
8013 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008014}
8015
8016/* handle an error in PyUnicode_EncodeCharmap
8017 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008018static int
8019charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008020 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008021 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008022 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008023 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008024{
8025 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008026 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008027 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008028 Py_UNICODE *uni2;
8029 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008030 Py_ssize_t collstartpos = *inpos;
8031 Py_ssize_t collendpos = *inpos+1;
8032 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008033 char *encoding = "charmap";
8034 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008035 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008036 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008037 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008038
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008039 if (PyUnicode_READY(unicode) < 0)
8040 return -1;
8041 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008042 /* find all unencodable characters */
8043 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008044 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008045 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008046 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008047 val = encoding_map_lookup(ch, mapping);
8048 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008049 break;
8050 ++collendpos;
8051 continue;
8052 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008053
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008054 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8055 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008056 if (rep==NULL)
8057 return -1;
8058 else if (rep!=Py_None) {
8059 Py_DECREF(rep);
8060 break;
8061 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008062 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008063 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008064 }
8065 /* cache callback name lookup
8066 * (if not done yet, i.e. it's the first error) */
8067 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008068 if ((errors==NULL) || (!strcmp(errors, "strict")))
8069 *known_errorHandler = 1;
8070 else if (!strcmp(errors, "replace"))
8071 *known_errorHandler = 2;
8072 else if (!strcmp(errors, "ignore"))
8073 *known_errorHandler = 3;
8074 else if (!strcmp(errors, "xmlcharrefreplace"))
8075 *known_errorHandler = 4;
8076 else
8077 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008078 }
8079 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008080 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008081 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008082 return -1;
8083 case 2: /* replace */
8084 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008085 x = charmapencode_output('?', mapping, res, respos);
8086 if (x==enc_EXCEPTION) {
8087 return -1;
8088 }
8089 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008090 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008091 return -1;
8092 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008093 }
8094 /* fall through */
8095 case 3: /* ignore */
8096 *inpos = collendpos;
8097 break;
8098 case 4: /* xmlcharrefreplace */
8099 /* generate replacement (temporarily (mis)uses p) */
8100 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008101 char buffer[2+29+1+1];
8102 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008103 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008104 for (cp = buffer; *cp; ++cp) {
8105 x = charmapencode_output(*cp, mapping, res, respos);
8106 if (x==enc_EXCEPTION)
8107 return -1;
8108 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008109 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008110 return -1;
8111 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008112 }
8113 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008114 *inpos = collendpos;
8115 break;
8116 default:
8117 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008118 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008119 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008120 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008121 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008122 if (PyBytes_Check(repunicode)) {
8123 /* Directly copy bytes result to output. */
8124 Py_ssize_t outsize = PyBytes_Size(*res);
8125 Py_ssize_t requiredsize;
8126 repsize = PyBytes_Size(repunicode);
8127 requiredsize = *respos + repsize;
8128 if (requiredsize > outsize)
8129 /* Make room for all additional bytes. */
8130 if (charmapencode_resize(res, respos, requiredsize)) {
8131 Py_DECREF(repunicode);
8132 return -1;
8133 }
8134 memcpy(PyBytes_AsString(*res) + *respos,
8135 PyBytes_AsString(repunicode), repsize);
8136 *respos += repsize;
8137 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008138 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008139 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008140 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008141 /* generate replacement */
8142 repsize = PyUnicode_GET_SIZE(repunicode);
8143 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008144 x = charmapencode_output(*uni2, mapping, res, respos);
8145 if (x==enc_EXCEPTION) {
8146 return -1;
8147 }
8148 else if (x==enc_FAILED) {
8149 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008150 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008151 return -1;
8152 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008153 }
8154 *inpos = newpos;
8155 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008156 }
8157 return 0;
8158}
8159
Alexander Belopolsky40018472011-02-26 01:02:56 +00008160PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008161_PyUnicode_EncodeCharmap(PyObject *unicode,
8162 PyObject *mapping,
8163 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008164{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008165 /* output object */
8166 PyObject *res = NULL;
8167 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008168 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008169 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008170 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008171 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008172 PyObject *errorHandler = NULL;
8173 PyObject *exc = NULL;
8174 /* the following variable is used for caching string comparisons
8175 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8176 * 3=ignore, 4=xmlcharrefreplace */
8177 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008178
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008179 if (PyUnicode_READY(unicode) < 0)
8180 return NULL;
8181 size = PyUnicode_GET_LENGTH(unicode);
8182
Guido van Rossumd57fd912000-03-10 22:53:23 +00008183 /* Default to Latin-1 */
8184 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008185 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008186
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008187 /* allocate enough for a simple encoding without
8188 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008189 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008190 if (res == NULL)
8191 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008192 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008193 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008194
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008195 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008196 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008197 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008198 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008199 if (x==enc_EXCEPTION) /* error */
8200 goto onError;
8201 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008202 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008203 &exc,
8204 &known_errorHandler, &errorHandler, errors,
8205 &res, &respos)) {
8206 goto onError;
8207 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008208 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008209 else
8210 /* done with this character => adjust input position */
8211 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008212 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008213
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008214 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008215 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008216 if (_PyBytes_Resize(&res, respos) < 0)
8217 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008218
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008219 Py_XDECREF(exc);
8220 Py_XDECREF(errorHandler);
8221 return res;
8222
Benjamin Peterson29060642009-01-31 22:14:21 +00008223 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008224 Py_XDECREF(res);
8225 Py_XDECREF(exc);
8226 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008227 return NULL;
8228}
8229
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008230/* Deprecated */
8231PyObject *
8232PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8233 Py_ssize_t size,
8234 PyObject *mapping,
8235 const char *errors)
8236{
8237 PyObject *result;
8238 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8239 if (unicode == NULL)
8240 return NULL;
8241 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8242 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008243 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008244}
8245
Alexander Belopolsky40018472011-02-26 01:02:56 +00008246PyObject *
8247PyUnicode_AsCharmapString(PyObject *unicode,
8248 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008249{
8250 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008251 PyErr_BadArgument();
8252 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008253 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008254 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008255}
8256
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008257/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008258static void
8259make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008260 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008261 Py_ssize_t startpos, Py_ssize_t endpos,
8262 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008263{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008264 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008265 *exceptionObject = _PyUnicodeTranslateError_Create(
8266 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008267 }
8268 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008269 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8270 goto onError;
8271 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8272 goto onError;
8273 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8274 goto onError;
8275 return;
8276 onError:
8277 Py_DECREF(*exceptionObject);
8278 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008279 }
8280}
8281
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008282/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008283static void
8284raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008285 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008286 Py_ssize_t startpos, Py_ssize_t endpos,
8287 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008288{
8289 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008290 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008291 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008292 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008293}
8294
8295/* error handling callback helper:
8296 build arguments, call the callback and check the arguments,
8297 put the result into newpos and return the replacement string, which
8298 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008299static PyObject *
8300unicode_translate_call_errorhandler(const char *errors,
8301 PyObject **errorHandler,
8302 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008303 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008304 Py_ssize_t startpos, Py_ssize_t endpos,
8305 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008306{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008307 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008308
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008309 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008310 PyObject *restuple;
8311 PyObject *resunicode;
8312
8313 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008314 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008315 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008316 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008317 }
8318
8319 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008320 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008321 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008322 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008323
8324 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008325 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008326 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008327 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008328 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008329 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008330 Py_DECREF(restuple);
8331 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008332 }
8333 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008334 &resunicode, &i_newpos)) {
8335 Py_DECREF(restuple);
8336 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008337 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008338 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008339 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008340 else
8341 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008342 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008343 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8344 Py_DECREF(restuple);
8345 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008346 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008347 Py_INCREF(resunicode);
8348 Py_DECREF(restuple);
8349 return resunicode;
8350}
8351
8352/* Lookup the character ch in the mapping and put the result in result,
8353 which must be decrefed by the caller.
8354 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008355static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008356charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008357{
Christian Heimes217cfd12007-12-02 14:31:20 +00008358 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008359 PyObject *x;
8360
8361 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008362 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008363 x = PyObject_GetItem(mapping, w);
8364 Py_DECREF(w);
8365 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008366 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8367 /* No mapping found means: use 1:1 mapping. */
8368 PyErr_Clear();
8369 *result = NULL;
8370 return 0;
8371 } else
8372 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008373 }
8374 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008375 *result = x;
8376 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008377 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008378 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008379 long value = PyLong_AS_LONG(x);
8380 long max = PyUnicode_GetMax();
8381 if (value < 0 || value > max) {
8382 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008383 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008384 Py_DECREF(x);
8385 return -1;
8386 }
8387 *result = x;
8388 return 0;
8389 }
8390 else if (PyUnicode_Check(x)) {
8391 *result = x;
8392 return 0;
8393 }
8394 else {
8395 /* wrong return value */
8396 PyErr_SetString(PyExc_TypeError,
8397 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008398 Py_DECREF(x);
8399 return -1;
8400 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008401}
8402/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008403 if not reallocate and adjust various state variables.
8404 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008405static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008406charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008407 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008408{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008409 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008410 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008411 /* exponentially overallocate to minimize reallocations */
8412 if (requiredsize < 2 * oldsize)
8413 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008414 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8415 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008417 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008418 }
8419 return 0;
8420}
8421/* lookup the character, put the result in the output string and adjust
8422 various state variables. Return a new reference to the object that
8423 was put in the output buffer in *result, or Py_None, if the mapping was
8424 undefined (in which case no character was written).
8425 The called must decref result.
8426 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008427static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008428charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8429 PyObject *mapping, Py_UCS4 **output,
8430 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008431 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008432{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008433 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8434 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008435 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008436 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008438 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008439 }
8440 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008441 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008442 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008443 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008444 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008445 }
8446 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008447 Py_ssize_t repsize;
8448 if (PyUnicode_READY(*res) == -1)
8449 return -1;
8450 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008451 if (repsize==1) {
8452 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008453 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008454 }
8455 else if (repsize!=0) {
8456 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008457 Py_ssize_t requiredsize = *opos +
8458 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008459 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008460 Py_ssize_t i;
8461 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008462 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008463 for(i = 0; i < repsize; i++)
8464 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008465 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008466 }
8467 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008469 return 0;
8470}
8471
Alexander Belopolsky40018472011-02-26 01:02:56 +00008472PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008473_PyUnicode_TranslateCharmap(PyObject *input,
8474 PyObject *mapping,
8475 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008476{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008477 /* input object */
8478 char *idata;
8479 Py_ssize_t size, i;
8480 int kind;
8481 /* output buffer */
8482 Py_UCS4 *output = NULL;
8483 Py_ssize_t osize;
8484 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008485 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008486 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008487 char *reason = "character maps to <undefined>";
8488 PyObject *errorHandler = NULL;
8489 PyObject *exc = NULL;
8490 /* the following variable is used for caching string comparisons
8491 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8492 * 3=ignore, 4=xmlcharrefreplace */
8493 int known_errorHandler = -1;
8494
Guido van Rossumd57fd912000-03-10 22:53:23 +00008495 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008496 PyErr_BadArgument();
8497 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008498 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008499
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008500 if (PyUnicode_READY(input) == -1)
8501 return NULL;
8502 idata = (char*)PyUnicode_DATA(input);
8503 kind = PyUnicode_KIND(input);
8504 size = PyUnicode_GET_LENGTH(input);
8505 i = 0;
8506
8507 if (size == 0) {
8508 Py_INCREF(input);
8509 return input;
8510 }
8511
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008512 /* allocate enough for a simple 1:1 translation without
8513 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008514 osize = size;
8515 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8516 opos = 0;
8517 if (output == NULL) {
8518 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008519 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008520 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008521
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008522 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008523 /* try to encode it */
8524 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008525 if (charmaptranslate_output(input, i, mapping,
8526 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008527 Py_XDECREF(x);
8528 goto onError;
8529 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008530 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008531 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008532 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008533 else { /* untranslatable character */
8534 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8535 Py_ssize_t repsize;
8536 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008537 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008538 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008539 Py_ssize_t collstart = i;
8540 Py_ssize_t collend = i+1;
8541 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008542
Benjamin Peterson29060642009-01-31 22:14:21 +00008543 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008544 while (collend < size) {
8545 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008546 goto onError;
8547 Py_XDECREF(x);
8548 if (x!=Py_None)
8549 break;
8550 ++collend;
8551 }
8552 /* cache callback name lookup
8553 * (if not done yet, i.e. it's the first error) */
8554 if (known_errorHandler==-1) {
8555 if ((errors==NULL) || (!strcmp(errors, "strict")))
8556 known_errorHandler = 1;
8557 else if (!strcmp(errors, "replace"))
8558 known_errorHandler = 2;
8559 else if (!strcmp(errors, "ignore"))
8560 known_errorHandler = 3;
8561 else if (!strcmp(errors, "xmlcharrefreplace"))
8562 known_errorHandler = 4;
8563 else
8564 known_errorHandler = 0;
8565 }
8566 switch (known_errorHandler) {
8567 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008568 raise_translate_exception(&exc, input, collstart,
8569 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008570 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008571 case 2: /* replace */
8572 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008573 for (coll = collstart; coll<collend; coll++)
8574 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008575 /* fall through */
8576 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008577 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008578 break;
8579 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008580 /* generate replacement (temporarily (mis)uses i) */
8581 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008582 char buffer[2+29+1+1];
8583 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008584 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8585 if (charmaptranslate_makespace(&output, &osize,
8586 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008587 goto onError;
8588 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008589 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008590 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008591 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008592 break;
8593 default:
8594 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008595 reason, input, &exc,
8596 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008597 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008598 goto onError;
8599 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008600 repsize = PyUnicode_GET_LENGTH(repunicode);
8601 if (charmaptranslate_makespace(&output, &osize,
8602 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008603 Py_DECREF(repunicode);
8604 goto onError;
8605 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008606 for (uni2 = 0; repsize-->0; ++uni2)
8607 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8608 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008609 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008610 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008611 }
8612 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008613 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8614 if (!res)
8615 goto onError;
8616 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008617 Py_XDECREF(exc);
8618 Py_XDECREF(errorHandler);
8619 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008620
Benjamin Peterson29060642009-01-31 22:14:21 +00008621 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008622 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008623 Py_XDECREF(exc);
8624 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008625 return NULL;
8626}
8627
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008628/* Deprecated. Use PyUnicode_Translate instead. */
8629PyObject *
8630PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8631 Py_ssize_t size,
8632 PyObject *mapping,
8633 const char *errors)
8634{
8635 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8636 if (!unicode)
8637 return NULL;
8638 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8639}
8640
Alexander Belopolsky40018472011-02-26 01:02:56 +00008641PyObject *
8642PyUnicode_Translate(PyObject *str,
8643 PyObject *mapping,
8644 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008645{
8646 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008647
Guido van Rossumd57fd912000-03-10 22:53:23 +00008648 str = PyUnicode_FromObject(str);
8649 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008650 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008651 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008652 Py_DECREF(str);
8653 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008654
Benjamin Peterson29060642009-01-31 22:14:21 +00008655 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008656 Py_XDECREF(str);
8657 return NULL;
8658}
Tim Petersced69f82003-09-16 20:30:58 +00008659
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008660static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008661fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008662{
8663 /* No need to call PyUnicode_READY(self) because this function is only
8664 called as a callback from fixup() which does it already. */
8665 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8666 const int kind = PyUnicode_KIND(self);
8667 void *data = PyUnicode_DATA(self);
8668 Py_UCS4 maxchar = 0, ch, fixed;
8669 Py_ssize_t i;
8670
8671 for (i = 0; i < len; ++i) {
8672 ch = PyUnicode_READ(kind, data, i);
8673 fixed = 0;
8674 if (ch > 127) {
8675 if (Py_UNICODE_ISSPACE(ch))
8676 fixed = ' ';
8677 else {
8678 const int decimal = Py_UNICODE_TODECIMAL(ch);
8679 if (decimal >= 0)
8680 fixed = '0' + decimal;
8681 }
8682 if (fixed != 0) {
8683 if (fixed > maxchar)
8684 maxchar = fixed;
8685 PyUnicode_WRITE(kind, data, i, fixed);
8686 }
8687 else if (ch > maxchar)
8688 maxchar = ch;
8689 }
8690 else if (ch > maxchar)
8691 maxchar = ch;
8692 }
8693
8694 return maxchar;
8695}
8696
8697PyObject *
8698_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8699{
8700 if (!PyUnicode_Check(unicode)) {
8701 PyErr_BadInternalCall();
8702 return NULL;
8703 }
8704 if (PyUnicode_READY(unicode) == -1)
8705 return NULL;
8706 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8707 /* If the string is already ASCII, just return the same string */
8708 Py_INCREF(unicode);
8709 return unicode;
8710 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008711 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008712}
8713
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008714PyObject *
8715PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8716 Py_ssize_t length)
8717{
8718 PyObject *result;
8719 Py_UNICODE *p; /* write pointer into result */
8720 Py_ssize_t i;
8721 /* Copy to a new string */
8722 result = (PyObject *)_PyUnicode_New(length);
8723 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8724 if (result == NULL)
8725 return result;
8726 p = PyUnicode_AS_UNICODE(result);
8727 /* Iterate over code points */
8728 for (i = 0; i < length; i++) {
8729 Py_UNICODE ch =s[i];
8730 if (ch > 127) {
8731 int decimal = Py_UNICODE_TODECIMAL(ch);
8732 if (decimal >= 0)
8733 p[i] = '0' + decimal;
8734 }
8735 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008736#ifndef DONT_MAKE_RESULT_READY
8737 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008738 Py_DECREF(result);
8739 return NULL;
8740 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008741#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008742 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008743 return result;
8744}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008745/* --- Decimal Encoder ---------------------------------------------------- */
8746
Alexander Belopolsky40018472011-02-26 01:02:56 +00008747int
8748PyUnicode_EncodeDecimal(Py_UNICODE *s,
8749 Py_ssize_t length,
8750 char *output,
8751 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008752{
8753 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008754 PyObject *errorHandler = NULL;
8755 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008756 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008757 const char *encoding = "decimal";
8758 const char *reason = "invalid decimal Unicode string";
8759 /* the following variable is used for caching string comparisons
8760 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8761 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008762
8763 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008764 PyErr_BadArgument();
8765 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008766 }
8767
8768 p = s;
8769 end = s + length;
8770 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008771 register Py_UNICODE ch = *p;
8772 int decimal;
8773 PyObject *repunicode;
8774 Py_ssize_t repsize;
8775 Py_ssize_t newpos;
8776 Py_UNICODE *uni2;
8777 Py_UNICODE *collstart;
8778 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008779
Benjamin Peterson29060642009-01-31 22:14:21 +00008780 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008781 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008782 ++p;
8783 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008784 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008785 decimal = Py_UNICODE_TODECIMAL(ch);
8786 if (decimal >= 0) {
8787 *output++ = '0' + decimal;
8788 ++p;
8789 continue;
8790 }
8791 if (0 < ch && ch < 256) {
8792 *output++ = (char)ch;
8793 ++p;
8794 continue;
8795 }
8796 /* All other characters are considered unencodable */
8797 collstart = p;
8798 collend = p+1;
8799 while (collend < end) {
8800 if ((0 < *collend && *collend < 256) ||
8801 !Py_UNICODE_ISSPACE(*collend) ||
8802 Py_UNICODE_TODECIMAL(*collend))
8803 break;
8804 }
8805 /* cache callback name lookup
8806 * (if not done yet, i.e. it's the first error) */
8807 if (known_errorHandler==-1) {
8808 if ((errors==NULL) || (!strcmp(errors, "strict")))
8809 known_errorHandler = 1;
8810 else if (!strcmp(errors, "replace"))
8811 known_errorHandler = 2;
8812 else if (!strcmp(errors, "ignore"))
8813 known_errorHandler = 3;
8814 else if (!strcmp(errors, "xmlcharrefreplace"))
8815 known_errorHandler = 4;
8816 else
8817 known_errorHandler = 0;
8818 }
8819 switch (known_errorHandler) {
8820 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008821 unicode = PyUnicode_FromUnicode(s, length);
8822 if (unicode == NULL)
8823 goto onError;
8824 raise_encode_exception(&exc, encoding, unicode, collstart-s, collend-s, reason);
8825 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008826 goto onError;
8827 case 2: /* replace */
8828 for (p = collstart; p < collend; ++p)
8829 *output++ = '?';
8830 /* fall through */
8831 case 3: /* ignore */
8832 p = collend;
8833 break;
8834 case 4: /* xmlcharrefreplace */
8835 /* generate replacement (temporarily (mis)uses p) */
8836 for (p = collstart; p < collend; ++p)
8837 output += sprintf(output, "&#%d;", (int)*p);
8838 p = collend;
8839 break;
8840 default:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008841 unicode = PyUnicode_FromUnicode(s, length);
8842 if (unicode == NULL)
8843 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008844 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008845 encoding, reason, unicode, &exc,
Benjamin Peterson29060642009-01-31 22:14:21 +00008846 collstart-s, collend-s, &newpos);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008847 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008848 if (repunicode == NULL)
8849 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008850 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008851 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008852 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8853 Py_DECREF(repunicode);
8854 goto onError;
8855 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008856 /* generate replacement */
8857 repsize = PyUnicode_GET_SIZE(repunicode);
8858 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8859 Py_UNICODE ch = *uni2;
8860 if (Py_UNICODE_ISSPACE(ch))
8861 *output++ = ' ';
8862 else {
8863 decimal = Py_UNICODE_TODECIMAL(ch);
8864 if (decimal >= 0)
8865 *output++ = '0' + decimal;
8866 else if (0 < ch && ch < 256)
8867 *output++ = (char)ch;
8868 else {
8869 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008870 unicode = PyUnicode_FromUnicode(s, length);
8871 if (unicode == NULL)
8872 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008873 raise_encode_exception(&exc, encoding,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008874 unicode, collstart-s, collend-s, reason);
8875 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008876 goto onError;
8877 }
8878 }
8879 }
8880 p = s + newpos;
8881 Py_DECREF(repunicode);
8882 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008883 }
8884 /* 0-terminate the output string */
8885 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008886 Py_XDECREF(exc);
8887 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008888 return 0;
8889
Benjamin Peterson29060642009-01-31 22:14:21 +00008890 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008891 Py_XDECREF(exc);
8892 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008893 return -1;
8894}
8895
Guido van Rossumd57fd912000-03-10 22:53:23 +00008896/* --- Helpers ------------------------------------------------------------ */
8897
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008898static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008899any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008900 Py_ssize_t start,
8901 Py_ssize_t end)
8902{
8903 int kind1, kind2, kind;
8904 void *buf1, *buf2;
8905 Py_ssize_t len1, len2, result;
8906
8907 kind1 = PyUnicode_KIND(s1);
8908 kind2 = PyUnicode_KIND(s2);
8909 kind = kind1 > kind2 ? kind1 : kind2;
8910 buf1 = PyUnicode_DATA(s1);
8911 buf2 = PyUnicode_DATA(s2);
8912 if (kind1 != kind)
8913 buf1 = _PyUnicode_AsKind(s1, kind);
8914 if (!buf1)
8915 return -2;
8916 if (kind2 != kind)
8917 buf2 = _PyUnicode_AsKind(s2, kind);
8918 if (!buf2) {
8919 if (kind1 != kind) PyMem_Free(buf1);
8920 return -2;
8921 }
8922 len1 = PyUnicode_GET_LENGTH(s1);
8923 len2 = PyUnicode_GET_LENGTH(s2);
8924
Victor Stinner794d5672011-10-10 03:21:36 +02008925 if (direction > 0) {
8926 switch(kind) {
8927 case PyUnicode_1BYTE_KIND:
8928 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8929 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8930 else
8931 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8932 break;
8933 case PyUnicode_2BYTE_KIND:
8934 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8935 break;
8936 case PyUnicode_4BYTE_KIND:
8937 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8938 break;
8939 default:
8940 assert(0); result = -2;
8941 }
8942 }
8943 else {
8944 switch(kind) {
8945 case PyUnicode_1BYTE_KIND:
8946 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8947 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8948 else
8949 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8950 break;
8951 case PyUnicode_2BYTE_KIND:
8952 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8953 break;
8954 case PyUnicode_4BYTE_KIND:
8955 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8956 break;
8957 default:
8958 assert(0); result = -2;
8959 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008960 }
8961
8962 if (kind1 != kind)
8963 PyMem_Free(buf1);
8964 if (kind2 != kind)
8965 PyMem_Free(buf2);
8966
8967 return result;
8968}
8969
8970Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02008971_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008972 Py_ssize_t n_buffer,
8973 void *digits, Py_ssize_t n_digits,
8974 Py_ssize_t min_width,
8975 const char *grouping,
8976 const char *thousands_sep)
8977{
8978 switch(kind) {
8979 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008980 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
8981 return _PyUnicode_ascii_InsertThousandsGrouping(
8982 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8983 min_width, grouping, thousands_sep);
8984 else
8985 return _PyUnicode_ucs1_InsertThousandsGrouping(
8986 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8987 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008988 case PyUnicode_2BYTE_KIND:
8989 return _PyUnicode_ucs2_InsertThousandsGrouping(
8990 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
8991 min_width, grouping, thousands_sep);
8992 case PyUnicode_4BYTE_KIND:
8993 return _PyUnicode_ucs4_InsertThousandsGrouping(
8994 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
8995 min_width, grouping, thousands_sep);
8996 }
8997 assert(0);
8998 return -1;
8999}
9000
9001
Thomas Wouters477c8d52006-05-27 19:21:47 +00009002/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009003#define ADJUST_INDICES(start, end, len) \
9004 if (end > len) \
9005 end = len; \
9006 else if (end < 0) { \
9007 end += len; \
9008 if (end < 0) \
9009 end = 0; \
9010 } \
9011 if (start < 0) { \
9012 start += len; \
9013 if (start < 0) \
9014 start = 0; \
9015 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009016
Alexander Belopolsky40018472011-02-26 01:02:56 +00009017Py_ssize_t
9018PyUnicode_Count(PyObject *str,
9019 PyObject *substr,
9020 Py_ssize_t start,
9021 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009022{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009023 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009024 PyObject* str_obj;
9025 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009026 int kind1, kind2, kind;
9027 void *buf1 = NULL, *buf2 = NULL;
9028 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009029
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009030 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009031 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009032 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009033 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009034 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009035 Py_DECREF(str_obj);
9036 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009037 }
Tim Petersced69f82003-09-16 20:30:58 +00009038
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009039 kind1 = PyUnicode_KIND(str_obj);
9040 kind2 = PyUnicode_KIND(sub_obj);
9041 kind = kind1 > kind2 ? kind1 : kind2;
9042 buf1 = PyUnicode_DATA(str_obj);
9043 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009044 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009045 if (!buf1)
9046 goto onError;
9047 buf2 = PyUnicode_DATA(sub_obj);
9048 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009049 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009050 if (!buf2)
9051 goto onError;
9052 len1 = PyUnicode_GET_LENGTH(str_obj);
9053 len2 = PyUnicode_GET_LENGTH(sub_obj);
9054
9055 ADJUST_INDICES(start, end, len1);
9056 switch(kind) {
9057 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009058 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9059 result = asciilib_count(
9060 ((Py_UCS1*)buf1) + start, end - start,
9061 buf2, len2, PY_SSIZE_T_MAX
9062 );
9063 else
9064 result = ucs1lib_count(
9065 ((Py_UCS1*)buf1) + start, end - start,
9066 buf2, len2, PY_SSIZE_T_MAX
9067 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009068 break;
9069 case PyUnicode_2BYTE_KIND:
9070 result = ucs2lib_count(
9071 ((Py_UCS2*)buf1) + start, end - start,
9072 buf2, len2, PY_SSIZE_T_MAX
9073 );
9074 break;
9075 case PyUnicode_4BYTE_KIND:
9076 result = ucs4lib_count(
9077 ((Py_UCS4*)buf1) + start, end - start,
9078 buf2, len2, PY_SSIZE_T_MAX
9079 );
9080 break;
9081 default:
9082 assert(0); result = 0;
9083 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009084
9085 Py_DECREF(sub_obj);
9086 Py_DECREF(str_obj);
9087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009088 if (kind1 != kind)
9089 PyMem_Free(buf1);
9090 if (kind2 != kind)
9091 PyMem_Free(buf2);
9092
Guido van Rossumd57fd912000-03-10 22:53:23 +00009093 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009094 onError:
9095 Py_DECREF(sub_obj);
9096 Py_DECREF(str_obj);
9097 if (kind1 != kind && buf1)
9098 PyMem_Free(buf1);
9099 if (kind2 != kind && buf2)
9100 PyMem_Free(buf2);
9101 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009102}
9103
Alexander Belopolsky40018472011-02-26 01:02:56 +00009104Py_ssize_t
9105PyUnicode_Find(PyObject *str,
9106 PyObject *sub,
9107 Py_ssize_t start,
9108 Py_ssize_t end,
9109 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009110{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009111 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009112
Guido van Rossumd57fd912000-03-10 22:53:23 +00009113 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009114 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009115 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009116 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009117 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009118 Py_DECREF(str);
9119 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009120 }
Tim Petersced69f82003-09-16 20:30:58 +00009121
Victor Stinner794d5672011-10-10 03:21:36 +02009122 result = any_find_slice(direction,
9123 str, sub, start, end
9124 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009125
Guido van Rossumd57fd912000-03-10 22:53:23 +00009126 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009127 Py_DECREF(sub);
9128
Guido van Rossumd57fd912000-03-10 22:53:23 +00009129 return result;
9130}
9131
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009132Py_ssize_t
9133PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9134 Py_ssize_t start, Py_ssize_t end,
9135 int direction)
9136{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009137 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009138 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009139 if (PyUnicode_READY(str) == -1)
9140 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009141 if (start < 0 || end < 0) {
9142 PyErr_SetString(PyExc_IndexError, "string index out of range");
9143 return -2;
9144 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009145 if (end > PyUnicode_GET_LENGTH(str))
9146 end = PyUnicode_GET_LENGTH(str);
9147 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009148 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9149 kind, end-start, ch, direction);
9150 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009151 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009152 else
9153 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009154}
9155
Alexander Belopolsky40018472011-02-26 01:02:56 +00009156static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009157tailmatch(PyObject *self,
9158 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009159 Py_ssize_t start,
9160 Py_ssize_t end,
9161 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009162{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009163 int kind_self;
9164 int kind_sub;
9165 void *data_self;
9166 void *data_sub;
9167 Py_ssize_t offset;
9168 Py_ssize_t i;
9169 Py_ssize_t end_sub;
9170
9171 if (PyUnicode_READY(self) == -1 ||
9172 PyUnicode_READY(substring) == -1)
9173 return 0;
9174
9175 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009176 return 1;
9177
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009178 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9179 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009180 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009181 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009182
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009183 kind_self = PyUnicode_KIND(self);
9184 data_self = PyUnicode_DATA(self);
9185 kind_sub = PyUnicode_KIND(substring);
9186 data_sub = PyUnicode_DATA(substring);
9187 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9188
9189 if (direction > 0)
9190 offset = end;
9191 else
9192 offset = start;
9193
9194 if (PyUnicode_READ(kind_self, data_self, offset) ==
9195 PyUnicode_READ(kind_sub, data_sub, 0) &&
9196 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9197 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9198 /* If both are of the same kind, memcmp is sufficient */
9199 if (kind_self == kind_sub) {
9200 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009201 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009202 data_sub,
9203 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009204 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009205 }
9206 /* otherwise we have to compare each character by first accesing it */
9207 else {
9208 /* We do not need to compare 0 and len(substring)-1 because
9209 the if statement above ensured already that they are equal
9210 when we end up here. */
9211 // TODO: honor direction and do a forward or backwards search
9212 for (i = 1; i < end_sub; ++i) {
9213 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9214 PyUnicode_READ(kind_sub, data_sub, i))
9215 return 0;
9216 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009217 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009218 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009219 }
9220
9221 return 0;
9222}
9223
Alexander Belopolsky40018472011-02-26 01:02:56 +00009224Py_ssize_t
9225PyUnicode_Tailmatch(PyObject *str,
9226 PyObject *substr,
9227 Py_ssize_t start,
9228 Py_ssize_t end,
9229 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009230{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009231 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009232
Guido van Rossumd57fd912000-03-10 22:53:23 +00009233 str = PyUnicode_FromObject(str);
9234 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009235 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009236 substr = PyUnicode_FromObject(substr);
9237 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009238 Py_DECREF(str);
9239 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009240 }
Tim Petersced69f82003-09-16 20:30:58 +00009241
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009242 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009243 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009244 Py_DECREF(str);
9245 Py_DECREF(substr);
9246 return result;
9247}
9248
Guido van Rossumd57fd912000-03-10 22:53:23 +00009249/* Apply fixfct filter to the Unicode object self and return a
9250 reference to the modified object */
9251
Alexander Belopolsky40018472011-02-26 01:02:56 +00009252static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009253fixup(PyObject *self,
9254 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009255{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009256 PyObject *u;
9257 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009258
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009259 if (PyUnicode_READY(self) == -1)
9260 return NULL;
9261 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
9262 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
9263 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009264 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009265 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009266
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009267 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009268 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009269
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009270 /* fix functions return the new maximum character in a string,
9271 if the kind of the resulting unicode object does not change,
9272 everything is fine. Otherwise we need to change the string kind
9273 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009274 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009275 if (maxchar_new == 0)
9276 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9277 else if (maxchar_new <= 127)
9278 maxchar_new = 127;
9279 else if (maxchar_new <= 255)
9280 maxchar_new = 255;
9281 else if (maxchar_new <= 65535)
9282 maxchar_new = 65535;
9283 else
9284 maxchar_new = 1114111; /* 0x10ffff */
9285
9286 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009287 /* fixfct should return TRUE if it modified the buffer. If
9288 FALSE, return a reference to the original buffer instead
9289 (to save space, not time) */
9290 Py_INCREF(self);
9291 Py_DECREF(u);
Victor Stinner7931d9a2011-11-04 00:22:48 +01009292 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009293 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009294 else if (maxchar_new == maxchar_old) {
9295 return u;
9296 }
9297 else {
9298 /* In case the maximum character changed, we need to
9299 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009300 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009301 if (v == NULL) {
9302 Py_DECREF(u);
9303 return NULL;
9304 }
9305 if (maxchar_new > maxchar_old) {
9306 /* If the maxchar increased so that the kind changed, not all
9307 characters are representable anymore and we need to fix the
9308 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009309 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009310 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009311 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9312 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009313 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009314 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009315 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009316
9317 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009318 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009319 return v;
9320 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009321}
9322
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009323static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009324fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009325{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009326 /* No need to call PyUnicode_READY(self) because this function is only
9327 called as a callback from fixup() which does it already. */
9328 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9329 const int kind = PyUnicode_KIND(self);
9330 void *data = PyUnicode_DATA(self);
9331 int touched = 0;
9332 Py_UCS4 maxchar = 0;
9333 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009334
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009335 for (i = 0; i < len; ++i) {
9336 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9337 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9338 if (up != ch) {
9339 if (up > maxchar)
9340 maxchar = up;
9341 PyUnicode_WRITE(kind, data, i, up);
9342 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009343 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009344 else if (ch > maxchar)
9345 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009346 }
9347
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009348 if (touched)
9349 return maxchar;
9350 else
9351 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009352}
9353
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009354static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009355fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009356{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009357 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9358 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9359 const int kind = PyUnicode_KIND(self);
9360 void *data = PyUnicode_DATA(self);
9361 int touched = 0;
9362 Py_UCS4 maxchar = 0;
9363 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009364
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009365 for(i = 0; i < len; ++i) {
9366 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9367 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9368 if (lo != ch) {
9369 if (lo > maxchar)
9370 maxchar = lo;
9371 PyUnicode_WRITE(kind, data, i, lo);
9372 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009373 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009374 else if (ch > maxchar)
9375 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009376 }
9377
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009378 if (touched)
9379 return maxchar;
9380 else
9381 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009382}
9383
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009384static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009385fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009386{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009387 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9388 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9389 const int kind = PyUnicode_KIND(self);
9390 void *data = PyUnicode_DATA(self);
9391 int touched = 0;
9392 Py_UCS4 maxchar = 0;
9393 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009394
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009395 for(i = 0; i < len; ++i) {
9396 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9397 Py_UCS4 nu = 0;
9398
9399 if (Py_UNICODE_ISUPPER(ch))
9400 nu = Py_UNICODE_TOLOWER(ch);
9401 else if (Py_UNICODE_ISLOWER(ch))
9402 nu = Py_UNICODE_TOUPPER(ch);
9403
9404 if (nu != 0) {
9405 if (nu > maxchar)
9406 maxchar = nu;
9407 PyUnicode_WRITE(kind, data, i, nu);
9408 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009409 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009410 else if (ch > maxchar)
9411 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009412 }
9413
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009414 if (touched)
9415 return maxchar;
9416 else
9417 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009418}
9419
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009420static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009421fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009422{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009423 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9424 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9425 const int kind = PyUnicode_KIND(self);
9426 void *data = PyUnicode_DATA(self);
9427 int touched = 0;
9428 Py_UCS4 maxchar = 0;
9429 Py_ssize_t i = 0;
9430 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009431
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009432 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009433 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009434
9435 ch = PyUnicode_READ(kind, data, i);
9436 if (!Py_UNICODE_ISUPPER(ch)) {
9437 maxchar = Py_UNICODE_TOUPPER(ch);
9438 PyUnicode_WRITE(kind, data, i, maxchar);
9439 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009440 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009441 ++i;
9442 for(; i < len; ++i) {
9443 ch = PyUnicode_READ(kind, data, i);
9444 if (!Py_UNICODE_ISLOWER(ch)) {
9445 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9446 if (lo > maxchar)
9447 maxchar = lo;
9448 PyUnicode_WRITE(kind, data, i, lo);
9449 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009450 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009451 else if (ch > maxchar)
9452 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009453 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009454
9455 if (touched)
9456 return maxchar;
9457 else
9458 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009459}
9460
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009461static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009462fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009463{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009464 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9465 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9466 const int kind = PyUnicode_KIND(self);
9467 void *data = PyUnicode_DATA(self);
9468 Py_UCS4 maxchar = 0;
9469 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009470 int previous_is_cased;
9471
9472 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009473 if (len == 1) {
9474 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9475 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9476 if (ti != ch) {
9477 PyUnicode_WRITE(kind, data, i, ti);
9478 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009479 }
9480 else
9481 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009482 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009483 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009484 for(; i < len; ++i) {
9485 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9486 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009487
Benjamin Peterson29060642009-01-31 22:14:21 +00009488 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009489 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009490 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009491 nu = Py_UNICODE_TOTITLE(ch);
9492
9493 if (nu > maxchar)
9494 maxchar = nu;
9495 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009496
Benjamin Peterson29060642009-01-31 22:14:21 +00009497 if (Py_UNICODE_ISLOWER(ch) ||
9498 Py_UNICODE_ISUPPER(ch) ||
9499 Py_UNICODE_ISTITLE(ch))
9500 previous_is_cased = 1;
9501 else
9502 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009503 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009504 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009505}
9506
Tim Peters8ce9f162004-08-27 01:49:32 +00009507PyObject *
9508PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009509{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009510 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009511 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009512 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009513 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009514 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9515 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009516 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009517 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009518 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009519 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009520 int use_memcpy;
9521 unsigned char *res_data = NULL, *sep_data = NULL;
9522 PyObject *last_obj;
9523 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009524
Tim Peters05eba1f2004-08-27 21:32:02 +00009525 fseq = PySequence_Fast(seq, "");
9526 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009527 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009528 }
9529
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009530 /* NOTE: the following code can't call back into Python code,
9531 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009532 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009533
Tim Peters05eba1f2004-08-27 21:32:02 +00009534 seqlen = PySequence_Fast_GET_SIZE(fseq);
9535 /* If empty sequence, return u"". */
9536 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009537 Py_DECREF(fseq);
9538 Py_INCREF(unicode_empty);
9539 res = unicode_empty;
9540 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009541 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009542
Tim Peters05eba1f2004-08-27 21:32:02 +00009543 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009544 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009545 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009546 if (seqlen == 1) {
9547 if (PyUnicode_CheckExact(items[0])) {
9548 res = items[0];
9549 Py_INCREF(res);
9550 Py_DECREF(fseq);
9551 return res;
9552 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009553 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009554 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009555 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009556 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009557 /* Set up sep and seplen */
9558 if (separator == NULL) {
9559 /* fall back to a blank space separator */
9560 sep = PyUnicode_FromOrdinal(' ');
9561 if (!sep)
9562 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009563 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009564 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009565 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009566 else {
9567 if (!PyUnicode_Check(separator)) {
9568 PyErr_Format(PyExc_TypeError,
9569 "separator: expected str instance,"
9570 " %.80s found",
9571 Py_TYPE(separator)->tp_name);
9572 goto onError;
9573 }
9574 if (PyUnicode_READY(separator))
9575 goto onError;
9576 sep = separator;
9577 seplen = PyUnicode_GET_LENGTH(separator);
9578 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9579 /* inc refcount to keep this code path symmetric with the
9580 above case of a blank separator */
9581 Py_INCREF(sep);
9582 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009583 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009584 }
9585
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009586 /* There are at least two things to join, or else we have a subclass
9587 * of str in the sequence.
9588 * Do a pre-pass to figure out the total amount of space we'll
9589 * need (sz), and see whether all argument are strings.
9590 */
9591 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009592#ifdef Py_DEBUG
9593 use_memcpy = 0;
9594#else
9595 use_memcpy = 1;
9596#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009597 for (i = 0; i < seqlen; i++) {
9598 const Py_ssize_t old_sz = sz;
9599 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009600 if (!PyUnicode_Check(item)) {
9601 PyErr_Format(PyExc_TypeError,
9602 "sequence item %zd: expected str instance,"
9603 " %.80s found",
9604 i, Py_TYPE(item)->tp_name);
9605 goto onError;
9606 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009607 if (PyUnicode_READY(item) == -1)
9608 goto onError;
9609 sz += PyUnicode_GET_LENGTH(item);
9610 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009611 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009612 if (i != 0)
9613 sz += seplen;
9614 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9615 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009616 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009617 goto onError;
9618 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009619 if (use_memcpy && last_obj != NULL) {
9620 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9621 use_memcpy = 0;
9622 }
9623 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009624 }
Tim Petersced69f82003-09-16 20:30:58 +00009625
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009626 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009627 if (res == NULL)
9628 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009629
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009630 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009631#ifdef Py_DEBUG
9632 use_memcpy = 0;
9633#else
9634 if (use_memcpy) {
9635 res_data = PyUnicode_1BYTE_DATA(res);
9636 kind = PyUnicode_KIND(res);
9637 if (seplen != 0)
9638 sep_data = PyUnicode_1BYTE_DATA(sep);
9639 }
9640#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009641 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009642 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009643 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009644 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009645 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009646 if (use_memcpy) {
9647 Py_MEMCPY(res_data,
9648 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009649 kind * seplen);
9650 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009651 }
9652 else {
9653 copy_characters(res, res_offset, sep, 0, seplen);
9654 res_offset += seplen;
9655 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009656 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009657 itemlen = PyUnicode_GET_LENGTH(item);
9658 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009659 if (use_memcpy) {
9660 Py_MEMCPY(res_data,
9661 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009662 kind * itemlen);
9663 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009664 }
9665 else {
9666 copy_characters(res, res_offset, item, 0, itemlen);
9667 res_offset += itemlen;
9668 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009669 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009670 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009671 if (use_memcpy)
9672 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009673 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009674 else
9675 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009676
Tim Peters05eba1f2004-08-27 21:32:02 +00009677 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009678 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009679 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009680 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009681
Benjamin Peterson29060642009-01-31 22:14:21 +00009682 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009683 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009684 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009685 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009686 return NULL;
9687}
9688
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009689#define FILL(kind, data, value, start, length) \
9690 do { \
9691 Py_ssize_t i_ = 0; \
9692 assert(kind != PyUnicode_WCHAR_KIND); \
9693 switch ((kind)) { \
9694 case PyUnicode_1BYTE_KIND: { \
9695 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9696 memset(to_, (unsigned char)value, length); \
9697 break; \
9698 } \
9699 case PyUnicode_2BYTE_KIND: { \
9700 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9701 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9702 break; \
9703 } \
9704 default: { \
9705 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9706 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9707 break; \
9708 } \
9709 } \
9710 } while (0)
9711
Victor Stinner9310abb2011-10-05 00:59:23 +02009712static PyObject *
9713pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009714 Py_ssize_t left,
9715 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009716 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009717{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009718 PyObject *u;
9719 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009720 int kind;
9721 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009722
9723 if (left < 0)
9724 left = 0;
9725 if (right < 0)
9726 right = 0;
9727
Tim Peters7a29bd52001-09-12 03:03:31 +00009728 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009729 Py_INCREF(self);
9730 return self;
9731 }
9732
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009733 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9734 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009735 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9736 return NULL;
9737 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009738 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9739 if (fill > maxchar)
9740 maxchar = fill;
9741 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009742 if (!u)
9743 return NULL;
9744
9745 kind = PyUnicode_KIND(u);
9746 data = PyUnicode_DATA(u);
9747 if (left)
9748 FILL(kind, data, fill, 0, left);
9749 if (right)
9750 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009751 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009752 assert(_PyUnicode_CheckConsistency(u, 1));
9753 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009754}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009755#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009756
Alexander Belopolsky40018472011-02-26 01:02:56 +00009757PyObject *
9758PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009759{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009760 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009761
9762 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009763 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009764 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009765
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009766 switch(PyUnicode_KIND(string)) {
9767 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009768 if (PyUnicode_IS_ASCII(string))
9769 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009770 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009771 PyUnicode_GET_LENGTH(string), keepends);
9772 else
9773 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009774 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009775 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009776 break;
9777 case PyUnicode_2BYTE_KIND:
9778 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009779 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009780 PyUnicode_GET_LENGTH(string), keepends);
9781 break;
9782 case PyUnicode_4BYTE_KIND:
9783 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009784 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009785 PyUnicode_GET_LENGTH(string), keepends);
9786 break;
9787 default:
9788 assert(0);
9789 list = 0;
9790 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009791 Py_DECREF(string);
9792 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009793}
9794
Alexander Belopolsky40018472011-02-26 01:02:56 +00009795static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009796split(PyObject *self,
9797 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009798 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009799{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009800 int kind1, kind2, kind;
9801 void *buf1, *buf2;
9802 Py_ssize_t len1, len2;
9803 PyObject* out;
9804
Guido van Rossumd57fd912000-03-10 22:53:23 +00009805 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009806 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009807
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009808 if (PyUnicode_READY(self) == -1)
9809 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009811 if (substring == NULL)
9812 switch(PyUnicode_KIND(self)) {
9813 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009814 if (PyUnicode_IS_ASCII(self))
9815 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009816 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009817 PyUnicode_GET_LENGTH(self), maxcount
9818 );
9819 else
9820 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009821 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009822 PyUnicode_GET_LENGTH(self), maxcount
9823 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009824 case PyUnicode_2BYTE_KIND:
9825 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009826 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009827 PyUnicode_GET_LENGTH(self), maxcount
9828 );
9829 case PyUnicode_4BYTE_KIND:
9830 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009831 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009832 PyUnicode_GET_LENGTH(self), maxcount
9833 );
9834 default:
9835 assert(0);
9836 return NULL;
9837 }
9838
9839 if (PyUnicode_READY(substring) == -1)
9840 return NULL;
9841
9842 kind1 = PyUnicode_KIND(self);
9843 kind2 = PyUnicode_KIND(substring);
9844 kind = kind1 > kind2 ? kind1 : kind2;
9845 buf1 = PyUnicode_DATA(self);
9846 buf2 = PyUnicode_DATA(substring);
9847 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009848 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009849 if (!buf1)
9850 return NULL;
9851 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009852 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009853 if (!buf2) {
9854 if (kind1 != kind) PyMem_Free(buf1);
9855 return NULL;
9856 }
9857 len1 = PyUnicode_GET_LENGTH(self);
9858 len2 = PyUnicode_GET_LENGTH(substring);
9859
9860 switch(kind) {
9861 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009862 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9863 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009864 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009865 else
9866 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009867 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009868 break;
9869 case PyUnicode_2BYTE_KIND:
9870 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009871 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009872 break;
9873 case PyUnicode_4BYTE_KIND:
9874 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009875 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009876 break;
9877 default:
9878 out = NULL;
9879 }
9880 if (kind1 != kind)
9881 PyMem_Free(buf1);
9882 if (kind2 != kind)
9883 PyMem_Free(buf2);
9884 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009885}
9886
Alexander Belopolsky40018472011-02-26 01:02:56 +00009887static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009888rsplit(PyObject *self,
9889 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009890 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009891{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009892 int kind1, kind2, kind;
9893 void *buf1, *buf2;
9894 Py_ssize_t len1, len2;
9895 PyObject* out;
9896
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009897 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009898 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009899
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009900 if (PyUnicode_READY(self) == -1)
9901 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009902
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009903 if (substring == NULL)
9904 switch(PyUnicode_KIND(self)) {
9905 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009906 if (PyUnicode_IS_ASCII(self))
9907 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009908 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009909 PyUnicode_GET_LENGTH(self), maxcount
9910 );
9911 else
9912 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009913 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009914 PyUnicode_GET_LENGTH(self), maxcount
9915 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009916 case PyUnicode_2BYTE_KIND:
9917 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009918 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009919 PyUnicode_GET_LENGTH(self), maxcount
9920 );
9921 case PyUnicode_4BYTE_KIND:
9922 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009923 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009924 PyUnicode_GET_LENGTH(self), maxcount
9925 );
9926 default:
9927 assert(0);
9928 return NULL;
9929 }
9930
9931 if (PyUnicode_READY(substring) == -1)
9932 return NULL;
9933
9934 kind1 = PyUnicode_KIND(self);
9935 kind2 = PyUnicode_KIND(substring);
9936 kind = kind1 > kind2 ? kind1 : kind2;
9937 buf1 = PyUnicode_DATA(self);
9938 buf2 = PyUnicode_DATA(substring);
9939 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009940 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009941 if (!buf1)
9942 return NULL;
9943 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009944 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009945 if (!buf2) {
9946 if (kind1 != kind) PyMem_Free(buf1);
9947 return NULL;
9948 }
9949 len1 = PyUnicode_GET_LENGTH(self);
9950 len2 = PyUnicode_GET_LENGTH(substring);
9951
9952 switch(kind) {
9953 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009954 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9955 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009956 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009957 else
9958 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009959 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009960 break;
9961 case PyUnicode_2BYTE_KIND:
9962 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009963 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009964 break;
9965 case PyUnicode_4BYTE_KIND:
9966 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009967 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009968 break;
9969 default:
9970 out = NULL;
9971 }
9972 if (kind1 != kind)
9973 PyMem_Free(buf1);
9974 if (kind2 != kind)
9975 PyMem_Free(buf2);
9976 return out;
9977}
9978
9979static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009980anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9981 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009982{
9983 switch(kind) {
9984 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009985 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9986 return asciilib_find(buf1, len1, buf2, len2, offset);
9987 else
9988 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009989 case PyUnicode_2BYTE_KIND:
9990 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9991 case PyUnicode_4BYTE_KIND:
9992 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9993 }
9994 assert(0);
9995 return -1;
9996}
9997
9998static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009999anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10000 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010001{
10002 switch(kind) {
10003 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010004 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10005 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10006 else
10007 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010008 case PyUnicode_2BYTE_KIND:
10009 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10010 case PyUnicode_4BYTE_KIND:
10011 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10012 }
10013 assert(0);
10014 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010015}
10016
Alexander Belopolsky40018472011-02-26 01:02:56 +000010017static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010018replace(PyObject *self, PyObject *str1,
10019 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010020{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010021 PyObject *u;
10022 char *sbuf = PyUnicode_DATA(self);
10023 char *buf1 = PyUnicode_DATA(str1);
10024 char *buf2 = PyUnicode_DATA(str2);
10025 int srelease = 0, release1 = 0, release2 = 0;
10026 int skind = PyUnicode_KIND(self);
10027 int kind1 = PyUnicode_KIND(str1);
10028 int kind2 = PyUnicode_KIND(str2);
10029 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10030 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10031 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010032 int mayshrink;
10033 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010034
10035 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010036 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010037 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010038 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010039
Victor Stinner59de0ee2011-10-07 10:01:28 +020010040 if (str1 == str2)
10041 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010042 if (skind < kind1)
10043 /* substring too wide to be present */
10044 goto nothing;
10045
Victor Stinner49a0a212011-10-12 23:46:10 +020010046 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10047 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10048 /* Replacing str1 with str2 may cause a maxchar reduction in the
10049 result string. */
10050 mayshrink = (maxchar_str2 < maxchar);
10051 maxchar = Py_MAX(maxchar, maxchar_str2);
10052
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010053 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010054 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010055 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010056 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010057 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010058 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010059 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010060 Py_UCS4 u1, u2;
10061 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010062 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010063 if (findchar(sbuf, PyUnicode_KIND(self),
10064 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010065 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010066 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010067 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010068 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010069 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010070 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010071 rkind = PyUnicode_KIND(u);
10072 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10073 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010074 if (--maxcount < 0)
10075 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010077 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010078 }
10079 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010080 int rkind = skind;
10081 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010082
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010083 if (kind1 < rkind) {
10084 /* widen substring */
10085 buf1 = _PyUnicode_AsKind(str1, rkind);
10086 if (!buf1) goto error;
10087 release1 = 1;
10088 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010089 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010090 if (i < 0)
10091 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010092 if (rkind > kind2) {
10093 /* widen replacement */
10094 buf2 = _PyUnicode_AsKind(str2, rkind);
10095 if (!buf2) goto error;
10096 release2 = 1;
10097 }
10098 else if (rkind < kind2) {
10099 /* widen self and buf1 */
10100 rkind = kind2;
10101 if (release1) PyMem_Free(buf1);
10102 sbuf = _PyUnicode_AsKind(self, rkind);
10103 if (!sbuf) goto error;
10104 srelease = 1;
10105 buf1 = _PyUnicode_AsKind(str1, rkind);
10106 if (!buf1) goto error;
10107 release1 = 1;
10108 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010109 u = PyUnicode_New(slen, maxchar);
10110 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010111 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010112 assert(PyUnicode_KIND(u) == rkind);
10113 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010114
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010115 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010116 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010117 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010118 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010119 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010120 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010121
10122 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010123 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010124 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010125 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010126 if (i == -1)
10127 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010128 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010129 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010130 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010131 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010132 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010133 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010134 }
10135 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010136 Py_ssize_t n, i, j, ires;
10137 Py_ssize_t product, new_size;
10138 int rkind = skind;
10139 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010140
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010141 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010142 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010143 buf1 = _PyUnicode_AsKind(str1, rkind);
10144 if (!buf1) goto error;
10145 release1 = 1;
10146 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010147 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010148 if (n == 0)
10149 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010150 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010151 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152 buf2 = _PyUnicode_AsKind(str2, rkind);
10153 if (!buf2) goto error;
10154 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010155 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010156 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010157 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 rkind = kind2;
10159 sbuf = _PyUnicode_AsKind(self, rkind);
10160 if (!sbuf) goto error;
10161 srelease = 1;
10162 if (release1) PyMem_Free(buf1);
10163 buf1 = _PyUnicode_AsKind(str1, rkind);
10164 if (!buf1) goto error;
10165 release1 = 1;
10166 }
10167 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10168 PyUnicode_GET_LENGTH(str1))); */
10169 product = n * (len2-len1);
10170 if ((product / (len2-len1)) != n) {
10171 PyErr_SetString(PyExc_OverflowError,
10172 "replace string is too long");
10173 goto error;
10174 }
10175 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010176 if (new_size == 0) {
10177 Py_INCREF(unicode_empty);
10178 u = unicode_empty;
10179 goto done;
10180 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010181 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10182 PyErr_SetString(PyExc_OverflowError,
10183 "replace string is too long");
10184 goto error;
10185 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010186 u = PyUnicode_New(new_size, maxchar);
10187 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010189 assert(PyUnicode_KIND(u) == rkind);
10190 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191 ires = i = 0;
10192 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010193 while (n-- > 0) {
10194 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010195 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010196 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010197 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010198 if (j == -1)
10199 break;
10200 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010201 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010202 memcpy(res + rkind * ires,
10203 sbuf + rkind * i,
10204 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010205 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010206 }
10207 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010209 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010210 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010211 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010212 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010213 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010214 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010215 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010216 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010217 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010218 memcpy(res + rkind * ires,
10219 sbuf + rkind * i,
10220 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010221 }
10222 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010223 /* interleave */
10224 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010225 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010226 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010227 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010228 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010229 if (--n <= 0)
10230 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010231 memcpy(res + rkind * ires,
10232 sbuf + rkind * i,
10233 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010234 ires++;
10235 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010236 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010237 memcpy(res + rkind * ires,
10238 sbuf + rkind * i,
10239 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010240 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010241 }
10242
10243 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010244 unicode_adjust_maxchar(&u);
10245 if (u == NULL)
10246 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010247 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010248
10249 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010250 if (srelease)
10251 PyMem_FREE(sbuf);
10252 if (release1)
10253 PyMem_FREE(buf1);
10254 if (release2)
10255 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010256 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010257 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010258
Benjamin Peterson29060642009-01-31 22:14:21 +000010259 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010260 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010261 if (srelease)
10262 PyMem_FREE(sbuf);
10263 if (release1)
10264 PyMem_FREE(buf1);
10265 if (release2)
10266 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010267 if (PyUnicode_CheckExact(self)) {
10268 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010269 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010270 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010271 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010272 error:
10273 if (srelease && sbuf)
10274 PyMem_FREE(sbuf);
10275 if (release1 && buf1)
10276 PyMem_FREE(buf1);
10277 if (release2 && buf2)
10278 PyMem_FREE(buf2);
10279 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010280}
10281
10282/* --- Unicode Object Methods --------------------------------------------- */
10283
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010284PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010285 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010286\n\
10287Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010288characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010289
10290static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010291unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010292{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010293 return fixup(self, fixtitle);
10294}
10295
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010296PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010297 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010298\n\
10299Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010300have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010301
10302static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010303unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010304{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010305 return fixup(self, fixcapitalize);
10306}
10307
10308#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010309PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010310 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010311\n\
10312Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010313normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010314
10315static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010316unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010317{
10318 PyObject *list;
10319 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010320 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010321
Guido van Rossumd57fd912000-03-10 22:53:23 +000010322 /* Split into words */
10323 list = split(self, NULL, -1);
10324 if (!list)
10325 return NULL;
10326
10327 /* Capitalize each word */
10328 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010329 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010330 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010331 if (item == NULL)
10332 goto onError;
10333 Py_DECREF(PyList_GET_ITEM(list, i));
10334 PyList_SET_ITEM(list, i, item);
10335 }
10336
10337 /* Join the words to form a new string */
10338 item = PyUnicode_Join(NULL, list);
10339
Benjamin Peterson29060642009-01-31 22:14:21 +000010340 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010341 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010342 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010343}
10344#endif
10345
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010346/* Argument converter. Coerces to a single unicode character */
10347
10348static int
10349convert_uc(PyObject *obj, void *addr)
10350{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010351 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010352 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010353
Benjamin Peterson14339b62009-01-31 16:36:08 +000010354 uniobj = PyUnicode_FromObject(obj);
10355 if (uniobj == NULL) {
10356 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010357 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010358 return 0;
10359 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010361 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010362 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010363 Py_DECREF(uniobj);
10364 return 0;
10365 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010366 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010367 Py_DECREF(uniobj);
10368 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010369}
10370
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010371PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010372 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010373\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010374Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010375done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010376
10377static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010378unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010379{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010380 Py_ssize_t marg, left;
10381 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010382 Py_UCS4 fillchar = ' ';
10383
Victor Stinnere9a29352011-10-01 02:14:59 +020010384 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010385 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010386
Victor Stinnere9a29352011-10-01 02:14:59 +020010387 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010388 return NULL;
10389
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010391 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010392 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010393 }
10394
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010395 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010396 left = marg / 2 + (marg & width & 1);
10397
Victor Stinner9310abb2011-10-05 00:59:23 +020010398 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010399}
10400
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010401/* This function assumes that str1 and str2 are readied by the caller. */
10402
Marc-André Lemburge5034372000-08-08 08:04:29 +000010403static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010404unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010405{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010406 int kind1, kind2;
10407 void *data1, *data2;
10408 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010409
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010410 kind1 = PyUnicode_KIND(str1);
10411 kind2 = PyUnicode_KIND(str2);
10412 data1 = PyUnicode_DATA(str1);
10413 data2 = PyUnicode_DATA(str2);
10414 len1 = PyUnicode_GET_LENGTH(str1);
10415 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010416
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010417 for (i = 0; i < len1 && i < len2; ++i) {
10418 Py_UCS4 c1, c2;
10419 c1 = PyUnicode_READ(kind1, data1, i);
10420 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010421
10422 if (c1 != c2)
10423 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010424 }
10425
10426 return (len1 < len2) ? -1 : (len1 != len2);
10427}
10428
Alexander Belopolsky40018472011-02-26 01:02:56 +000010429int
10430PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010431{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10433 if (PyUnicode_READY(left) == -1 ||
10434 PyUnicode_READY(right) == -1)
10435 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010436 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010437 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010438 PyErr_Format(PyExc_TypeError,
10439 "Can't compare %.100s and %.100s",
10440 left->ob_type->tp_name,
10441 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010442 return -1;
10443}
10444
Martin v. Löwis5b222132007-06-10 09:51:05 +000010445int
10446PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10447{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 Py_ssize_t i;
10449 int kind;
10450 void *data;
10451 Py_UCS4 chr;
10452
Victor Stinner910337b2011-10-03 03:20:16 +020010453 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010454 if (PyUnicode_READY(uni) == -1)
10455 return -1;
10456 kind = PyUnicode_KIND(uni);
10457 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010458 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010459 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10460 if (chr != str[i])
10461 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010462 /* This check keeps Python strings that end in '\0' from comparing equal
10463 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010464 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010465 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010466 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010467 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010468 return 0;
10469}
10470
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010471
Benjamin Peterson29060642009-01-31 22:14:21 +000010472#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010473 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010474
Alexander Belopolsky40018472011-02-26 01:02:56 +000010475PyObject *
10476PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010477{
10478 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010479
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010480 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10481 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010482 if (PyUnicode_READY(left) == -1 ||
10483 PyUnicode_READY(right) == -1)
10484 return NULL;
10485 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10486 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010487 if (op == Py_EQ) {
10488 Py_INCREF(Py_False);
10489 return Py_False;
10490 }
10491 if (op == Py_NE) {
10492 Py_INCREF(Py_True);
10493 return Py_True;
10494 }
10495 }
10496 if (left == right)
10497 result = 0;
10498 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010499 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010500
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010501 /* Convert the return value to a Boolean */
10502 switch (op) {
10503 case Py_EQ:
10504 v = TEST_COND(result == 0);
10505 break;
10506 case Py_NE:
10507 v = TEST_COND(result != 0);
10508 break;
10509 case Py_LE:
10510 v = TEST_COND(result <= 0);
10511 break;
10512 case Py_GE:
10513 v = TEST_COND(result >= 0);
10514 break;
10515 case Py_LT:
10516 v = TEST_COND(result == -1);
10517 break;
10518 case Py_GT:
10519 v = TEST_COND(result == 1);
10520 break;
10521 default:
10522 PyErr_BadArgument();
10523 return NULL;
10524 }
10525 Py_INCREF(v);
10526 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010527 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010528
Brian Curtindfc80e32011-08-10 20:28:54 -050010529 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010530}
10531
Alexander Belopolsky40018472011-02-26 01:02:56 +000010532int
10533PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010534{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010535 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010536 int kind1, kind2, kind;
10537 void *buf1, *buf2;
10538 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010539 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010540
10541 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010542 sub = PyUnicode_FromObject(element);
10543 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010544 PyErr_Format(PyExc_TypeError,
10545 "'in <string>' requires string as left operand, not %s",
10546 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010547 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010548 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010549 if (PyUnicode_READY(sub) == -1)
10550 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010551
Thomas Wouters477c8d52006-05-27 19:21:47 +000010552 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010553 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010554 Py_DECREF(sub);
10555 return -1;
10556 }
10557
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010558 kind1 = PyUnicode_KIND(str);
10559 kind2 = PyUnicode_KIND(sub);
10560 kind = kind1 > kind2 ? kind1 : kind2;
10561 buf1 = PyUnicode_DATA(str);
10562 buf2 = PyUnicode_DATA(sub);
10563 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010564 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010565 if (!buf1) {
10566 Py_DECREF(sub);
10567 return -1;
10568 }
10569 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010570 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010571 if (!buf2) {
10572 Py_DECREF(sub);
10573 if (kind1 != kind) PyMem_Free(buf1);
10574 return -1;
10575 }
10576 len1 = PyUnicode_GET_LENGTH(str);
10577 len2 = PyUnicode_GET_LENGTH(sub);
10578
10579 switch(kind) {
10580 case PyUnicode_1BYTE_KIND:
10581 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10582 break;
10583 case PyUnicode_2BYTE_KIND:
10584 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10585 break;
10586 case PyUnicode_4BYTE_KIND:
10587 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10588 break;
10589 default:
10590 result = -1;
10591 assert(0);
10592 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010593
10594 Py_DECREF(str);
10595 Py_DECREF(sub);
10596
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010597 if (kind1 != kind)
10598 PyMem_Free(buf1);
10599 if (kind2 != kind)
10600 PyMem_Free(buf2);
10601
Guido van Rossum403d68b2000-03-13 15:55:09 +000010602 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010603}
10604
Guido van Rossumd57fd912000-03-10 22:53:23 +000010605/* Concat to string or Unicode object giving a new Unicode object. */
10606
Alexander Belopolsky40018472011-02-26 01:02:56 +000010607PyObject *
10608PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010609{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010610 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010611 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010612
10613 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010614 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010615 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010616 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010617 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010618 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010619 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010620
10621 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010622 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010623 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010625 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010626 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010627 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010628 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010629 }
10630
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010631 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010632 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10633 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010634
Guido van Rossumd57fd912000-03-10 22:53:23 +000010635 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010636 w = PyUnicode_New(
10637 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10638 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010639 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010640 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010641 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10642 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010643 Py_DECREF(u);
10644 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010645 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010647
Benjamin Peterson29060642009-01-31 22:14:21 +000010648 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010649 Py_XDECREF(u);
10650 Py_XDECREF(v);
10651 return NULL;
10652}
10653
Victor Stinnerb0923652011-10-04 01:17:31 +020010654static void
10655unicode_append_inplace(PyObject **p_left, PyObject *right)
10656{
10657 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010658
10659 assert(PyUnicode_IS_READY(*p_left));
10660 assert(PyUnicode_IS_READY(right));
10661
10662 left_len = PyUnicode_GET_LENGTH(*p_left);
10663 right_len = PyUnicode_GET_LENGTH(right);
10664 if (left_len > PY_SSIZE_T_MAX - right_len) {
10665 PyErr_SetString(PyExc_OverflowError,
10666 "strings are too large to concat");
10667 goto error;
10668 }
10669 new_len = left_len + right_len;
10670
10671 /* Now we own the last reference to 'left', so we can resize it
10672 * in-place.
10673 */
10674 if (unicode_resize(p_left, new_len) != 0) {
10675 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10676 * deallocated so it cannot be put back into
10677 * 'variable'. The MemoryError is raised when there
10678 * is no value in 'variable', which might (very
10679 * remotely) be a cause of incompatibilities.
10680 */
10681 goto error;
10682 }
10683 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010684 copy_characters(*p_left, left_len, right, 0, right_len);
10685 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010686 return;
10687
10688error:
10689 Py_DECREF(*p_left);
10690 *p_left = NULL;
10691}
10692
Walter Dörwald1ab83302007-05-18 17:15:44 +000010693void
Victor Stinner23e56682011-10-03 03:54:37 +020010694PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010695{
Victor Stinner23e56682011-10-03 03:54:37 +020010696 PyObject *left, *res;
10697
10698 if (p_left == NULL) {
10699 if (!PyErr_Occurred())
10700 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010701 return;
10702 }
Victor Stinner23e56682011-10-03 03:54:37 +020010703 left = *p_left;
10704 if (right == NULL || !PyUnicode_Check(left)) {
10705 if (!PyErr_Occurred())
10706 PyErr_BadInternalCall();
10707 goto error;
10708 }
10709
Victor Stinnere1335c72011-10-04 20:53:03 +020010710 if (PyUnicode_READY(left))
10711 goto error;
10712 if (PyUnicode_READY(right))
10713 goto error;
10714
Victor Stinner23e56682011-10-03 03:54:37 +020010715 if (PyUnicode_CheckExact(left) && left != unicode_empty
10716 && PyUnicode_CheckExact(right) && right != unicode_empty
10717 && unicode_resizable(left)
10718 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10719 || _PyUnicode_WSTR(left) != NULL))
10720 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010721 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10722 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010723 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010724 not so different than duplicating the string. */
10725 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010726 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010727 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010728 if (p_left != NULL)
10729 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010730 return;
10731 }
10732 }
10733
10734 res = PyUnicode_Concat(left, right);
10735 if (res == NULL)
10736 goto error;
10737 Py_DECREF(left);
10738 *p_left = res;
10739 return;
10740
10741error:
10742 Py_DECREF(*p_left);
10743 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010744}
10745
10746void
10747PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10748{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010749 PyUnicode_Append(pleft, right);
10750 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010751}
10752
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010753PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010754 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010755\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010756Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010757string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010758interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010759
10760static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010761unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010762{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010763 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010764 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010765 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010766 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010767 int kind1, kind2, kind;
10768 void *buf1, *buf2;
10769 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010770
Jesus Ceaac451502011-04-20 17:09:23 +020010771 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10772 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010773 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010774
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010775 kind1 = PyUnicode_KIND(self);
10776 kind2 = PyUnicode_KIND(substring);
10777 kind = kind1 > kind2 ? kind1 : kind2;
10778 buf1 = PyUnicode_DATA(self);
10779 buf2 = PyUnicode_DATA(substring);
10780 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010781 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010782 if (!buf1) {
10783 Py_DECREF(substring);
10784 return NULL;
10785 }
10786 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010787 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010788 if (!buf2) {
10789 Py_DECREF(substring);
10790 if (kind1 != kind) PyMem_Free(buf1);
10791 return NULL;
10792 }
10793 len1 = PyUnicode_GET_LENGTH(self);
10794 len2 = PyUnicode_GET_LENGTH(substring);
10795
10796 ADJUST_INDICES(start, end, len1);
10797 switch(kind) {
10798 case PyUnicode_1BYTE_KIND:
10799 iresult = ucs1lib_count(
10800 ((Py_UCS1*)buf1) + start, end - start,
10801 buf2, len2, PY_SSIZE_T_MAX
10802 );
10803 break;
10804 case PyUnicode_2BYTE_KIND:
10805 iresult = ucs2lib_count(
10806 ((Py_UCS2*)buf1) + start, end - start,
10807 buf2, len2, PY_SSIZE_T_MAX
10808 );
10809 break;
10810 case PyUnicode_4BYTE_KIND:
10811 iresult = ucs4lib_count(
10812 ((Py_UCS4*)buf1) + start, end - start,
10813 buf2, len2, PY_SSIZE_T_MAX
10814 );
10815 break;
10816 default:
10817 assert(0); iresult = 0;
10818 }
10819
10820 result = PyLong_FromSsize_t(iresult);
10821
10822 if (kind1 != kind)
10823 PyMem_Free(buf1);
10824 if (kind2 != kind)
10825 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010826
10827 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010828
Guido van Rossumd57fd912000-03-10 22:53:23 +000010829 return result;
10830}
10831
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010832PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010833 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010834\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010835Encode S using the codec registered for encoding. Default encoding\n\
10836is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010837handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010838a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10839'xmlcharrefreplace' as well as any other name registered with\n\
10840codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010841
10842static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010843unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010844{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010845 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010846 char *encoding = NULL;
10847 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010848
Benjamin Peterson308d6372009-09-18 21:42:35 +000010849 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10850 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010851 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010852 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010853}
10854
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010855PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010856 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010857\n\
10858Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010859If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010860
10861static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010862unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010863{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010864 Py_ssize_t i, j, line_pos, src_len, incr;
10865 Py_UCS4 ch;
10866 PyObject *u;
10867 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010868 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010869 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010870 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010871
10872 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010873 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010874
Antoine Pitrou22425222011-10-04 19:10:51 +020010875 if (PyUnicode_READY(self) == -1)
10876 return NULL;
10877
Thomas Wouters7e474022000-07-16 12:04:32 +000010878 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010879 src_len = PyUnicode_GET_LENGTH(self);
10880 i = j = line_pos = 0;
10881 kind = PyUnicode_KIND(self);
10882 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010883 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010884 for (; i < src_len; i++) {
10885 ch = PyUnicode_READ(kind, src_data, i);
10886 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010887 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010888 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010889 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010890 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010891 goto overflow;
10892 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010893 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010894 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010895 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010896 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010897 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010898 goto overflow;
10899 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010900 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010901 if (ch == '\n' || ch == '\r')
10902 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010903 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010904 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010905 if (!found && PyUnicode_CheckExact(self)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +010010906 Py_INCREF(self);
10907 return self;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010908 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010909
Guido van Rossumd57fd912000-03-10 22:53:23 +000010910 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010911 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010912 if (!u)
10913 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010914 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010915
Antoine Pitroue71d5742011-10-04 15:55:09 +020010916 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010917
Antoine Pitroue71d5742011-10-04 15:55:09 +020010918 for (; i < src_len; i++) {
10919 ch = PyUnicode_READ(kind, src_data, i);
10920 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010921 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010922 incr = tabsize - (line_pos % tabsize);
10923 line_pos += incr;
10924 while (incr--) {
10925 PyUnicode_WRITE(kind, dest_data, j, ' ');
10926 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010927 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010928 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010929 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010930 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010931 line_pos++;
10932 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010933 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010934 if (ch == '\n' || ch == '\r')
10935 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010936 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010937 }
10938 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020010939#ifndef DONT_MAKE_RESULT_READY
10940 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010941 Py_DECREF(u);
10942 return NULL;
10943 }
Victor Stinner17efeed2011-10-04 20:05:46 +020010944#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010945 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010010946 return u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010947
Antoine Pitroue71d5742011-10-04 15:55:09 +020010948 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010949 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10950 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010951}
10952
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010953PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010954 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010955\n\
10956Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010957such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010958arguments start and end are interpreted as in slice notation.\n\
10959\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010960Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010961
10962static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010963unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010964{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010965 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010966 Py_ssize_t start;
10967 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010968 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010969
Jesus Ceaac451502011-04-20 17:09:23 +020010970 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10971 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010972 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010973
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010974 if (PyUnicode_READY(self) == -1)
10975 return NULL;
10976 if (PyUnicode_READY(substring) == -1)
10977 return NULL;
10978
Victor Stinner7931d9a2011-11-04 00:22:48 +010010979 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010980
10981 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010983 if (result == -2)
10984 return NULL;
10985
Christian Heimes217cfd12007-12-02 14:31:20 +000010986 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010987}
10988
10989static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010990unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010991{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010992 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
10993 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010994 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010995 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010996}
10997
Guido van Rossumc2504932007-09-18 19:42:40 +000010998/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010010999 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011000static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011001unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002{
Guido van Rossumc2504932007-09-18 19:42:40 +000011003 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011004 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011005
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011006 if (_PyUnicode_HASH(self) != -1)
11007 return _PyUnicode_HASH(self);
11008 if (PyUnicode_READY(self) == -1)
11009 return -1;
11010 len = PyUnicode_GET_LENGTH(self);
11011
11012 /* The hash function as a macro, gets expanded three times below. */
11013#define HASH(P) \
11014 x = (Py_uhash_t)*P << 7; \
11015 while (--len >= 0) \
11016 x = (1000003*x) ^ (Py_uhash_t)*P++;
11017
11018 switch (PyUnicode_KIND(self)) {
11019 case PyUnicode_1BYTE_KIND: {
11020 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11021 HASH(c);
11022 break;
11023 }
11024 case PyUnicode_2BYTE_KIND: {
11025 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11026 HASH(s);
11027 break;
11028 }
11029 default: {
11030 Py_UCS4 *l;
11031 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11032 "Impossible switch case in unicode_hash");
11033 l = PyUnicode_4BYTE_DATA(self);
11034 HASH(l);
11035 break;
11036 }
11037 }
11038 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11039
Guido van Rossumc2504932007-09-18 19:42:40 +000011040 if (x == -1)
11041 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011042 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011043 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011045#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011046
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011047PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011048 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011049\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011050Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011051
11052static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011053unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011054{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011055 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011056 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011057 Py_ssize_t start;
11058 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011059
Jesus Ceaac451502011-04-20 17:09:23 +020011060 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11061 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011062 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011063
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011064 if (PyUnicode_READY(self) == -1)
11065 return NULL;
11066 if (PyUnicode_READY(substring) == -1)
11067 return NULL;
11068
Victor Stinner7931d9a2011-11-04 00:22:48 +010011069 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011070
11071 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011072
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011073 if (result == -2)
11074 return NULL;
11075
Guido van Rossumd57fd912000-03-10 22:53:23 +000011076 if (result < 0) {
11077 PyErr_SetString(PyExc_ValueError, "substring not found");
11078 return NULL;
11079 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011080
Christian Heimes217cfd12007-12-02 14:31:20 +000011081 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011082}
11083
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011084PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011085 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011086\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011087Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011088at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011089
11090static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011091unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011092{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011093 Py_ssize_t i, length;
11094 int kind;
11095 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011096 int cased;
11097
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011098 if (PyUnicode_READY(self) == -1)
11099 return NULL;
11100 length = PyUnicode_GET_LENGTH(self);
11101 kind = PyUnicode_KIND(self);
11102 data = PyUnicode_DATA(self);
11103
Guido van Rossumd57fd912000-03-10 22:53:23 +000011104 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011105 if (length == 1)
11106 return PyBool_FromLong(
11107 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011108
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011109 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011110 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011111 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011112
Guido van Rossumd57fd912000-03-10 22:53:23 +000011113 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011114 for (i = 0; i < length; i++) {
11115 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011116
Benjamin Peterson29060642009-01-31 22:14:21 +000011117 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11118 return PyBool_FromLong(0);
11119 else if (!cased && Py_UNICODE_ISLOWER(ch))
11120 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011121 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011122 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011123}
11124
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011125PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011126 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011127\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011128Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011129at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011130
11131static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011132unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011133{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011134 Py_ssize_t i, length;
11135 int kind;
11136 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011137 int cased;
11138
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011139 if (PyUnicode_READY(self) == -1)
11140 return NULL;
11141 length = PyUnicode_GET_LENGTH(self);
11142 kind = PyUnicode_KIND(self);
11143 data = PyUnicode_DATA(self);
11144
Guido van Rossumd57fd912000-03-10 22:53:23 +000011145 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011146 if (length == 1)
11147 return PyBool_FromLong(
11148 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011149
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011150 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011151 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011152 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011153
Guido van Rossumd57fd912000-03-10 22:53:23 +000011154 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011155 for (i = 0; i < length; i++) {
11156 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011157
Benjamin Peterson29060642009-01-31 22:14:21 +000011158 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11159 return PyBool_FromLong(0);
11160 else if (!cased && Py_UNICODE_ISUPPER(ch))
11161 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011162 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011163 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011164}
11165
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011166PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011167 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011168\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011169Return True if S is a titlecased string and there is at least one\n\
11170character in S, i.e. upper- and titlecase characters may only\n\
11171follow uncased characters and lowercase characters only cased ones.\n\
11172Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173
11174static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011175unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011176{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011177 Py_ssize_t i, length;
11178 int kind;
11179 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011180 int cased, previous_is_cased;
11181
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011182 if (PyUnicode_READY(self) == -1)
11183 return NULL;
11184 length = PyUnicode_GET_LENGTH(self);
11185 kind = PyUnicode_KIND(self);
11186 data = PyUnicode_DATA(self);
11187
Guido van Rossumd57fd912000-03-10 22:53:23 +000011188 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011189 if (length == 1) {
11190 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11191 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11192 (Py_UNICODE_ISUPPER(ch) != 0));
11193 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011194
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011195 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011196 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011197 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011198
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199 cased = 0;
11200 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011201 for (i = 0; i < length; i++) {
11202 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011203
Benjamin Peterson29060642009-01-31 22:14:21 +000011204 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11205 if (previous_is_cased)
11206 return PyBool_FromLong(0);
11207 previous_is_cased = 1;
11208 cased = 1;
11209 }
11210 else if (Py_UNICODE_ISLOWER(ch)) {
11211 if (!previous_is_cased)
11212 return PyBool_FromLong(0);
11213 previous_is_cased = 1;
11214 cased = 1;
11215 }
11216 else
11217 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011219 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011220}
11221
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011222PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011223 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011225Return True if all characters in S are whitespace\n\
11226and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011227
11228static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011229unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011231 Py_ssize_t i, length;
11232 int kind;
11233 void *data;
11234
11235 if (PyUnicode_READY(self) == -1)
11236 return NULL;
11237 length = PyUnicode_GET_LENGTH(self);
11238 kind = PyUnicode_KIND(self);
11239 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011240
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011242 if (length == 1)
11243 return PyBool_FromLong(
11244 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011245
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011246 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011247 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011248 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011249
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011250 for (i = 0; i < length; i++) {
11251 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011252 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011253 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011254 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011255 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011256}
11257
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011258PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011259 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011260\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011261Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011262and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011263
11264static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011265unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011266{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011267 Py_ssize_t i, length;
11268 int kind;
11269 void *data;
11270
11271 if (PyUnicode_READY(self) == -1)
11272 return NULL;
11273 length = PyUnicode_GET_LENGTH(self);
11274 kind = PyUnicode_KIND(self);
11275 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011276
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011277 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011278 if (length == 1)
11279 return PyBool_FromLong(
11280 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011281
11282 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011283 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011284 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011285
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011286 for (i = 0; i < length; i++) {
11287 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011288 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011289 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011290 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011291}
11292
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011293PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011294 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011295\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011296Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011297and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011298
11299static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011300unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011301{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011302 int kind;
11303 void *data;
11304 Py_ssize_t len, i;
11305
11306 if (PyUnicode_READY(self) == -1)
11307 return NULL;
11308
11309 kind = PyUnicode_KIND(self);
11310 data = PyUnicode_DATA(self);
11311 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011312
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011313 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011314 if (len == 1) {
11315 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11316 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11317 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011318
11319 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011320 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011321 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011322
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011323 for (i = 0; i < len; i++) {
11324 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011325 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011326 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011327 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011328 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011329}
11330
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011331PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011332 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011333\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011334Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011335False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011336
11337static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011338unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011339{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011340 Py_ssize_t i, length;
11341 int kind;
11342 void *data;
11343
11344 if (PyUnicode_READY(self) == -1)
11345 return NULL;
11346 length = PyUnicode_GET_LENGTH(self);
11347 kind = PyUnicode_KIND(self);
11348 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011349
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011351 if (length == 1)
11352 return PyBool_FromLong(
11353 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011354
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011355 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011356 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011357 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011358
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011359 for (i = 0; i < length; i++) {
11360 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011361 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011362 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011363 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011364}
11365
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011366PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011367 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011368\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011369Return True if all characters in S are digits\n\
11370and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011371
11372static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011373unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011374{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011375 Py_ssize_t i, length;
11376 int kind;
11377 void *data;
11378
11379 if (PyUnicode_READY(self) == -1)
11380 return NULL;
11381 length = PyUnicode_GET_LENGTH(self);
11382 kind = PyUnicode_KIND(self);
11383 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011384
Guido van Rossumd57fd912000-03-10 22:53:23 +000011385 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011386 if (length == 1) {
11387 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11388 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11389 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011390
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011391 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011392 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011393 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011394
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011395 for (i = 0; i < length; i++) {
11396 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011397 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011399 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011400}
11401
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011402PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011403 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011404\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011405Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011406False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407
11408static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011409unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011410{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011411 Py_ssize_t i, length;
11412 int kind;
11413 void *data;
11414
11415 if (PyUnicode_READY(self) == -1)
11416 return NULL;
11417 length = PyUnicode_GET_LENGTH(self);
11418 kind = PyUnicode_KIND(self);
11419 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011422 if (length == 1)
11423 return PyBool_FromLong(
11424 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011425
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011426 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011427 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011428 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011429
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011430 for (i = 0; i < length; i++) {
11431 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011432 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011434 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435}
11436
Martin v. Löwis47383402007-08-15 07:32:56 +000011437int
11438PyUnicode_IsIdentifier(PyObject *self)
11439{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011440 int kind;
11441 void *data;
11442 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011443 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011444
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011445 if (PyUnicode_READY(self) == -1) {
11446 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011447 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011448 }
11449
11450 /* Special case for empty strings */
11451 if (PyUnicode_GET_LENGTH(self) == 0)
11452 return 0;
11453 kind = PyUnicode_KIND(self);
11454 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011455
11456 /* PEP 3131 says that the first character must be in
11457 XID_Start and subsequent characters in XID_Continue,
11458 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011459 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011460 letters, digits, underscore). However, given the current
11461 definition of XID_Start and XID_Continue, it is sufficient
11462 to check just for these, except that _ must be allowed
11463 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011464 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011465 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011466 return 0;
11467
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011468 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011469 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011470 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011471 return 1;
11472}
11473
11474PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011475 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011476\n\
11477Return True if S is a valid identifier according\n\
11478to the language definition.");
11479
11480static PyObject*
11481unicode_isidentifier(PyObject *self)
11482{
11483 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11484}
11485
Georg Brandl559e5d72008-06-11 18:37:52 +000011486PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011487 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011488\n\
11489Return True if all characters in S are considered\n\
11490printable in repr() or S is empty, False otherwise.");
11491
11492static PyObject*
11493unicode_isprintable(PyObject *self)
11494{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011495 Py_ssize_t i, length;
11496 int kind;
11497 void *data;
11498
11499 if (PyUnicode_READY(self) == -1)
11500 return NULL;
11501 length = PyUnicode_GET_LENGTH(self);
11502 kind = PyUnicode_KIND(self);
11503 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011504
11505 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011506 if (length == 1)
11507 return PyBool_FromLong(
11508 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011509
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011510 for (i = 0; i < length; i++) {
11511 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011512 Py_RETURN_FALSE;
11513 }
11514 }
11515 Py_RETURN_TRUE;
11516}
11517
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011518PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011519 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520\n\
11521Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011522iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011523
11524static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011525unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011526{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011527 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011528}
11529
Martin v. Löwis18e16552006-02-15 17:27:45 +000011530static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011531unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011533 if (PyUnicode_READY(self) == -1)
11534 return -1;
11535 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011536}
11537
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011538PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011539 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011541Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011542done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011543
11544static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011545unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011546{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011547 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011548 Py_UCS4 fillchar = ' ';
11549
11550 if (PyUnicode_READY(self) == -1)
11551 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011552
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011553 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554 return NULL;
11555
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011556 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011558 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011559 }
11560
Victor Stinner7931d9a2011-11-04 00:22:48 +010011561 return pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011562}
11563
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011564PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011565 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011566\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011567Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011568
11569static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011570unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011571{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572 return fixup(self, fixlower);
11573}
11574
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011575#define LEFTSTRIP 0
11576#define RIGHTSTRIP 1
11577#define BOTHSTRIP 2
11578
11579/* Arrays indexed by above */
11580static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11581
11582#define STRIPNAME(i) (stripformat[i]+3)
11583
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011584/* externally visible for str.strip(unicode) */
11585PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011586_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011587{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011588 void *data;
11589 int kind;
11590 Py_ssize_t i, j, len;
11591 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011592
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011593 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11594 return NULL;
11595
11596 kind = PyUnicode_KIND(self);
11597 data = PyUnicode_DATA(self);
11598 len = PyUnicode_GET_LENGTH(self);
11599 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11600 PyUnicode_DATA(sepobj),
11601 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011602
Benjamin Peterson14339b62009-01-31 16:36:08 +000011603 i = 0;
11604 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011605 while (i < len &&
11606 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011607 i++;
11608 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011609 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011610
Benjamin Peterson14339b62009-01-31 16:36:08 +000011611 j = len;
11612 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011613 do {
11614 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011615 } while (j >= i &&
11616 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011617 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011618 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011619
Victor Stinner7931d9a2011-11-04 00:22:48 +010011620 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011621}
11622
11623PyObject*
11624PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11625{
11626 unsigned char *data;
11627 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011628 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011629
Victor Stinnerde636f32011-10-01 03:55:54 +020011630 if (PyUnicode_READY(self) == -1)
11631 return NULL;
11632
11633 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11634
Victor Stinner12bab6d2011-10-01 01:53:49 +020011635 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011636 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011637 if (PyUnicode_CheckExact(self)) {
11638 Py_INCREF(self);
11639 return self;
11640 }
11641 else
11642 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011643 }
11644
Victor Stinner12bab6d2011-10-01 01:53:49 +020011645 length = end - start;
11646 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011647 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011648
Victor Stinnerde636f32011-10-01 03:55:54 +020011649 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011650 PyErr_SetString(PyExc_IndexError, "string index out of range");
11651 return NULL;
11652 }
11653
Victor Stinnerb9275c12011-10-05 14:01:42 +020011654 if (PyUnicode_IS_ASCII(self)) {
11655 kind = PyUnicode_KIND(self);
11656 data = PyUnicode_1BYTE_DATA(self);
11657 return unicode_fromascii(data + start, length);
11658 }
11659 else {
11660 kind = PyUnicode_KIND(self);
11661 data = PyUnicode_1BYTE_DATA(self);
11662 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011663 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011664 length);
11665 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011666}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011667
11668static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011669do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011670{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011671 int kind;
11672 void *data;
11673 Py_ssize_t len, i, j;
11674
11675 if (PyUnicode_READY(self) == -1)
11676 return NULL;
11677
11678 kind = PyUnicode_KIND(self);
11679 data = PyUnicode_DATA(self);
11680 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011681
Benjamin Peterson14339b62009-01-31 16:36:08 +000011682 i = 0;
11683 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011684 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011685 i++;
11686 }
11687 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011688
Benjamin Peterson14339b62009-01-31 16:36:08 +000011689 j = len;
11690 if (striptype != LEFTSTRIP) {
11691 do {
11692 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011693 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011694 j++;
11695 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011696
Victor Stinner7931d9a2011-11-04 00:22:48 +010011697 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011698}
11699
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011700
11701static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011702do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011703{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011704 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011705
Benjamin Peterson14339b62009-01-31 16:36:08 +000011706 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11707 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011708
Benjamin Peterson14339b62009-01-31 16:36:08 +000011709 if (sep != NULL && sep != Py_None) {
11710 if (PyUnicode_Check(sep))
11711 return _PyUnicode_XStrip(self, striptype, sep);
11712 else {
11713 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011714 "%s arg must be None or str",
11715 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011716 return NULL;
11717 }
11718 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011719
Benjamin Peterson14339b62009-01-31 16:36:08 +000011720 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011721}
11722
11723
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011724PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011725 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011726\n\
11727Return a copy of the string S with leading and trailing\n\
11728whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011729If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011730
11731static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011732unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011733{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011734 if (PyTuple_GET_SIZE(args) == 0)
11735 return do_strip(self, BOTHSTRIP); /* Common case */
11736 else
11737 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011738}
11739
11740
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011741PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011742 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011743\n\
11744Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011745If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011746
11747static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011748unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011749{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011750 if (PyTuple_GET_SIZE(args) == 0)
11751 return do_strip(self, LEFTSTRIP); /* Common case */
11752 else
11753 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011754}
11755
11756
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011757PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011758 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011759\n\
11760Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011761If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011762
11763static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011764unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011765{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011766 if (PyTuple_GET_SIZE(args) == 0)
11767 return do_strip(self, RIGHTSTRIP); /* Common case */
11768 else
11769 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011770}
11771
11772
Guido van Rossumd57fd912000-03-10 22:53:23 +000011773static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011774unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011775{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011776 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011777 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011778
Georg Brandl222de0f2009-04-12 12:01:50 +000011779 if (len < 1) {
11780 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011781 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011782 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011783
Tim Peters7a29bd52001-09-12 03:03:31 +000011784 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011785 /* no repeat, return original string */
11786 Py_INCREF(str);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011787 return str;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011788 }
Tim Peters8f422462000-09-09 06:13:41 +000011789
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011790 if (PyUnicode_READY(str) == -1)
11791 return NULL;
11792
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011793 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011794 PyErr_SetString(PyExc_OverflowError,
11795 "repeated string is too long");
11796 return NULL;
11797 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011798 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011799
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011800 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011801 if (!u)
11802 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011803 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011804
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011805 if (PyUnicode_GET_LENGTH(str) == 1) {
11806 const int kind = PyUnicode_KIND(str);
11807 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11808 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011809 if (kind == PyUnicode_1BYTE_KIND)
11810 memset(to, (unsigned char)fill_char, len);
11811 else {
11812 for (n = 0; n < len; ++n)
11813 PyUnicode_WRITE(kind, to, n, fill_char);
11814 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011815 }
11816 else {
11817 /* number of characters copied this far */
11818 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011819 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011820 char *to = (char *) PyUnicode_DATA(u);
11821 Py_MEMCPY(to, PyUnicode_DATA(str),
11822 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011823 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011824 n = (done <= nchars-done) ? done : nchars-done;
11825 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011826 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011827 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011828 }
11829
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011830 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011831 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011832}
11833
Alexander Belopolsky40018472011-02-26 01:02:56 +000011834PyObject *
11835PyUnicode_Replace(PyObject *obj,
11836 PyObject *subobj,
11837 PyObject *replobj,
11838 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011839{
11840 PyObject *self;
11841 PyObject *str1;
11842 PyObject *str2;
11843 PyObject *result;
11844
11845 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011846 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011847 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011848 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011849 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011850 Py_DECREF(self);
11851 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011852 }
11853 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011854 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011855 Py_DECREF(self);
11856 Py_DECREF(str1);
11857 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011858 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011859 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860 Py_DECREF(self);
11861 Py_DECREF(str1);
11862 Py_DECREF(str2);
11863 return result;
11864}
11865
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011866PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011867 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011868\n\
11869Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011870old replaced by new. If the optional argument count is\n\
11871given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011872
11873static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011874unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011875{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011876 PyObject *str1;
11877 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011878 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011879 PyObject *result;
11880
Martin v. Löwis18e16552006-02-15 17:27:45 +000011881 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011882 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011883 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011884 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011885 str1 = PyUnicode_FromObject(str1);
11886 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11887 return NULL;
11888 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011889 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011890 Py_DECREF(str1);
11891 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011892 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011893
11894 result = replace(self, str1, str2, maxcount);
11895
11896 Py_DECREF(str1);
11897 Py_DECREF(str2);
11898 return result;
11899}
11900
Alexander Belopolsky40018472011-02-26 01:02:56 +000011901static PyObject *
11902unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011903{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011904 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011905 Py_ssize_t isize;
11906 Py_ssize_t osize, squote, dquote, i, o;
11907 Py_UCS4 max, quote;
11908 int ikind, okind;
11909 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011910
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011911 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011912 return NULL;
11913
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011914 isize = PyUnicode_GET_LENGTH(unicode);
11915 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011916
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011917 /* Compute length of output, quote characters, and
11918 maximum character */
11919 osize = 2; /* quotes */
11920 max = 127;
11921 squote = dquote = 0;
11922 ikind = PyUnicode_KIND(unicode);
11923 for (i = 0; i < isize; i++) {
11924 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11925 switch (ch) {
11926 case '\'': squote++; osize++; break;
11927 case '"': dquote++; osize++; break;
11928 case '\\': case '\t': case '\r': case '\n':
11929 osize += 2; break;
11930 default:
11931 /* Fast-path ASCII */
11932 if (ch < ' ' || ch == 0x7f)
11933 osize += 4; /* \xHH */
11934 else if (ch < 0x7f)
11935 osize++;
11936 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11937 osize++;
11938 max = ch > max ? ch : max;
11939 }
11940 else if (ch < 0x100)
11941 osize += 4; /* \xHH */
11942 else if (ch < 0x10000)
11943 osize += 6; /* \uHHHH */
11944 else
11945 osize += 10; /* \uHHHHHHHH */
11946 }
11947 }
11948
11949 quote = '\'';
11950 if (squote) {
11951 if (dquote)
11952 /* Both squote and dquote present. Use squote,
11953 and escape them */
11954 osize += squote;
11955 else
11956 quote = '"';
11957 }
11958
11959 repr = PyUnicode_New(osize, max);
11960 if (repr == NULL)
11961 return NULL;
11962 okind = PyUnicode_KIND(repr);
11963 odata = PyUnicode_DATA(repr);
11964
11965 PyUnicode_WRITE(okind, odata, 0, quote);
11966 PyUnicode_WRITE(okind, odata, osize-1, quote);
11967
11968 for (i = 0, o = 1; i < isize; i++) {
11969 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011970
11971 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011972 if ((ch == quote) || (ch == '\\')) {
11973 PyUnicode_WRITE(okind, odata, o++, '\\');
11974 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011975 continue;
11976 }
11977
Benjamin Peterson29060642009-01-31 22:14:21 +000011978 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011979 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011980 PyUnicode_WRITE(okind, odata, o++, '\\');
11981 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011982 }
11983 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011984 PyUnicode_WRITE(okind, odata, o++, '\\');
11985 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011986 }
11987 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011988 PyUnicode_WRITE(okind, odata, o++, '\\');
11989 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011990 }
11991
11992 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011993 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011994 PyUnicode_WRITE(okind, odata, o++, '\\');
11995 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020011996 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
11997 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011998 }
11999
Georg Brandl559e5d72008-06-11 18:37:52 +000012000 /* Copy ASCII characters as-is */
12001 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012002 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012003 }
12004
Benjamin Peterson29060642009-01-31 22:14:21 +000012005 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012006 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012007 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012008 (categories Z* and C* except ASCII space)
12009 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012010 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012011 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012012 if (ch <= 0xff) {
12013 PyUnicode_WRITE(okind, odata, o++, '\\');
12014 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012015 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12016 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012017 }
12018 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012019 else if (ch >= 0x10000) {
12020 PyUnicode_WRITE(okind, odata, o++, '\\');
12021 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012022 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12023 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12024 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12025 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12026 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12027 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12028 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12029 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012030 }
12031 /* Map 16-bit characters to '\uxxxx' */
12032 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012033 PyUnicode_WRITE(okind, odata, o++, '\\');
12034 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012035 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12036 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12037 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12038 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012039 }
12040 }
12041 /* Copy characters as-is */
12042 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012043 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012044 }
12045 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012046 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012047 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012048 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012049 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012050}
12051
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012052PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012053 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012054\n\
12055Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012056such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012057arguments start and end are interpreted as in slice notation.\n\
12058\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012059Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012060
12061static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012062unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012063{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012064 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012065 Py_ssize_t start;
12066 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012067 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012068
Jesus Ceaac451502011-04-20 17:09:23 +020012069 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12070 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012071 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012072
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012073 if (PyUnicode_READY(self) == -1)
12074 return NULL;
12075 if (PyUnicode_READY(substring) == -1)
12076 return NULL;
12077
Victor Stinner7931d9a2011-11-04 00:22:48 +010012078 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012079
12080 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012081
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012082 if (result == -2)
12083 return NULL;
12084
Christian Heimes217cfd12007-12-02 14:31:20 +000012085 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012086}
12087
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012088PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012089 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012090\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012091Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012092
12093static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012094unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012095{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012096 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012097 Py_ssize_t start;
12098 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012099 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012100
Jesus Ceaac451502011-04-20 17:09:23 +020012101 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12102 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012103 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012105 if (PyUnicode_READY(self) == -1)
12106 return NULL;
12107 if (PyUnicode_READY(substring) == -1)
12108 return NULL;
12109
Victor Stinner7931d9a2011-11-04 00:22:48 +010012110 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012111
12112 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012113
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012114 if (result == -2)
12115 return NULL;
12116
Guido van Rossumd57fd912000-03-10 22:53:23 +000012117 if (result < 0) {
12118 PyErr_SetString(PyExc_ValueError, "substring not found");
12119 return NULL;
12120 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012121
Christian Heimes217cfd12007-12-02 14:31:20 +000012122 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012123}
12124
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012125PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012126 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012127\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012128Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012129done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012130
12131static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012132unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012133{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012134 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012135 Py_UCS4 fillchar = ' ';
12136
Victor Stinnere9a29352011-10-01 02:14:59 +020012137 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012138 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012139
Victor Stinnere9a29352011-10-01 02:14:59 +020012140 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012141 return NULL;
12142
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012143 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012144 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012145 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012146 }
12147
Victor Stinner7931d9a2011-11-04 00:22:48 +010012148 return pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012149}
12150
Alexander Belopolsky40018472011-02-26 01:02:56 +000012151PyObject *
12152PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012153{
12154 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012155
Guido van Rossumd57fd912000-03-10 22:53:23 +000012156 s = PyUnicode_FromObject(s);
12157 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012158 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012159 if (sep != NULL) {
12160 sep = PyUnicode_FromObject(sep);
12161 if (sep == NULL) {
12162 Py_DECREF(s);
12163 return NULL;
12164 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012165 }
12166
Victor Stinner9310abb2011-10-05 00:59:23 +020012167 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012168
12169 Py_DECREF(s);
12170 Py_XDECREF(sep);
12171 return result;
12172}
12173
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012174PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012175 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012176\n\
12177Return a list of the words in S, using sep as the\n\
12178delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012179splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012180whitespace string is a separator and empty strings are\n\
12181removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012182
12183static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012184unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012185{
12186 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012187 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188
Martin v. Löwis18e16552006-02-15 17:27:45 +000012189 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012190 return NULL;
12191
12192 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012193 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012194 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012195 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012196 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012197 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012198}
12199
Thomas Wouters477c8d52006-05-27 19:21:47 +000012200PyObject *
12201PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12202{
12203 PyObject* str_obj;
12204 PyObject* sep_obj;
12205 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012206 int kind1, kind2, kind;
12207 void *buf1 = NULL, *buf2 = NULL;
12208 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012209
12210 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012211 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012212 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012213 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012214 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012215 Py_DECREF(str_obj);
12216 return NULL;
12217 }
12218
Victor Stinner14f8f022011-10-05 20:58:25 +020012219 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012220 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012221 kind = Py_MAX(kind1, kind2);
12222 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012223 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012224 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012225 if (!buf1)
12226 goto onError;
12227 buf2 = PyUnicode_DATA(sep_obj);
12228 if (kind2 != kind)
12229 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12230 if (!buf2)
12231 goto onError;
12232 len1 = PyUnicode_GET_LENGTH(str_obj);
12233 len2 = PyUnicode_GET_LENGTH(sep_obj);
12234
Victor Stinner14f8f022011-10-05 20:58:25 +020012235 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012236 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012237 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12238 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12239 else
12240 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012241 break;
12242 case PyUnicode_2BYTE_KIND:
12243 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12244 break;
12245 case PyUnicode_4BYTE_KIND:
12246 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12247 break;
12248 default:
12249 assert(0);
12250 out = 0;
12251 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012252
12253 Py_DECREF(sep_obj);
12254 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012255 if (kind1 != kind)
12256 PyMem_Free(buf1);
12257 if (kind2 != kind)
12258 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012259
12260 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012261 onError:
12262 Py_DECREF(sep_obj);
12263 Py_DECREF(str_obj);
12264 if (kind1 != kind && buf1)
12265 PyMem_Free(buf1);
12266 if (kind2 != kind && buf2)
12267 PyMem_Free(buf2);
12268 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012269}
12270
12271
12272PyObject *
12273PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12274{
12275 PyObject* str_obj;
12276 PyObject* sep_obj;
12277 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012278 int kind1, kind2, kind;
12279 void *buf1 = NULL, *buf2 = NULL;
12280 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012281
12282 str_obj = PyUnicode_FromObject(str_in);
12283 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012284 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012285 sep_obj = PyUnicode_FromObject(sep_in);
12286 if (!sep_obj) {
12287 Py_DECREF(str_obj);
12288 return NULL;
12289 }
12290
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012291 kind1 = PyUnicode_KIND(str_in);
12292 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012293 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012294 buf1 = PyUnicode_DATA(str_in);
12295 if (kind1 != kind)
12296 buf1 = _PyUnicode_AsKind(str_in, kind);
12297 if (!buf1)
12298 goto onError;
12299 buf2 = PyUnicode_DATA(sep_obj);
12300 if (kind2 != kind)
12301 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12302 if (!buf2)
12303 goto onError;
12304 len1 = PyUnicode_GET_LENGTH(str_obj);
12305 len2 = PyUnicode_GET_LENGTH(sep_obj);
12306
12307 switch(PyUnicode_KIND(str_in)) {
12308 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012309 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12310 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12311 else
12312 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012313 break;
12314 case PyUnicode_2BYTE_KIND:
12315 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12316 break;
12317 case PyUnicode_4BYTE_KIND:
12318 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12319 break;
12320 default:
12321 assert(0);
12322 out = 0;
12323 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012324
12325 Py_DECREF(sep_obj);
12326 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012327 if (kind1 != kind)
12328 PyMem_Free(buf1);
12329 if (kind2 != kind)
12330 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012331
12332 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012333 onError:
12334 Py_DECREF(sep_obj);
12335 Py_DECREF(str_obj);
12336 if (kind1 != kind && buf1)
12337 PyMem_Free(buf1);
12338 if (kind2 != kind && buf2)
12339 PyMem_Free(buf2);
12340 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012341}
12342
12343PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012344 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012345\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012346Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012347the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012348found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012349
12350static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012351unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012352{
Victor Stinner9310abb2011-10-05 00:59:23 +020012353 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012354}
12355
12356PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012357 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012358\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012359Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012360the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012361separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012362
12363static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012364unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012365{
Victor Stinner9310abb2011-10-05 00:59:23 +020012366 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012367}
12368
Alexander Belopolsky40018472011-02-26 01:02:56 +000012369PyObject *
12370PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012371{
12372 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012373
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012374 s = PyUnicode_FromObject(s);
12375 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012376 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012377 if (sep != NULL) {
12378 sep = PyUnicode_FromObject(sep);
12379 if (sep == NULL) {
12380 Py_DECREF(s);
12381 return NULL;
12382 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012383 }
12384
Victor Stinner9310abb2011-10-05 00:59:23 +020012385 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012386
12387 Py_DECREF(s);
12388 Py_XDECREF(sep);
12389 return result;
12390}
12391
12392PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012393 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012394\n\
12395Return a list of the words in S, using sep as the\n\
12396delimiter string, starting at the end of the string and\n\
12397working to the front. If maxsplit is given, at most maxsplit\n\
12398splits are done. If sep is not specified, any whitespace string\n\
12399is a separator.");
12400
12401static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012402unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012403{
12404 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012405 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012406
Martin v. Löwis18e16552006-02-15 17:27:45 +000012407 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012408 return NULL;
12409
12410 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012411 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012412 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012413 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012414 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012415 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012416}
12417
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012418PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012419 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012420\n\
12421Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012422Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012423is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012424
12425static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012426unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012427{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012428 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012429 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012430
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012431 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12432 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012433 return NULL;
12434
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012435 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012436}
12437
12438static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012439PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012440{
Walter Dörwald346737f2007-05-31 10:44:43 +000012441 if (PyUnicode_CheckExact(self)) {
12442 Py_INCREF(self);
12443 return self;
12444 } else
12445 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012446 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012447}
12448
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012449PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012450 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012451\n\
12452Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012453and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012454
12455static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012456unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012457{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012458 return fixup(self, fixswapcase);
12459}
12460
Georg Brandlceee0772007-11-27 23:48:05 +000012461PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012462 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012463\n\
12464Return a translation table usable for str.translate().\n\
12465If there is only one argument, it must be a dictionary mapping Unicode\n\
12466ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012467Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012468If there are two arguments, they must be strings of equal length, and\n\
12469in the resulting dictionary, each character in x will be mapped to the\n\
12470character at the same position in y. If there is a third argument, it\n\
12471must be a string, whose characters will be mapped to None in the result.");
12472
12473static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012474unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012475{
12476 PyObject *x, *y = NULL, *z = NULL;
12477 PyObject *new = NULL, *key, *value;
12478 Py_ssize_t i = 0;
12479 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012480
Georg Brandlceee0772007-11-27 23:48:05 +000012481 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12482 return NULL;
12483 new = PyDict_New();
12484 if (!new)
12485 return NULL;
12486 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012487 int x_kind, y_kind, z_kind;
12488 void *x_data, *y_data, *z_data;
12489
Georg Brandlceee0772007-11-27 23:48:05 +000012490 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012491 if (!PyUnicode_Check(x)) {
12492 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12493 "be a string if there is a second argument");
12494 goto err;
12495 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012496 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012497 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12498 "arguments must have equal length");
12499 goto err;
12500 }
12501 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012502 x_kind = PyUnicode_KIND(x);
12503 y_kind = PyUnicode_KIND(y);
12504 x_data = PyUnicode_DATA(x);
12505 y_data = PyUnicode_DATA(y);
12506 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12507 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12508 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012509 if (!key || !value)
12510 goto err;
12511 res = PyDict_SetItem(new, key, value);
12512 Py_DECREF(key);
12513 Py_DECREF(value);
12514 if (res < 0)
12515 goto err;
12516 }
12517 /* create entries for deleting chars in z */
12518 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012519 z_kind = PyUnicode_KIND(z);
12520 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012521 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012522 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012523 if (!key)
12524 goto err;
12525 res = PyDict_SetItem(new, key, Py_None);
12526 Py_DECREF(key);
12527 if (res < 0)
12528 goto err;
12529 }
12530 }
12531 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012532 int kind;
12533 void *data;
12534
Georg Brandlceee0772007-11-27 23:48:05 +000012535 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012536 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012537 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12538 "to maketrans it must be a dict");
12539 goto err;
12540 }
12541 /* copy entries into the new dict, converting string keys to int keys */
12542 while (PyDict_Next(x, &i, &key, &value)) {
12543 if (PyUnicode_Check(key)) {
12544 /* convert string keys to integer keys */
12545 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012546 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012547 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12548 "table must be of length 1");
12549 goto err;
12550 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012551 kind = PyUnicode_KIND(key);
12552 data = PyUnicode_DATA(key);
12553 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012554 if (!newkey)
12555 goto err;
12556 res = PyDict_SetItem(new, newkey, value);
12557 Py_DECREF(newkey);
12558 if (res < 0)
12559 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012560 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012561 /* just keep integer keys */
12562 if (PyDict_SetItem(new, key, value) < 0)
12563 goto err;
12564 } else {
12565 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12566 "be strings or integers");
12567 goto err;
12568 }
12569 }
12570 }
12571 return new;
12572 err:
12573 Py_DECREF(new);
12574 return NULL;
12575}
12576
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012577PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012578 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012579\n\
12580Return a copy of the string S, where all characters have been mapped\n\
12581through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012582Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012583Unmapped characters are left untouched. Characters mapped to None\n\
12584are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012585
12586static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012587unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012588{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012589 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012590}
12591
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012592PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012593 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012594\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012595Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012596
12597static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012598unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012599{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012600 return fixup(self, fixupper);
12601}
12602
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012603PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012604 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012605\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012606Pad a numeric string S with zeros on the left, to fill a field\n\
12607of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012608
12609static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012610unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012611{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012612 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012613 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012614 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012615 int kind;
12616 void *data;
12617 Py_UCS4 chr;
12618
12619 if (PyUnicode_READY(self) == -1)
12620 return NULL;
12621
Martin v. Löwis18e16552006-02-15 17:27:45 +000012622 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012623 return NULL;
12624
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012625 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012626 if (PyUnicode_CheckExact(self)) {
12627 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012628 return self;
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012629 }
12630 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012631 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012632 }
12633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012634 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012635
12636 u = pad(self, fill, 0, '0');
12637
Walter Dörwald068325e2002-04-15 13:36:47 +000012638 if (u == NULL)
12639 return NULL;
12640
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012641 kind = PyUnicode_KIND(u);
12642 data = PyUnicode_DATA(u);
12643 chr = PyUnicode_READ(kind, data, fill);
12644
12645 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012646 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012647 PyUnicode_WRITE(kind, data, 0, chr);
12648 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012649 }
12650
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012651 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012652 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012653}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012654
12655#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012656static PyObject *
12657unicode__decimal2ascii(PyObject *self)
12658{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012659 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012660}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012661#endif
12662
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012663PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012664 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012665\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012666Return True if S starts with the specified prefix, False otherwise.\n\
12667With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012668With optional end, stop comparing S at that position.\n\
12669prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012670
12671static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012672unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012673 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012674{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012675 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012676 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012677 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012678 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012679 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012680
Jesus Ceaac451502011-04-20 17:09:23 +020012681 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012682 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012683 if (PyTuple_Check(subobj)) {
12684 Py_ssize_t i;
12685 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012686 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012687 if (substring == NULL)
12688 return NULL;
12689 result = tailmatch(self, substring, start, end, -1);
12690 Py_DECREF(substring);
12691 if (result) {
12692 Py_RETURN_TRUE;
12693 }
12694 }
12695 /* nothing matched */
12696 Py_RETURN_FALSE;
12697 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012698 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012699 if (substring == NULL) {
12700 if (PyErr_ExceptionMatches(PyExc_TypeError))
12701 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12702 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012703 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012704 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012705 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012706 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012707 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012708}
12709
12710
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012711PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012712 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012713\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012714Return True if S ends with the specified suffix, False otherwise.\n\
12715With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012716With optional end, stop comparing S at that position.\n\
12717suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012718
12719static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012720unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012721 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012722{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012723 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012724 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012725 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012726 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012727 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012728
Jesus Ceaac451502011-04-20 17:09:23 +020012729 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012730 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012731 if (PyTuple_Check(subobj)) {
12732 Py_ssize_t i;
12733 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012734 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012735 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012736 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012737 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012738 result = tailmatch(self, substring, start, end, +1);
12739 Py_DECREF(substring);
12740 if (result) {
12741 Py_RETURN_TRUE;
12742 }
12743 }
12744 Py_RETURN_FALSE;
12745 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012746 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012747 if (substring == NULL) {
12748 if (PyErr_ExceptionMatches(PyExc_TypeError))
12749 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12750 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012751 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012752 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012753 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012754 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012755 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012756}
12757
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012758#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012759
12760PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012761 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012762\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012763Return a formatted version of S, using substitutions from args and kwargs.\n\
12764The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012765
Eric Smith27bbca62010-11-04 17:06:58 +000012766PyDoc_STRVAR(format_map__doc__,
12767 "S.format_map(mapping) -> str\n\
12768\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012769Return a formatted version of S, using substitutions from mapping.\n\
12770The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012771
Eric Smith4a7d76d2008-05-30 18:10:19 +000012772static PyObject *
12773unicode__format__(PyObject* self, PyObject* args)
12774{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012775 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012776
12777 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12778 return NULL;
12779
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012780 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012781 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012782 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012783}
12784
Eric Smith8c663262007-08-25 02:26:07 +000012785PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012786 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012787\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012788Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012789
12790static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012791unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012792{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012793 Py_ssize_t size;
12794
12795 /* If it's a compact object, account for base structure +
12796 character data. */
12797 if (PyUnicode_IS_COMPACT_ASCII(v))
12798 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12799 else if (PyUnicode_IS_COMPACT(v))
12800 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012801 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012802 else {
12803 /* If it is a two-block object, account for base object, and
12804 for character block if present. */
12805 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012806 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012807 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012808 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012809 }
12810 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012811 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012812 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012813 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012814 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012815 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012816
12817 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012818}
12819
12820PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012821 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012822
12823static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012824unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012825{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012826 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012827 if (!copy)
12828 return NULL;
12829 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012830}
12831
Guido van Rossumd57fd912000-03-10 22:53:23 +000012832static PyMethodDef unicode_methods[] = {
12833
12834 /* Order is according to common usage: often used methods should
12835 appear first, since lookup is done sequentially. */
12836
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012837 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012838 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12839 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012840 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012841 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12842 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12843 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12844 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12845 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12846 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12847 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012848 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012849 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12850 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12851 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012852 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012853 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12854 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12855 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012856 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012857 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012858 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012859 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012860 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12861 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12862 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12863 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12864 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12865 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12866 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12867 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12868 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12869 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12870 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12871 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12872 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12873 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012874 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012875 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012876 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012877 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012878 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012879 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012880 {"maketrans", (PyCFunction) unicode_maketrans,
12881 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012882 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012883#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012884 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012885#endif
12886
12887#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012888 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012889 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012890#endif
12891
Benjamin Peterson14339b62009-01-31 16:36:08 +000012892 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012893 {NULL, NULL}
12894};
12895
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012896static PyObject *
12897unicode_mod(PyObject *v, PyObject *w)
12898{
Brian Curtindfc80e32011-08-10 20:28:54 -050012899 if (!PyUnicode_Check(v))
12900 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012901 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012902}
12903
12904static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012905 0, /*nb_add*/
12906 0, /*nb_subtract*/
12907 0, /*nb_multiply*/
12908 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012909};
12910
Guido van Rossumd57fd912000-03-10 22:53:23 +000012911static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012912 (lenfunc) unicode_length, /* sq_length */
12913 PyUnicode_Concat, /* sq_concat */
12914 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12915 (ssizeargfunc) unicode_getitem, /* sq_item */
12916 0, /* sq_slice */
12917 0, /* sq_ass_item */
12918 0, /* sq_ass_slice */
12919 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012920};
12921
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012922static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012923unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012924{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012925 if (PyUnicode_READY(self) == -1)
12926 return NULL;
12927
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012928 if (PyIndex_Check(item)) {
12929 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012930 if (i == -1 && PyErr_Occurred())
12931 return NULL;
12932 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012933 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012934 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012935 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000012936 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012937 PyObject *result;
12938 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012939 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012940 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012941
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012942 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000012943 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012944 return NULL;
12945 }
12946
12947 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012948 return PyUnicode_New(0, 0);
12949 } else if (start == 0 && step == 1 &&
12950 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000012951 PyUnicode_CheckExact(self)) {
12952 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012953 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000012954 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012955 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020012956 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012957 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012958 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012959 src_kind = PyUnicode_KIND(self);
12960 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020012961 if (!PyUnicode_IS_ASCII(self)) {
12962 kind_limit = kind_maxchar_limit(src_kind);
12963 max_char = 0;
12964 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
12965 ch = PyUnicode_READ(src_kind, src_data, cur);
12966 if (ch > max_char) {
12967 max_char = ch;
12968 if (max_char >= kind_limit)
12969 break;
12970 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012971 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012972 }
Victor Stinner55c99112011-10-13 01:17:06 +020012973 else
12974 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012975 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012976 if (result == NULL)
12977 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012978 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012979 dest_data = PyUnicode_DATA(result);
12980
12981 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012982 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
12983 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012984 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012985 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012986 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012987 } else {
12988 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
12989 return NULL;
12990 }
12991}
12992
12993static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012994 (lenfunc)unicode_length, /* mp_length */
12995 (binaryfunc)unicode_subscript, /* mp_subscript */
12996 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012997};
12998
Guido van Rossumd57fd912000-03-10 22:53:23 +000012999
Guido van Rossumd57fd912000-03-10 22:53:23 +000013000/* Helpers for PyUnicode_Format() */
13001
13002static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013003getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013004{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013005 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013006 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013007 (*p_argidx)++;
13008 if (arglen < 0)
13009 return args;
13010 else
13011 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013012 }
13013 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013014 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013015 return NULL;
13016}
13017
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013018/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013019
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013020static PyObject *
13021formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013022{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013023 char *p;
13024 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013025 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013026
Guido van Rossumd57fd912000-03-10 22:53:23 +000013027 x = PyFloat_AsDouble(v);
13028 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013029 return NULL;
13030
Guido van Rossumd57fd912000-03-10 22:53:23 +000013031 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013032 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013033
Eric Smith0923d1d2009-04-16 20:16:10 +000013034 p = PyOS_double_to_string(x, type, prec,
13035 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013036 if (p == NULL)
13037 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013038 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013039 PyMem_Free(p);
13040 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013041}
13042
Tim Peters38fd5b62000-09-21 05:43:11 +000013043static PyObject*
13044formatlong(PyObject *val, int flags, int prec, int type)
13045{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013046 char *buf;
13047 int len;
13048 PyObject *str; /* temporary string object. */
13049 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013050
Benjamin Peterson14339b62009-01-31 16:36:08 +000013051 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13052 if (!str)
13053 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013054 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013055 Py_DECREF(str);
13056 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013057}
13058
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013059static Py_UCS4
13060formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013061{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013062 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013063 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013064 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013065 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013066 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013067 goto onError;
13068 }
13069 else {
13070 /* Integer input truncated to a character */
13071 long x;
13072 x = PyLong_AsLong(v);
13073 if (x == -1 && PyErr_Occurred())
13074 goto onError;
13075
13076 if (x < 0 || x > 0x10ffff) {
13077 PyErr_SetString(PyExc_OverflowError,
13078 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013079 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013080 }
13081
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013082 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013083 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013084
Benjamin Peterson29060642009-01-31 22:14:21 +000013085 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013086 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013087 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013088 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013089}
13090
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013091static int
13092repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13093{
13094 int r;
13095 assert(count > 0);
13096 assert(PyUnicode_Check(obj));
13097 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013098 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013099 if (repeated == NULL)
13100 return -1;
13101 r = _PyAccu_Accumulate(acc, repeated);
13102 Py_DECREF(repeated);
13103 return r;
13104 }
13105 else {
13106 do {
13107 if (_PyAccu_Accumulate(acc, obj))
13108 return -1;
13109 } while (--count);
13110 return 0;
13111 }
13112}
13113
Alexander Belopolsky40018472011-02-26 01:02:56 +000013114PyObject *
13115PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013116{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013117 void *fmt;
13118 int fmtkind;
13119 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013120 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013121 int r;
13122 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013123 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013124 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013125 PyObject *temp = NULL;
13126 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013127 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013128 _PyAccu acc;
13129 static PyObject *plus, *minus, *blank, *zero, *percent;
13130
13131 if (!plus && !(plus = get_latin1_char('+')))
13132 return NULL;
13133 if (!minus && !(minus = get_latin1_char('-')))
13134 return NULL;
13135 if (!blank && !(blank = get_latin1_char(' ')))
13136 return NULL;
13137 if (!zero && !(zero = get_latin1_char('0')))
13138 return NULL;
13139 if (!percent && !(percent = get_latin1_char('%')))
13140 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013141
Guido van Rossumd57fd912000-03-10 22:53:23 +000013142 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013143 PyErr_BadInternalCall();
13144 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013145 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013146 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013147 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013148 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013149 if (_PyAccu_Init(&acc))
13150 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013151 fmt = PyUnicode_DATA(uformat);
13152 fmtkind = PyUnicode_KIND(uformat);
13153 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13154 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013155
Guido van Rossumd57fd912000-03-10 22:53:23 +000013156 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013157 arglen = PyTuple_Size(args);
13158 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013159 }
13160 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013161 arglen = -1;
13162 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013163 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013164 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013165 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013166 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013167
13168 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013169 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013170 PyObject *nonfmt;
13171 Py_ssize_t nonfmtpos;
13172 nonfmtpos = fmtpos++;
13173 while (fmtcnt >= 0 &&
13174 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13175 fmtpos++;
13176 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013177 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013178 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013179 if (nonfmt == NULL)
13180 goto onError;
13181 r = _PyAccu_Accumulate(&acc, nonfmt);
13182 Py_DECREF(nonfmt);
13183 if (r)
13184 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013185 }
13186 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013187 /* Got a format specifier */
13188 int flags = 0;
13189 Py_ssize_t width = -1;
13190 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013191 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013192 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013193 int isnumok;
13194 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013195 void *pbuf = NULL;
13196 Py_ssize_t pindex, len;
13197 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013198
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013199 fmtpos++;
13200 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13201 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013202 Py_ssize_t keylen;
13203 PyObject *key;
13204 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013205
Benjamin Peterson29060642009-01-31 22:14:21 +000013206 if (dict == NULL) {
13207 PyErr_SetString(PyExc_TypeError,
13208 "format requires a mapping");
13209 goto onError;
13210 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013211 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013212 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013213 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013214 /* Skip over balanced parentheses */
13215 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013216 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013217 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013218 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013219 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013220 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013221 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013222 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013223 if (fmtcnt < 0 || pcount > 0) {
13224 PyErr_SetString(PyExc_ValueError,
13225 "incomplete format key");
13226 goto onError;
13227 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013228 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013229 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013230 if (key == NULL)
13231 goto onError;
13232 if (args_owned) {
13233 Py_DECREF(args);
13234 args_owned = 0;
13235 }
13236 args = PyObject_GetItem(dict, key);
13237 Py_DECREF(key);
13238 if (args == NULL) {
13239 goto onError;
13240 }
13241 args_owned = 1;
13242 arglen = -1;
13243 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013244 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013245 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013246 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013247 case '-': flags |= F_LJUST; continue;
13248 case '+': flags |= F_SIGN; continue;
13249 case ' ': flags |= F_BLANK; continue;
13250 case '#': flags |= F_ALT; continue;
13251 case '0': flags |= F_ZERO; continue;
13252 }
13253 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013254 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013255 if (c == '*') {
13256 v = getnextarg(args, arglen, &argidx);
13257 if (v == NULL)
13258 goto onError;
13259 if (!PyLong_Check(v)) {
13260 PyErr_SetString(PyExc_TypeError,
13261 "* wants int");
13262 goto onError;
13263 }
13264 width = PyLong_AsLong(v);
13265 if (width == -1 && PyErr_Occurred())
13266 goto onError;
13267 if (width < 0) {
13268 flags |= F_LJUST;
13269 width = -width;
13270 }
13271 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013272 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013273 }
13274 else if (c >= '0' && c <= '9') {
13275 width = c - '0';
13276 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013277 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013278 if (c < '0' || c > '9')
13279 break;
13280 if ((width*10) / 10 != width) {
13281 PyErr_SetString(PyExc_ValueError,
13282 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013283 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013284 }
13285 width = width*10 + (c - '0');
13286 }
13287 }
13288 if (c == '.') {
13289 prec = 0;
13290 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013291 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013292 if (c == '*') {
13293 v = getnextarg(args, arglen, &argidx);
13294 if (v == NULL)
13295 goto onError;
13296 if (!PyLong_Check(v)) {
13297 PyErr_SetString(PyExc_TypeError,
13298 "* wants int");
13299 goto onError;
13300 }
13301 prec = PyLong_AsLong(v);
13302 if (prec == -1 && PyErr_Occurred())
13303 goto onError;
13304 if (prec < 0)
13305 prec = 0;
13306 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013307 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013308 }
13309 else if (c >= '0' && c <= '9') {
13310 prec = c - '0';
13311 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013312 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013313 if (c < '0' || c > '9')
13314 break;
13315 if ((prec*10) / 10 != prec) {
13316 PyErr_SetString(PyExc_ValueError,
13317 "prec too big");
13318 goto onError;
13319 }
13320 prec = prec*10 + (c - '0');
13321 }
13322 }
13323 } /* prec */
13324 if (fmtcnt >= 0) {
13325 if (c == 'h' || c == 'l' || c == 'L') {
13326 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013327 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013328 }
13329 }
13330 if (fmtcnt < 0) {
13331 PyErr_SetString(PyExc_ValueError,
13332 "incomplete format");
13333 goto onError;
13334 }
13335 if (c != '%') {
13336 v = getnextarg(args, arglen, &argidx);
13337 if (v == NULL)
13338 goto onError;
13339 }
13340 sign = 0;
13341 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013342 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013343 switch (c) {
13344
13345 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013346 _PyAccu_Accumulate(&acc, percent);
13347 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013348
13349 case 's':
13350 case 'r':
13351 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013352 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013353 temp = v;
13354 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013355 }
13356 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013357 if (c == 's')
13358 temp = PyObject_Str(v);
13359 else if (c == 'r')
13360 temp = PyObject_Repr(v);
13361 else
13362 temp = PyObject_ASCII(v);
13363 if (temp == NULL)
13364 goto onError;
13365 if (PyUnicode_Check(temp))
13366 /* nothing to do */;
13367 else {
13368 Py_DECREF(temp);
13369 PyErr_SetString(PyExc_TypeError,
13370 "%s argument has non-string str()");
13371 goto onError;
13372 }
13373 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013374 if (PyUnicode_READY(temp) == -1) {
13375 Py_CLEAR(temp);
13376 goto onError;
13377 }
13378 pbuf = PyUnicode_DATA(temp);
13379 kind = PyUnicode_KIND(temp);
13380 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013381 if (prec >= 0 && len > prec)
13382 len = prec;
13383 break;
13384
13385 case 'i':
13386 case 'd':
13387 case 'u':
13388 case 'o':
13389 case 'x':
13390 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013391 isnumok = 0;
13392 if (PyNumber_Check(v)) {
13393 PyObject *iobj=NULL;
13394
13395 if (PyLong_Check(v)) {
13396 iobj = v;
13397 Py_INCREF(iobj);
13398 }
13399 else {
13400 iobj = PyNumber_Long(v);
13401 }
13402 if (iobj!=NULL) {
13403 if (PyLong_Check(iobj)) {
13404 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013405 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013406 Py_DECREF(iobj);
13407 if (!temp)
13408 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013409 if (PyUnicode_READY(temp) == -1) {
13410 Py_CLEAR(temp);
13411 goto onError;
13412 }
13413 pbuf = PyUnicode_DATA(temp);
13414 kind = PyUnicode_KIND(temp);
13415 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013416 sign = 1;
13417 }
13418 else {
13419 Py_DECREF(iobj);
13420 }
13421 }
13422 }
13423 if (!isnumok) {
13424 PyErr_Format(PyExc_TypeError,
13425 "%%%c format: a number is required, "
13426 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13427 goto onError;
13428 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013429 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013430 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013431 fillobj = zero;
13432 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013433 break;
13434
13435 case 'e':
13436 case 'E':
13437 case 'f':
13438 case 'F':
13439 case 'g':
13440 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013441 temp = formatfloat(v, flags, prec, c);
13442 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013443 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013444 if (PyUnicode_READY(temp) == -1) {
13445 Py_CLEAR(temp);
13446 goto onError;
13447 }
13448 pbuf = PyUnicode_DATA(temp);
13449 kind = PyUnicode_KIND(temp);
13450 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013451 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013452 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013453 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013454 fillobj = zero;
13455 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013456 break;
13457
13458 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013459 {
13460 Py_UCS4 ch = formatchar(v);
13461 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013462 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013463 temp = _PyUnicode_FromUCS4(&ch, 1);
13464 if (temp == NULL)
13465 goto onError;
13466 pbuf = PyUnicode_DATA(temp);
13467 kind = PyUnicode_KIND(temp);
13468 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013469 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013470 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013471
13472 default:
13473 PyErr_Format(PyExc_ValueError,
13474 "unsupported format character '%c' (0x%x) "
13475 "at index %zd",
13476 (31<=c && c<=126) ? (char)c : '?',
13477 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013478 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013479 goto onError;
13480 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013481 /* pbuf is initialized here. */
13482 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013483 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013484 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13485 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013486 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013487 pindex++;
13488 }
13489 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13490 signobj = plus;
13491 len--;
13492 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013493 }
13494 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013495 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013496 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013497 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013498 else
13499 sign = 0;
13500 }
13501 if (width < len)
13502 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013503 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013504 if (fill != ' ') {
13505 assert(signobj != NULL);
13506 if (_PyAccu_Accumulate(&acc, signobj))
13507 goto onError;
13508 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013509 if (width > len)
13510 width--;
13511 }
13512 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013513 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013514 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013515 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013516 second = get_latin1_char(
13517 PyUnicode_READ(kind, pbuf, pindex + 1));
13518 pindex += 2;
13519 if (second == NULL ||
13520 _PyAccu_Accumulate(&acc, zero) ||
13521 _PyAccu_Accumulate(&acc, second))
13522 goto onError;
13523 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013524 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013525 width -= 2;
13526 if (width < 0)
13527 width = 0;
13528 len -= 2;
13529 }
13530 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013531 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013532 if (repeat_accumulate(&acc, fillobj, width - len))
13533 goto onError;
13534 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013535 }
13536 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013537 if (sign) {
13538 assert(signobj != NULL);
13539 if (_PyAccu_Accumulate(&acc, signobj))
13540 goto onError;
13541 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013542 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013543 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13544 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013545 second = get_latin1_char(
13546 PyUnicode_READ(kind, pbuf, pindex + 1));
13547 pindex += 2;
13548 if (second == NULL ||
13549 _PyAccu_Accumulate(&acc, zero) ||
13550 _PyAccu_Accumulate(&acc, second))
13551 goto onError;
13552 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013553 }
13554 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013555 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013556 if (temp != NULL) {
13557 assert(pbuf == PyUnicode_DATA(temp));
13558 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013559 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013560 else {
13561 const char *p = (const char *) pbuf;
13562 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013563 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013564 v = PyUnicode_FromKindAndData(kind, p, len);
13565 }
13566 if (v == NULL)
13567 goto onError;
13568 r = _PyAccu_Accumulate(&acc, v);
13569 Py_DECREF(v);
13570 if (r)
13571 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013572 if (width > len && repeat_accumulate(&acc, blank, width - len))
13573 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013574 if (dict && (argidx < arglen) && c != '%') {
13575 PyErr_SetString(PyExc_TypeError,
13576 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013577 goto onError;
13578 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013579 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013580 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013581 } /* until end */
13582 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013583 PyErr_SetString(PyExc_TypeError,
13584 "not all arguments converted during string formatting");
13585 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013586 }
13587
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013588 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013589 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013590 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013591 }
13592 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013593 Py_XDECREF(temp);
13594 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013595 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013596
Benjamin Peterson29060642009-01-31 22:14:21 +000013597 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013598 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013599 Py_XDECREF(temp);
13600 Py_XDECREF(second);
13601 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013602 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013603 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013604 }
13605 return NULL;
13606}
13607
Jeremy Hylton938ace62002-07-17 16:30:39 +000013608static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013609unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13610
Tim Peters6d6c1a32001-08-02 04:15:00 +000013611static PyObject *
13612unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13613{
Benjamin Peterson29060642009-01-31 22:14:21 +000013614 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013615 static char *kwlist[] = {"object", "encoding", "errors", 0};
13616 char *encoding = NULL;
13617 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013618
Benjamin Peterson14339b62009-01-31 16:36:08 +000013619 if (type != &PyUnicode_Type)
13620 return unicode_subtype_new(type, args, kwds);
13621 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013622 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013623 return NULL;
13624 if (x == NULL)
Victor Stinner7931d9a2011-11-04 00:22:48 +010013625 return PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013626 if (encoding == NULL && errors == NULL)
13627 return PyObject_Str(x);
13628 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013629 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013630}
13631
Guido van Rossume023fe02001-08-30 03:12:59 +000013632static PyObject *
13633unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13634{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013635 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013636 Py_ssize_t length, char_size;
13637 int share_wstr, share_utf8;
13638 unsigned int kind;
13639 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013640
Benjamin Peterson14339b62009-01-31 16:36:08 +000013641 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013642
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013643 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013644 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013645 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013646 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013647 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013648 return NULL;
13649
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013650 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013651 if (self == NULL) {
13652 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013653 return NULL;
13654 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013655 kind = PyUnicode_KIND(unicode);
13656 length = PyUnicode_GET_LENGTH(unicode);
13657
13658 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013659#ifdef Py_DEBUG
13660 _PyUnicode_HASH(self) = -1;
13661#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013662 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013663#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013664 _PyUnicode_STATE(self).interned = 0;
13665 _PyUnicode_STATE(self).kind = kind;
13666 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013667 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013668 _PyUnicode_STATE(self).ready = 1;
13669 _PyUnicode_WSTR(self) = NULL;
13670 _PyUnicode_UTF8_LENGTH(self) = 0;
13671 _PyUnicode_UTF8(self) = NULL;
13672 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013673 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013674
13675 share_utf8 = 0;
13676 share_wstr = 0;
13677 if (kind == PyUnicode_1BYTE_KIND) {
13678 char_size = 1;
13679 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13680 share_utf8 = 1;
13681 }
13682 else if (kind == PyUnicode_2BYTE_KIND) {
13683 char_size = 2;
13684 if (sizeof(wchar_t) == 2)
13685 share_wstr = 1;
13686 }
13687 else {
13688 assert(kind == PyUnicode_4BYTE_KIND);
13689 char_size = 4;
13690 if (sizeof(wchar_t) == 4)
13691 share_wstr = 1;
13692 }
13693
13694 /* Ensure we won't overflow the length. */
13695 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13696 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013697 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013698 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013699 data = PyObject_MALLOC((length + 1) * char_size);
13700 if (data == NULL) {
13701 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013702 goto onError;
13703 }
13704
Victor Stinnerc3c74152011-10-02 20:39:55 +020013705 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013706 if (share_utf8) {
13707 _PyUnicode_UTF8_LENGTH(self) = length;
13708 _PyUnicode_UTF8(self) = data;
13709 }
13710 if (share_wstr) {
13711 _PyUnicode_WSTR_LENGTH(self) = length;
13712 _PyUnicode_WSTR(self) = (wchar_t *)data;
13713 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013714
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013715 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013716 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013717 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013718#ifdef Py_DEBUG
13719 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13720#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013721 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013722 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013723
13724onError:
13725 Py_DECREF(unicode);
13726 Py_DECREF(self);
13727 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013728}
13729
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013730PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013731 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013732\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013733Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013734encoding defaults to the current default string encoding.\n\
13735errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013736
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013737static PyObject *unicode_iter(PyObject *seq);
13738
Guido van Rossumd57fd912000-03-10 22:53:23 +000013739PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013740 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013741 "str", /* tp_name */
13742 sizeof(PyUnicodeObject), /* tp_size */
13743 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013744 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013745 (destructor)unicode_dealloc, /* tp_dealloc */
13746 0, /* tp_print */
13747 0, /* tp_getattr */
13748 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013749 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013750 unicode_repr, /* tp_repr */
13751 &unicode_as_number, /* tp_as_number */
13752 &unicode_as_sequence, /* tp_as_sequence */
13753 &unicode_as_mapping, /* tp_as_mapping */
13754 (hashfunc) unicode_hash, /* tp_hash*/
13755 0, /* tp_call*/
13756 (reprfunc) unicode_str, /* tp_str */
13757 PyObject_GenericGetAttr, /* tp_getattro */
13758 0, /* tp_setattro */
13759 0, /* tp_as_buffer */
13760 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013761 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013762 unicode_doc, /* tp_doc */
13763 0, /* tp_traverse */
13764 0, /* tp_clear */
13765 PyUnicode_RichCompare, /* tp_richcompare */
13766 0, /* tp_weaklistoffset */
13767 unicode_iter, /* tp_iter */
13768 0, /* tp_iternext */
13769 unicode_methods, /* tp_methods */
13770 0, /* tp_members */
13771 0, /* tp_getset */
13772 &PyBaseObject_Type, /* tp_base */
13773 0, /* tp_dict */
13774 0, /* tp_descr_get */
13775 0, /* tp_descr_set */
13776 0, /* tp_dictoffset */
13777 0, /* tp_init */
13778 0, /* tp_alloc */
13779 unicode_new, /* tp_new */
13780 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013781};
13782
13783/* Initialize the Unicode implementation */
13784
Victor Stinner3a50e702011-10-18 21:21:00 +020013785int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013786{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013787 int i;
13788
Thomas Wouters477c8d52006-05-27 19:21:47 +000013789 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013790 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013791 0x000A, /* LINE FEED */
13792 0x000D, /* CARRIAGE RETURN */
13793 0x001C, /* FILE SEPARATOR */
13794 0x001D, /* GROUP SEPARATOR */
13795 0x001E, /* RECORD SEPARATOR */
13796 0x0085, /* NEXT LINE */
13797 0x2028, /* LINE SEPARATOR */
13798 0x2029, /* PARAGRAPH SEPARATOR */
13799 };
13800
Fred Drakee4315f52000-05-09 19:53:39 +000013801 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013802 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013803 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013804 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013805 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013806
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013807 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013808 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013809 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013810 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013811
13812 /* initialize the linebreak bloom filter */
13813 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013814 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013815 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013816
13817 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013818
13819#ifdef HAVE_MBCS
13820 winver.dwOSVersionInfoSize = sizeof(winver);
13821 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13822 PyErr_SetFromWindowsErr(0);
13823 return -1;
13824 }
13825#endif
13826 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013827}
13828
13829/* Finalize the Unicode implementation */
13830
Christian Heimesa156e092008-02-16 07:38:31 +000013831int
13832PyUnicode_ClearFreeList(void)
13833{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013834 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013835}
13836
Guido van Rossumd57fd912000-03-10 22:53:23 +000013837void
Thomas Wouters78890102000-07-22 19:25:51 +000013838_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013839{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013840 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013841
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013842 Py_XDECREF(unicode_empty);
13843 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013844
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013845 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013846 if (unicode_latin1[i]) {
13847 Py_DECREF(unicode_latin1[i]);
13848 unicode_latin1[i] = NULL;
13849 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013850 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013851 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013852 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013853}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013854
Walter Dörwald16807132007-05-25 13:52:07 +000013855void
13856PyUnicode_InternInPlace(PyObject **p)
13857{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013858 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013859 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013860#ifdef Py_DEBUG
13861 assert(s != NULL);
13862 assert(_PyUnicode_CHECK(s));
13863#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013864 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013865 return;
13866#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013867 /* If it's a subclass, we don't really know what putting
13868 it in the interned dict might do. */
13869 if (!PyUnicode_CheckExact(s))
13870 return;
13871 if (PyUnicode_CHECK_INTERNED(s))
13872 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013873 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013874 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013875 return;
13876 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013877 s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013878 if (interned == NULL) {
13879 interned = PyDict_New();
13880 if (interned == NULL) {
13881 PyErr_Clear(); /* Don't leave an exception */
13882 return;
13883 }
13884 }
13885 /* It might be that the GetItem call fails even
13886 though the key is present in the dictionary,
13887 namely when this happens during a stack overflow. */
13888 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010013889 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013890 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013891
Benjamin Peterson29060642009-01-31 22:14:21 +000013892 if (t) {
13893 Py_INCREF(t);
13894 Py_DECREF(*p);
13895 *p = t;
13896 return;
13897 }
Walter Dörwald16807132007-05-25 13:52:07 +000013898
Benjamin Peterson14339b62009-01-31 16:36:08 +000013899 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010013900 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013901 PyErr_Clear();
13902 PyThreadState_GET()->recursion_critical = 0;
13903 return;
13904 }
13905 PyThreadState_GET()->recursion_critical = 0;
13906 /* The two references in interned are not counted by refcnt.
13907 The deallocator will take care of this */
13908 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013909 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013910}
13911
13912void
13913PyUnicode_InternImmortal(PyObject **p)
13914{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013915 PyUnicode_InternInPlace(p);
13916 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020013917 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013918 Py_INCREF(*p);
13919 }
Walter Dörwald16807132007-05-25 13:52:07 +000013920}
13921
13922PyObject *
13923PyUnicode_InternFromString(const char *cp)
13924{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013925 PyObject *s = PyUnicode_FromString(cp);
13926 if (s == NULL)
13927 return NULL;
13928 PyUnicode_InternInPlace(&s);
13929 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000013930}
13931
Alexander Belopolsky40018472011-02-26 01:02:56 +000013932void
13933_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000013934{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013935 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013936 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013937 Py_ssize_t i, n;
13938 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000013939
Benjamin Peterson14339b62009-01-31 16:36:08 +000013940 if (interned == NULL || !PyDict_Check(interned))
13941 return;
13942 keys = PyDict_Keys(interned);
13943 if (keys == NULL || !PyList_Check(keys)) {
13944 PyErr_Clear();
13945 return;
13946 }
Walter Dörwald16807132007-05-25 13:52:07 +000013947
Benjamin Peterson14339b62009-01-31 16:36:08 +000013948 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
13949 detector, interned unicode strings are not forcibly deallocated;
13950 rather, we give them their stolen references back, and then clear
13951 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000013952
Benjamin Peterson14339b62009-01-31 16:36:08 +000013953 n = PyList_GET_SIZE(keys);
13954 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000013955 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013956 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013957 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013958 if (PyUnicode_READY(s) == -1) {
13959 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013960 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013961 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013962 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013963 case SSTATE_NOT_INTERNED:
13964 /* XXX Shouldn't happen */
13965 break;
13966 case SSTATE_INTERNED_IMMORTAL:
13967 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013968 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013969 break;
13970 case SSTATE_INTERNED_MORTAL:
13971 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013972 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013973 break;
13974 default:
13975 Py_FatalError("Inconsistent interned string state.");
13976 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013977 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013978 }
13979 fprintf(stderr, "total size of all interned strings: "
13980 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
13981 "mortal/immortal\n", mortal_size, immortal_size);
13982 Py_DECREF(keys);
13983 PyDict_Clear(interned);
13984 Py_DECREF(interned);
13985 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000013986}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013987
13988
13989/********************* Unicode Iterator **************************/
13990
13991typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013992 PyObject_HEAD
13993 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013994 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013995} unicodeiterobject;
13996
13997static void
13998unicodeiter_dealloc(unicodeiterobject *it)
13999{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014000 _PyObject_GC_UNTRACK(it);
14001 Py_XDECREF(it->it_seq);
14002 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014003}
14004
14005static int
14006unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14007{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014008 Py_VISIT(it->it_seq);
14009 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014010}
14011
14012static PyObject *
14013unicodeiter_next(unicodeiterobject *it)
14014{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014015 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014016
Benjamin Peterson14339b62009-01-31 16:36:08 +000014017 assert(it != NULL);
14018 seq = it->it_seq;
14019 if (seq == NULL)
14020 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014021 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014022
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014023 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14024 int kind = PyUnicode_KIND(seq);
14025 void *data = PyUnicode_DATA(seq);
14026 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14027 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014028 if (item != NULL)
14029 ++it->it_index;
14030 return item;
14031 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014032
Benjamin Peterson14339b62009-01-31 16:36:08 +000014033 Py_DECREF(seq);
14034 it->it_seq = NULL;
14035 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014036}
14037
14038static PyObject *
14039unicodeiter_len(unicodeiterobject *it)
14040{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014041 Py_ssize_t len = 0;
14042 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014043 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014044 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014045}
14046
14047PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14048
14049static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014050 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014051 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014052 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014053};
14054
14055PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014056 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14057 "str_iterator", /* tp_name */
14058 sizeof(unicodeiterobject), /* tp_basicsize */
14059 0, /* tp_itemsize */
14060 /* methods */
14061 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14062 0, /* tp_print */
14063 0, /* tp_getattr */
14064 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014065 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014066 0, /* tp_repr */
14067 0, /* tp_as_number */
14068 0, /* tp_as_sequence */
14069 0, /* tp_as_mapping */
14070 0, /* tp_hash */
14071 0, /* tp_call */
14072 0, /* tp_str */
14073 PyObject_GenericGetAttr, /* tp_getattro */
14074 0, /* tp_setattro */
14075 0, /* tp_as_buffer */
14076 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14077 0, /* tp_doc */
14078 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14079 0, /* tp_clear */
14080 0, /* tp_richcompare */
14081 0, /* tp_weaklistoffset */
14082 PyObject_SelfIter, /* tp_iter */
14083 (iternextfunc)unicodeiter_next, /* tp_iternext */
14084 unicodeiter_methods, /* tp_methods */
14085 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014086};
14087
14088static PyObject *
14089unicode_iter(PyObject *seq)
14090{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014091 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014092
Benjamin Peterson14339b62009-01-31 16:36:08 +000014093 if (!PyUnicode_Check(seq)) {
14094 PyErr_BadInternalCall();
14095 return NULL;
14096 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014097 if (PyUnicode_READY(seq) == -1)
14098 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014099 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14100 if (it == NULL)
14101 return NULL;
14102 it->it_index = 0;
14103 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014104 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014105 _PyObject_GC_TRACK(it);
14106 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014107}
14108
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014109
14110size_t
14111Py_UNICODE_strlen(const Py_UNICODE *u)
14112{
14113 int res = 0;
14114 while(*u++)
14115 res++;
14116 return res;
14117}
14118
14119Py_UNICODE*
14120Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14121{
14122 Py_UNICODE *u = s1;
14123 while ((*u++ = *s2++));
14124 return s1;
14125}
14126
14127Py_UNICODE*
14128Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14129{
14130 Py_UNICODE *u = s1;
14131 while ((*u++ = *s2++))
14132 if (n-- == 0)
14133 break;
14134 return s1;
14135}
14136
14137Py_UNICODE*
14138Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14139{
14140 Py_UNICODE *u1 = s1;
14141 u1 += Py_UNICODE_strlen(u1);
14142 Py_UNICODE_strcpy(u1, s2);
14143 return s1;
14144}
14145
14146int
14147Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14148{
14149 while (*s1 && *s2 && *s1 == *s2)
14150 s1++, s2++;
14151 if (*s1 && *s2)
14152 return (*s1 < *s2) ? -1 : +1;
14153 if (*s1)
14154 return 1;
14155 if (*s2)
14156 return -1;
14157 return 0;
14158}
14159
14160int
14161Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14162{
14163 register Py_UNICODE u1, u2;
14164 for (; n != 0; n--) {
14165 u1 = *s1;
14166 u2 = *s2;
14167 if (u1 != u2)
14168 return (u1 < u2) ? -1 : +1;
14169 if (u1 == '\0')
14170 return 0;
14171 s1++;
14172 s2++;
14173 }
14174 return 0;
14175}
14176
14177Py_UNICODE*
14178Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14179{
14180 const Py_UNICODE *p;
14181 for (p = s; *p; p++)
14182 if (*p == c)
14183 return (Py_UNICODE*)p;
14184 return NULL;
14185}
14186
14187Py_UNICODE*
14188Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14189{
14190 const Py_UNICODE *p;
14191 p = s + Py_UNICODE_strlen(s);
14192 while (p != s) {
14193 p--;
14194 if (*p == c)
14195 return (Py_UNICODE*)p;
14196 }
14197 return NULL;
14198}
Victor Stinner331ea922010-08-10 16:37:20 +000014199
Victor Stinner71133ff2010-09-01 23:43:53 +000014200Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014201PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014202{
Victor Stinner577db2c2011-10-11 22:12:48 +020014203 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014204 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014205
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014206 if (!PyUnicode_Check(unicode)) {
14207 PyErr_BadArgument();
14208 return NULL;
14209 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014210 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014211 if (u == NULL)
14212 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014213 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014214 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014215 PyErr_NoMemory();
14216 return NULL;
14217 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014218 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014219 size *= sizeof(Py_UNICODE);
14220 copy = PyMem_Malloc(size);
14221 if (copy == NULL) {
14222 PyErr_NoMemory();
14223 return NULL;
14224 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014225 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014226 return copy;
14227}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014228
Georg Brandl66c221e2010-10-14 07:04:07 +000014229/* A _string module, to export formatter_parser and formatter_field_name_split
14230 to the string.Formatter class implemented in Python. */
14231
14232static PyMethodDef _string_methods[] = {
14233 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14234 METH_O, PyDoc_STR("split the argument as a field name")},
14235 {"formatter_parser", (PyCFunction) formatter_parser,
14236 METH_O, PyDoc_STR("parse the argument as a format string")},
14237 {NULL, NULL}
14238};
14239
14240static struct PyModuleDef _string_module = {
14241 PyModuleDef_HEAD_INIT,
14242 "_string",
14243 PyDoc_STR("string helper module"),
14244 0,
14245 _string_methods,
14246 NULL,
14247 NULL,
14248 NULL,
14249 NULL
14250};
14251
14252PyMODINIT_FUNC
14253PyInit__string(void)
14254{
14255 return PyModule_Create(&_string_module);
14256}
14257
14258
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014259#ifdef __cplusplus
14260}
14261#endif