blob: 61534b48d588763e98fa12bd9497184350b0046a [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000044
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000045#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000046#include <windows.h>
47#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000048
Victor Stinnerce5faf62011-10-05 00:42:43 +020049#ifdef Py_DEBUG
50# define DONT_MAKE_RESULT_READY
51#endif
52
Guido van Rossumd57fd912000-03-10 22:53:23 +000053/* Endianness switches; defaults to little endian */
54
55#ifdef WORDS_BIGENDIAN
56# define BYTEORDER_IS_BIG_ENDIAN
57#else
58# define BYTEORDER_IS_LITTLE_ENDIAN
59#endif
60
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000061/* --- Globals ------------------------------------------------------------
62
63 The globals are initialized by the _PyUnicode_Init() API and should
64 not be used before calling that API.
65
66*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000067
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000068
69#ifdef __cplusplus
70extern "C" {
71#endif
72
Victor Stinner910337b2011-10-03 03:20:16 +020073#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020074# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020075#else
76# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
77#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020078
Victor Stinnere90fe6a2011-10-01 16:48:13 +020079#define _PyUnicode_UTF8(op) \
80 (((PyCompactUnicodeObject*)(op))->utf8)
81#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020082 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020083 assert(PyUnicode_IS_READY(op)), \
84 PyUnicode_IS_COMPACT_ASCII(op) ? \
85 ((char*)((PyASCIIObject*)(op) + 1)) : \
86 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020087#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020088 (((PyCompactUnicodeObject*)(op))->utf8_length)
89#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020090 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020091 assert(PyUnicode_IS_READY(op)), \
92 PyUnicode_IS_COMPACT_ASCII(op) ? \
93 ((PyASCIIObject*)(op))->length : \
94 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020095#define _PyUnicode_WSTR(op) \
96 (((PyASCIIObject*)(op))->wstr)
97#define _PyUnicode_WSTR_LENGTH(op) \
98 (((PyCompactUnicodeObject*)(op))->wstr_length)
99#define _PyUnicode_LENGTH(op) \
100 (((PyASCIIObject *)(op))->length)
101#define _PyUnicode_STATE(op) \
102 (((PyASCIIObject *)(op))->state)
103#define _PyUnicode_HASH(op) \
104 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200105#define _PyUnicode_KIND(op) \
106 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200107 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200108#define _PyUnicode_GET_LENGTH(op) \
109 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200110 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200111#define _PyUnicode_DATA_ANY(op) \
112 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200113
Victor Stinner910337b2011-10-03 03:20:16 +0200114#undef PyUnicode_READY
115#define PyUnicode_READY(op) \
116 (assert(_PyUnicode_CHECK(op)), \
117 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200118 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100119 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200120
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200121#define _PyUnicode_READY_REPLACE(p_obj) \
122 (assert(_PyUnicode_CHECK(*p_obj)), \
123 (PyUnicode_IS_READY(*p_obj) ? \
124 0 : _PyUnicode_ReadyReplace((PyObject **)(p_obj))))
125
Victor Stinnerc379ead2011-10-03 12:52:27 +0200126#define _PyUnicode_SHARE_UTF8(op) \
127 (assert(_PyUnicode_CHECK(op)), \
128 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
129 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
130#define _PyUnicode_SHARE_WSTR(op) \
131 (assert(_PyUnicode_CHECK(op)), \
132 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
133
Victor Stinner829c0ad2011-10-03 01:08:02 +0200134/* true if the Unicode object has an allocated UTF-8 memory block
135 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200136#define _PyUnicode_HAS_UTF8_MEMORY(op) \
137 (assert(_PyUnicode_CHECK(op)), \
138 (!PyUnicode_IS_COMPACT_ASCII(op) \
139 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200140 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
141
Victor Stinner03490912011-10-03 23:45:12 +0200142/* true if the Unicode object has an allocated wstr memory block
143 (not shared with other data) */
144#define _PyUnicode_HAS_WSTR_MEMORY(op) \
145 (assert(_PyUnicode_CHECK(op)), \
146 (_PyUnicode_WSTR(op) && \
147 (!PyUnicode_IS_READY(op) || \
148 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
149
Victor Stinner910337b2011-10-03 03:20:16 +0200150/* Generic helper macro to convert characters of different types.
151 from_type and to_type have to be valid type names, begin and end
152 are pointers to the source characters which should be of type
153 "from_type *". to is a pointer of type "to_type *" and points to the
154 buffer where the result characters are written to. */
155#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
156 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200157 to_type *_to = (to_type *) to; \
158 const from_type *_iter = (begin); \
159 const from_type *_end = (end); \
160 Py_ssize_t n = (_end) - (_iter); \
161 const from_type *_unrolled_end = \
162 _iter + (n & ~ (Py_ssize_t) 3); \
163 while (_iter < (_unrolled_end)) { \
164 _to[0] = (to_type) _iter[0]; \
165 _to[1] = (to_type) _iter[1]; \
166 _to[2] = (to_type) _iter[2]; \
167 _to[3] = (to_type) _iter[3]; \
168 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200169 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_end)) \
171 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200172 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200173
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200174/* The Unicode string has been modified: reset the hash */
175#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
176
Walter Dörwald16807132007-05-25 13:52:07 +0000177/* This dictionary holds all interned unicode strings. Note that references
178 to strings in this dictionary are *not* counted in the string's ob_refcnt.
179 When the interned string reaches a refcnt of 0 the string deallocation
180 function will delete the reference from this dictionary.
181
182 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000183 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000184*/
185static PyObject *interned;
186
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000187/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200188static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000189
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200190/* List of static strings. */
191static _Py_Identifier *static_strings;
192
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000193/* Single character Unicode strings in the Latin-1 range are being
194 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200195static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000196
Christian Heimes190d79e2008-01-30 11:58:22 +0000197/* Fast detection of the most frequent whitespace characters */
198const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000199 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000200/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000201/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000202/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000203/* case 0x000C: * FORM FEED */
204/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000205 0, 1, 1, 1, 1, 1, 0, 0,
206 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000207/* case 0x001C: * FILE SEPARATOR */
208/* case 0x001D: * GROUP SEPARATOR */
209/* case 0x001E: * RECORD SEPARATOR */
210/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000211 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000213 1, 0, 0, 0, 0, 0, 0, 0,
214 0, 0, 0, 0, 0, 0, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000217
Benjamin Peterson14339b62009-01-31 16:36:08 +0000218 0, 0, 0, 0, 0, 0, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0,
220 0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0,
223 0, 0, 0, 0, 0, 0, 0, 0,
224 0, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000226};
227
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200228/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200229static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200230static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200231static void copy_characters(
232 PyObject *to, Py_ssize_t to_start,
233 PyObject *from, Py_ssize_t from_start,
234 Py_ssize_t how_many);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200235#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200236static int unicode_is_singleton(PyObject *unicode);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200237#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200238
Alexander Belopolsky40018472011-02-26 01:02:56 +0000239static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200240unicode_fromascii(const unsigned char *s, Py_ssize_t size);
241static PyObject *
242_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
243static PyObject *
244_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
245static PyObject *
246_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
247
248static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000249unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000250 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100251 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000252 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
253
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254static void
255raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300256 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100257 PyObject *unicode,
258 Py_ssize_t startpos, Py_ssize_t endpos,
259 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000260
Christian Heimes190d79e2008-01-30 11:58:22 +0000261/* Same for linebreaks */
262static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000263 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000264/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000265/* 0x000B, * LINE TABULATION */
266/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000267/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000268 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000269 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000270/* 0x001C, * FILE SEPARATOR */
271/* 0x001D, * GROUP SEPARATOR */
272/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 0, 0, 0, 0, 1, 1, 1, 0,
274 0, 0, 0, 0, 0, 0, 0, 0,
275 0, 0, 0, 0, 0, 0, 0, 0,
276 0, 0, 0, 0, 0, 0, 0, 0,
277 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000278
Benjamin Peterson14339b62009-01-31 16:36:08 +0000279 0, 0, 0, 0, 0, 0, 0, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
282 0, 0, 0, 0, 0, 0, 0, 0,
283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000287};
288
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300289/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
290 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000291Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000292PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000293{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000294#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000295 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000296#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000297 /* This is actually an illegal character, so it should
298 not be passed to unichr. */
299 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000300#endif
301}
302
Victor Stinner910337b2011-10-03 03:20:16 +0200303#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200304int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100305_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200306{
307 PyASCIIObject *ascii;
308 unsigned int kind;
309
310 assert(PyUnicode_Check(op));
311
312 ascii = (PyASCIIObject *)op;
313 kind = ascii->state.kind;
314
Victor Stinnera3b334d2011-10-03 13:53:37 +0200315 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200316 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200317 assert(ascii->state.ready == 1);
318 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200319 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200320 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200321 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200322
Victor Stinnera41463c2011-10-04 01:05:08 +0200323 if (ascii->state.compact == 1) {
324 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200325 assert(kind == PyUnicode_1BYTE_KIND
326 || kind == PyUnicode_2BYTE_KIND
327 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200328 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200329 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200330 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100331 }
332 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200333 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
334
335 data = unicode->data.any;
336 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100337 assert(ascii->length == 0);
338 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200339 assert(ascii->state.compact == 0);
340 assert(ascii->state.ascii == 0);
341 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100342 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200343 assert(ascii->wstr != NULL);
344 assert(data == NULL);
345 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200346 }
347 else {
348 assert(kind == PyUnicode_1BYTE_KIND
349 || kind == PyUnicode_2BYTE_KIND
350 || kind == PyUnicode_4BYTE_KIND);
351 assert(ascii->state.compact == 0);
352 assert(ascii->state.ready == 1);
353 assert(data != NULL);
354 if (ascii->state.ascii) {
355 assert (compact->utf8 == data);
356 assert (compact->utf8_length == ascii->length);
357 }
358 else
359 assert (compact->utf8 != data);
360 }
361 }
362 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200363 if (
364#if SIZEOF_WCHAR_T == 2
365 kind == PyUnicode_2BYTE_KIND
366#else
367 kind == PyUnicode_4BYTE_KIND
368#endif
369 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200370 {
371 assert(ascii->wstr == data);
372 assert(compact->wstr_length == ascii->length);
373 } else
374 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200375 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200376
377 if (compact->utf8 == NULL)
378 assert(compact->utf8_length == 0);
379 if (ascii->wstr == NULL)
380 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200381 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200382 /* check that the best kind is used */
383 if (check_content && kind != PyUnicode_WCHAR_KIND)
384 {
385 Py_ssize_t i;
386 Py_UCS4 maxchar = 0;
387 void *data = PyUnicode_DATA(ascii);
388 for (i=0; i < ascii->length; i++)
389 {
390 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
391 if (ch > maxchar)
392 maxchar = ch;
393 }
394 if (kind == PyUnicode_1BYTE_KIND) {
395 if (ascii->state.ascii == 0)
396 assert(maxchar >= 128);
397 else
398 assert(maxchar < 128);
399 }
400 else if (kind == PyUnicode_2BYTE_KIND)
401 assert(maxchar >= 0x100);
402 else
403 assert(maxchar >= 0x10000);
404 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100405 if (check_content && !unicode_is_singleton(op))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200406 assert(ascii->hash == -1);
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400407 return 1;
408}
Victor Stinner910337b2011-10-03 03:20:16 +0200409#endif
410
Victor Stinner3a50e702011-10-18 21:21:00 +0200411#ifdef HAVE_MBCS
412static OSVERSIONINFOEX winver;
413#endif
414
Thomas Wouters477c8d52006-05-27 19:21:47 +0000415/* --- Bloom Filters ----------------------------------------------------- */
416
417/* stuff to implement simple "bloom filters" for Unicode characters.
418 to keep things simple, we use a single bitmask, using the least 5
419 bits from each unicode characters as the bit index. */
420
421/* the linebreak mask is set up by Unicode_Init below */
422
Antoine Pitrouf068f942010-01-13 14:19:12 +0000423#if LONG_BIT >= 128
424#define BLOOM_WIDTH 128
425#elif LONG_BIT >= 64
426#define BLOOM_WIDTH 64
427#elif LONG_BIT >= 32
428#define BLOOM_WIDTH 32
429#else
430#error "LONG_BIT is smaller than 32"
431#endif
432
Thomas Wouters477c8d52006-05-27 19:21:47 +0000433#define BLOOM_MASK unsigned long
434
435static BLOOM_MASK bloom_linebreak;
436
Antoine Pitrouf068f942010-01-13 14:19:12 +0000437#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
438#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000439
Benjamin Peterson29060642009-01-31 22:14:21 +0000440#define BLOOM_LINEBREAK(ch) \
441 ((ch) < 128U ? ascii_linebreak[(ch)] : \
442 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000443
Alexander Belopolsky40018472011-02-26 01:02:56 +0000444Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200445make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000446{
447 /* calculate simple bloom-style bitmask for a given unicode string */
448
Antoine Pitrouf068f942010-01-13 14:19:12 +0000449 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000450 Py_ssize_t i;
451
452 mask = 0;
453 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200454 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000455
456 return mask;
457}
458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200459#define BLOOM_MEMBER(mask, chr, str) \
460 (BLOOM(mask, chr) \
461 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000462
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200463/* Compilation of templated routines */
464
465#include "stringlib/asciilib.h"
466#include "stringlib/fastsearch.h"
467#include "stringlib/partition.h"
468#include "stringlib/split.h"
469#include "stringlib/count.h"
470#include "stringlib/find.h"
471#include "stringlib/find_max_char.h"
472#include "stringlib/localeutil.h"
473#include "stringlib/undef.h"
474
475#include "stringlib/ucs1lib.h"
476#include "stringlib/fastsearch.h"
477#include "stringlib/partition.h"
478#include "stringlib/split.h"
479#include "stringlib/count.h"
480#include "stringlib/find.h"
481#include "stringlib/find_max_char.h"
482#include "stringlib/localeutil.h"
483#include "stringlib/undef.h"
484
485#include "stringlib/ucs2lib.h"
486#include "stringlib/fastsearch.h"
487#include "stringlib/partition.h"
488#include "stringlib/split.h"
489#include "stringlib/count.h"
490#include "stringlib/find.h"
491#include "stringlib/find_max_char.h"
492#include "stringlib/localeutil.h"
493#include "stringlib/undef.h"
494
495#include "stringlib/ucs4lib.h"
496#include "stringlib/fastsearch.h"
497#include "stringlib/partition.h"
498#include "stringlib/split.h"
499#include "stringlib/count.h"
500#include "stringlib/find.h"
501#include "stringlib/find_max_char.h"
502#include "stringlib/localeutil.h"
503#include "stringlib/undef.h"
504
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200505#include "stringlib/unicodedefs.h"
506#include "stringlib/fastsearch.h"
507#include "stringlib/count.h"
508#include "stringlib/find.h"
509
Guido van Rossumd57fd912000-03-10 22:53:23 +0000510/* --- Unicode Object ----------------------------------------------------- */
511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200512static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200513fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200514
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200515Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
516 Py_ssize_t size, Py_UCS4 ch,
517 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200518{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200519 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
520
521 switch (kind) {
522 case PyUnicode_1BYTE_KIND:
523 {
524 Py_UCS1 ch1 = (Py_UCS1) ch;
525 if (ch1 == ch)
526 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
527 else
528 return -1;
529 }
530 case PyUnicode_2BYTE_KIND:
531 {
532 Py_UCS2 ch2 = (Py_UCS2) ch;
533 if (ch2 == ch)
534 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
535 else
536 return -1;
537 }
538 case PyUnicode_4BYTE_KIND:
539 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
540 default:
541 assert(0);
542 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200543 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200544}
545
Victor Stinnerfe226c02011-10-03 03:52:20 +0200546static PyObject*
547resize_compact(PyObject *unicode, Py_ssize_t length)
548{
549 Py_ssize_t char_size;
550 Py_ssize_t struct_size;
551 Py_ssize_t new_size;
552 int share_wstr;
553
554 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200555 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200556 if (PyUnicode_IS_COMPACT_ASCII(unicode))
557 struct_size = sizeof(PyASCIIObject);
558 else
559 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200560 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200561
562 _Py_DEC_REFTOTAL;
563 _Py_ForgetReference(unicode);
564
565 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
566 PyErr_NoMemory();
567 return NULL;
568 }
569 new_size = (struct_size + (length + 1) * char_size);
570
571 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
572 if (unicode == NULL) {
573 PyObject_Del(unicode);
574 PyErr_NoMemory();
575 return NULL;
576 }
577 _Py_NewReference(unicode);
578 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200579 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200580 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200581 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
582 _PyUnicode_WSTR_LENGTH(unicode) = length;
583 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200584 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
585 length, 0);
586 return unicode;
587}
588
Alexander Belopolsky40018472011-02-26 01:02:56 +0000589static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200590resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000591{
Victor Stinner95663112011-10-04 01:03:50 +0200592 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200593 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200594 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000595
Victor Stinner95663112011-10-04 01:03:50 +0200596 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200597
598 if (PyUnicode_IS_READY(unicode)) {
599 Py_ssize_t char_size;
600 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200601 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200602 void *data;
603
604 data = _PyUnicode_DATA_ANY(unicode);
605 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200606 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200607 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
608 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200609 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
610 {
611 PyObject_DEL(_PyUnicode_UTF8(unicode));
612 _PyUnicode_UTF8(unicode) = NULL;
613 _PyUnicode_UTF8_LENGTH(unicode) = 0;
614 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200615
616 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
617 PyErr_NoMemory();
618 return -1;
619 }
620 new_size = (length + 1) * char_size;
621
622 data = (PyObject *)PyObject_REALLOC(data, new_size);
623 if (data == NULL) {
624 PyErr_NoMemory();
625 return -1;
626 }
627 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200628 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200629 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200630 _PyUnicode_WSTR_LENGTH(unicode) = length;
631 }
632 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200633 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200634 _PyUnicode_UTF8_LENGTH(unicode) = length;
635 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200636 _PyUnicode_LENGTH(unicode) = length;
637 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200638 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200639 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200640 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200641 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200642 }
Victor Stinner95663112011-10-04 01:03:50 +0200643 assert(_PyUnicode_WSTR(unicode) != NULL);
644
645 /* check for integer overflow */
646 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
647 PyErr_NoMemory();
648 return -1;
649 }
650 wstr = _PyUnicode_WSTR(unicode);
651 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
652 if (!wstr) {
653 PyErr_NoMemory();
654 return -1;
655 }
656 _PyUnicode_WSTR(unicode) = wstr;
657 _PyUnicode_WSTR(unicode)[length] = 0;
658 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200659 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000660 return 0;
661}
662
Victor Stinnerfe226c02011-10-03 03:52:20 +0200663static PyObject*
664resize_copy(PyObject *unicode, Py_ssize_t length)
665{
666 Py_ssize_t copy_length;
667 if (PyUnicode_IS_COMPACT(unicode)) {
668 PyObject *copy;
669 assert(PyUnicode_IS_READY(unicode));
670
671 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
672 if (copy == NULL)
673 return NULL;
674
675 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200676 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200677 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200678 }
679 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200680 PyObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200681 assert(_PyUnicode_WSTR(unicode) != NULL);
682 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200683 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200684 if (w == NULL)
685 return NULL;
686 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
687 copy_length = Py_MIN(copy_length, length);
688 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
689 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200690 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200691 }
692}
693
Guido van Rossumd57fd912000-03-10 22:53:23 +0000694/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000695 Ux0000 terminated; some code (e.g. new_identifier)
696 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000697
698 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000699 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000700
701*/
702
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200703#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200704static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200705#endif
706
Alexander Belopolsky40018472011-02-26 01:02:56 +0000707static PyUnicodeObject *
708_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000709{
710 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200711 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000712
Thomas Wouters477c8d52006-05-27 19:21:47 +0000713 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000714 if (length == 0 && unicode_empty != NULL) {
715 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200716 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000717 }
718
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000719 /* Ensure we won't overflow the size. */
720 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
721 return (PyUnicodeObject *)PyErr_NoMemory();
722 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200723 if (length < 0) {
724 PyErr_SetString(PyExc_SystemError,
725 "Negative size passed to _PyUnicode_New");
726 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000727 }
728
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200729#ifdef Py_DEBUG
730 ++unicode_old_new_calls;
731#endif
732
733 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
734 if (unicode == NULL)
735 return NULL;
736 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
737 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
738 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000739 PyErr_NoMemory();
740 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000741 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200742
Jeremy Hyltond8082792003-09-16 19:41:39 +0000743 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000744 * the caller fails before initializing str -- unicode_resize()
745 * reads str[0], and the Keep-Alive optimization can keep memory
746 * allocated for str alive across a call to unicode_dealloc(unicode).
747 * We don't want unicode_resize to read uninitialized memory in
748 * that case.
749 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200750 _PyUnicode_WSTR(unicode)[0] = 0;
751 _PyUnicode_WSTR(unicode)[length] = 0;
752 _PyUnicode_WSTR_LENGTH(unicode) = length;
753 _PyUnicode_HASH(unicode) = -1;
754 _PyUnicode_STATE(unicode).interned = 0;
755 _PyUnicode_STATE(unicode).kind = 0;
756 _PyUnicode_STATE(unicode).compact = 0;
757 _PyUnicode_STATE(unicode).ready = 0;
758 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200759 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200760 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200761 _PyUnicode_UTF8(unicode) = NULL;
762 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100763 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000764 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000765
Benjamin Peterson29060642009-01-31 22:14:21 +0000766 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000767 /* XXX UNREF/NEWREF interface should be more symmetrical */
768 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000769 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000770 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000771 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000772}
773
Victor Stinnerf42dc442011-10-02 23:33:16 +0200774static const char*
775unicode_kind_name(PyObject *unicode)
776{
Victor Stinner42dfd712011-10-03 14:41:45 +0200777 /* don't check consistency: unicode_kind_name() is called from
778 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200779 if (!PyUnicode_IS_COMPACT(unicode))
780 {
781 if (!PyUnicode_IS_READY(unicode))
782 return "wstr";
783 switch(PyUnicode_KIND(unicode))
784 {
785 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200786 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200787 return "legacy ascii";
788 else
789 return "legacy latin1";
790 case PyUnicode_2BYTE_KIND:
791 return "legacy UCS2";
792 case PyUnicode_4BYTE_KIND:
793 return "legacy UCS4";
794 default:
795 return "<legacy invalid kind>";
796 }
797 }
798 assert(PyUnicode_IS_READY(unicode));
799 switch(PyUnicode_KIND(unicode))
800 {
801 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200802 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200803 return "ascii";
804 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200805 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200806 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200807 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200808 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200809 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200810 default:
811 return "<invalid compact kind>";
812 }
813}
814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200815#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200816static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200817
818/* Functions wrapping macros for use in debugger */
819char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200820 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200821}
822
823void *_PyUnicode_compact_data(void *unicode) {
824 return _PyUnicode_COMPACT_DATA(unicode);
825}
826void *_PyUnicode_data(void *unicode){
827 printf("obj %p\n", unicode);
828 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
829 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
830 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
831 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
832 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
833 return PyUnicode_DATA(unicode);
834}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200835
836void
837_PyUnicode_Dump(PyObject *op)
838{
839 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200840 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
841 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
842 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200843
Victor Stinnera849a4b2011-10-03 12:12:11 +0200844 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200845 {
846 if (ascii->state.ascii)
847 data = (ascii + 1);
848 else
849 data = (compact + 1);
850 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200851 else
852 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200853 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
854
Victor Stinnera849a4b2011-10-03 12:12:11 +0200855 if (ascii->wstr == data)
856 printf("shared ");
857 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200858
Victor Stinnera3b334d2011-10-03 13:53:37 +0200859 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200860 printf(" (%zu), ", compact->wstr_length);
861 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
862 printf("shared ");
863 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200864 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200865 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200866}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200867#endif
868
869PyObject *
870PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
871{
872 PyObject *obj;
873 PyCompactUnicodeObject *unicode;
874 void *data;
875 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200876 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200877 Py_ssize_t char_size;
878 Py_ssize_t struct_size;
879
880 /* Optimization for empty strings */
881 if (size == 0 && unicode_empty != NULL) {
882 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200883 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200884 }
885
886#ifdef Py_DEBUG
887 ++unicode_new_new_calls;
888#endif
889
Victor Stinner9e9d6892011-10-04 01:02:02 +0200890 is_ascii = 0;
891 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200892 struct_size = sizeof(PyCompactUnicodeObject);
893 if (maxchar < 128) {
894 kind_state = PyUnicode_1BYTE_KIND;
895 char_size = 1;
896 is_ascii = 1;
897 struct_size = sizeof(PyASCIIObject);
898 }
899 else if (maxchar < 256) {
900 kind_state = PyUnicode_1BYTE_KIND;
901 char_size = 1;
902 }
903 else if (maxchar < 65536) {
904 kind_state = PyUnicode_2BYTE_KIND;
905 char_size = 2;
906 if (sizeof(wchar_t) == 2)
907 is_sharing = 1;
908 }
909 else {
910 kind_state = PyUnicode_4BYTE_KIND;
911 char_size = 4;
912 if (sizeof(wchar_t) == 4)
913 is_sharing = 1;
914 }
915
916 /* Ensure we won't overflow the size. */
917 if (size < 0) {
918 PyErr_SetString(PyExc_SystemError,
919 "Negative size passed to PyUnicode_New");
920 return NULL;
921 }
922 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
923 return PyErr_NoMemory();
924
925 /* Duplicated allocation code from _PyObject_New() instead of a call to
926 * PyObject_New() so we are able to allocate space for the object and
927 * it's data buffer.
928 */
929 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
930 if (obj == NULL)
931 return PyErr_NoMemory();
932 obj = PyObject_INIT(obj, &PyUnicode_Type);
933 if (obj == NULL)
934 return NULL;
935
936 unicode = (PyCompactUnicodeObject *)obj;
937 if (is_ascii)
938 data = ((PyASCIIObject*)obj) + 1;
939 else
940 data = unicode + 1;
941 _PyUnicode_LENGTH(unicode) = size;
942 _PyUnicode_HASH(unicode) = -1;
943 _PyUnicode_STATE(unicode).interned = 0;
944 _PyUnicode_STATE(unicode).kind = kind_state;
945 _PyUnicode_STATE(unicode).compact = 1;
946 _PyUnicode_STATE(unicode).ready = 1;
947 _PyUnicode_STATE(unicode).ascii = is_ascii;
948 if (is_ascii) {
949 ((char*)data)[size] = 0;
950 _PyUnicode_WSTR(unicode) = NULL;
951 }
952 else if (kind_state == PyUnicode_1BYTE_KIND) {
953 ((char*)data)[size] = 0;
954 _PyUnicode_WSTR(unicode) = NULL;
955 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200956 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200957 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200958 }
959 else {
960 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200961 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200962 if (kind_state == PyUnicode_2BYTE_KIND)
963 ((Py_UCS2*)data)[size] = 0;
964 else /* kind_state == PyUnicode_4BYTE_KIND */
965 ((Py_UCS4*)data)[size] = 0;
966 if (is_sharing) {
967 _PyUnicode_WSTR_LENGTH(unicode) = size;
968 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
969 }
970 else {
971 _PyUnicode_WSTR_LENGTH(unicode) = 0;
972 _PyUnicode_WSTR(unicode) = NULL;
973 }
974 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100975 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200976 return obj;
977}
978
979#if SIZEOF_WCHAR_T == 2
980/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
981 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +0200982 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200983
984 This function assumes that unicode can hold one more code point than wstr
985 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200986static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200988 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200989{
990 const wchar_t *iter;
991 Py_UCS4 *ucs4_out;
992
Victor Stinner910337b2011-10-03 03:20:16 +0200993 assert(unicode != NULL);
994 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200995 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
996 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
997
998 for (iter = begin; iter < end; ) {
999 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1000 _PyUnicode_GET_LENGTH(unicode)));
1001 if (*iter >= 0xD800 && *iter <= 0xDBFF
1002 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1003 {
1004 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
1005 iter += 2;
1006 }
1007 else {
1008 *ucs4_out++ = *iter;
1009 iter++;
1010 }
1011 }
1012 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1013 _PyUnicode_GET_LENGTH(unicode)));
1014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001015}
1016#endif
1017
Victor Stinnercd9950f2011-10-02 00:34:53 +02001018static int
1019_PyUnicode_Dirty(PyObject *unicode)
1020{
Victor Stinner910337b2011-10-03 03:20:16 +02001021 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001022 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001023 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001024 "Cannot modify a string having more than 1 reference");
1025 return -1;
1026 }
1027 _PyUnicode_DIRTY(unicode);
1028 return 0;
1029}
1030
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001031static int
1032_copy_characters(PyObject *to, Py_ssize_t to_start,
1033 PyObject *from, Py_ssize_t from_start,
1034 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001035{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001036 unsigned int from_kind, to_kind;
1037 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001038 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001039
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001040 assert(PyUnicode_Check(from));
1041 assert(PyUnicode_Check(to));
1042 assert(PyUnicode_IS_READY(from));
1043 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001044
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001045 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1046 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1047 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001048
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001049 if (how_many == 0)
1050 return 0;
1051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001053 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001055 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001056
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001057#ifdef Py_DEBUG
1058 if (!check_maxchar
1059 && (from_kind > to_kind
1060 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001061 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001062 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1063 Py_UCS4 ch;
1064 Py_ssize_t i;
1065 for (i=0; i < how_many; i++) {
1066 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1067 assert(ch <= to_maxchar);
1068 }
1069 }
1070#endif
1071 fast = (from_kind == to_kind);
1072 if (check_maxchar
1073 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1074 {
1075 /* deny latin1 => ascii */
1076 fast = 0;
1077 }
1078
1079 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001080 Py_MEMCPY((char*)to_data + to_kind * to_start,
1081 (char*)from_data + from_kind * from_start,
1082 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001083 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001084 else if (from_kind == PyUnicode_1BYTE_KIND
1085 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001086 {
1087 _PyUnicode_CONVERT_BYTES(
1088 Py_UCS1, Py_UCS2,
1089 PyUnicode_1BYTE_DATA(from) + from_start,
1090 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1091 PyUnicode_2BYTE_DATA(to) + to_start
1092 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001093 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001094 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001095 && to_kind == PyUnicode_4BYTE_KIND)
1096 {
1097 _PyUnicode_CONVERT_BYTES(
1098 Py_UCS1, Py_UCS4,
1099 PyUnicode_1BYTE_DATA(from) + from_start,
1100 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1101 PyUnicode_4BYTE_DATA(to) + to_start
1102 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001103 }
1104 else if (from_kind == PyUnicode_2BYTE_KIND
1105 && to_kind == PyUnicode_4BYTE_KIND)
1106 {
1107 _PyUnicode_CONVERT_BYTES(
1108 Py_UCS2, Py_UCS4,
1109 PyUnicode_2BYTE_DATA(from) + from_start,
1110 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1111 PyUnicode_4BYTE_DATA(to) + to_start
1112 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001113 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001114 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001115 /* check if max_char(from substring) <= max_char(to) */
1116 if (from_kind > to_kind
1117 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001118 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001119 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001120 /* slow path to check for character overflow */
1121 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001122 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001123 Py_ssize_t i;
1124
Victor Stinner56c161a2011-10-06 02:47:11 +02001125#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001126 for (i=0; i < how_many; i++) {
1127 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001128 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001129 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1130 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001131#else
1132 if (!check_maxchar) {
1133 for (i=0; i < how_many; i++) {
1134 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1135 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1136 }
1137 }
1138 else {
1139 for (i=0; i < how_many; i++) {
1140 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1141 if (ch > to_maxchar)
1142 return 1;
1143 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1144 }
1145 }
1146#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001147 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001148 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001149 assert(0 && "inconsistent state");
1150 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001151 }
1152 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001153 return 0;
1154}
1155
1156static void
1157copy_characters(PyObject *to, Py_ssize_t to_start,
1158 PyObject *from, Py_ssize_t from_start,
1159 Py_ssize_t how_many)
1160{
1161 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1162}
1163
1164Py_ssize_t
1165PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1166 PyObject *from, Py_ssize_t from_start,
1167 Py_ssize_t how_many)
1168{
1169 int err;
1170
1171 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1172 PyErr_BadInternalCall();
1173 return -1;
1174 }
1175
1176 if (PyUnicode_READY(from))
1177 return -1;
1178 if (PyUnicode_READY(to))
1179 return -1;
1180
1181 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1182 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1183 PyErr_Format(PyExc_SystemError,
1184 "Cannot write %zi characters at %zi "
1185 "in a string of %zi characters",
1186 how_many, to_start, PyUnicode_GET_LENGTH(to));
1187 return -1;
1188 }
1189
1190 if (how_many == 0)
1191 return 0;
1192
1193 if (_PyUnicode_Dirty(to))
1194 return -1;
1195
1196 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1197 if (err) {
1198 PyErr_Format(PyExc_SystemError,
1199 "Cannot copy %s characters "
1200 "into a string of %s characters",
1201 unicode_kind_name(from),
1202 unicode_kind_name(to));
1203 return -1;
1204 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001205 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001206}
1207
Victor Stinner17222162011-09-28 22:15:37 +02001208/* Find the maximum code point and count the number of surrogate pairs so a
1209 correct string length can be computed before converting a string to UCS4.
1210 This function counts single surrogates as a character and not as a pair.
1211
1212 Return 0 on success, or -1 on error. */
1213static int
1214find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1215 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001216{
1217 const wchar_t *iter;
1218
Victor Stinnerc53be962011-10-02 21:33:54 +02001219 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001220 *num_surrogates = 0;
1221 *maxchar = 0;
1222
1223 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001224 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001225 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001226#if SIZEOF_WCHAR_T != 2
1227 if (*maxchar >= 0x10000)
1228 return 0;
1229#endif
1230 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001231#if SIZEOF_WCHAR_T == 2
1232 if (*iter >= 0xD800 && *iter <= 0xDBFF
1233 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1234 {
1235 Py_UCS4 surrogate_val;
1236 surrogate_val = (((iter[0] & 0x3FF)<<10)
1237 | (iter[1] & 0x3FF)) + 0x10000;
1238 ++(*num_surrogates);
1239 if (surrogate_val > *maxchar)
1240 *maxchar = surrogate_val;
1241 iter += 2;
1242 }
1243 else
1244 iter++;
1245#else
1246 iter++;
1247#endif
1248 }
1249 return 0;
1250}
1251
1252#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001253static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001254#endif
1255
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001256static int
1257unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001258{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001259 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001260 wchar_t *end;
1261 Py_UCS4 maxchar = 0;
1262 Py_ssize_t num_surrogates;
1263#if SIZEOF_WCHAR_T == 2
1264 Py_ssize_t length_wo_surrogates;
1265#endif
1266
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001267 assert(p_obj != NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001268 unicode = *p_obj;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001269
Georg Brandl7597add2011-10-05 16:36:47 +02001270 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001271 strings were created using _PyObject_New() and where no canonical
1272 representation (the str field) has been set yet aka strings
1273 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001274 assert(_PyUnicode_CHECK(unicode));
1275 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001276 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001277 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001278 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001279 /* Actually, it should neither be interned nor be anything else: */
1280 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001281
1282#ifdef Py_DEBUG
1283 ++unicode_ready_calls;
1284#endif
1285
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001286#ifdef Py_DEBUG
1287 assert(!replace || Py_REFCNT(unicode) == 1);
1288#else
1289 if (replace && Py_REFCNT(unicode) != 1)
1290 replace = 0;
1291#endif
1292 if (replace) {
1293 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1294 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1295 /* Optimization for empty strings */
1296 if (len == 0) {
1297 Py_INCREF(unicode_empty);
1298 Py_DECREF(*p_obj);
1299 *p_obj = unicode_empty;
1300 return 0;
1301 }
1302 if (len == 1 && wstr[0] < 256) {
1303 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1304 if (latin1_char == NULL)
1305 return -1;
1306 Py_DECREF(*p_obj);
1307 *p_obj = latin1_char;
1308 return 0;
1309 }
1310 }
1311
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001312 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001313 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001314 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001315 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316
1317 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001318 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1319 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320 PyErr_NoMemory();
1321 return -1;
1322 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001323 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324 _PyUnicode_WSTR(unicode), end,
1325 PyUnicode_1BYTE_DATA(unicode));
1326 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1327 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1328 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1329 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001330 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001331 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001332 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001333 }
1334 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001335 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001336 _PyUnicode_UTF8(unicode) = NULL;
1337 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001338 }
1339 PyObject_FREE(_PyUnicode_WSTR(unicode));
1340 _PyUnicode_WSTR(unicode) = NULL;
1341 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1342 }
1343 /* In this case we might have to convert down from 4-byte native
1344 wchar_t to 2-byte unicode. */
1345 else if (maxchar < 65536) {
1346 assert(num_surrogates == 0 &&
1347 "FindMaxCharAndNumSurrogatePairs() messed up");
1348
Victor Stinner506f5922011-09-28 22:34:18 +02001349#if SIZEOF_WCHAR_T == 2
1350 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001351 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001352 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1353 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1354 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001355 _PyUnicode_UTF8(unicode) = NULL;
1356 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001357#else
1358 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001359 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001360 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001361 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001362 PyErr_NoMemory();
1363 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001364 }
Victor Stinner506f5922011-09-28 22:34:18 +02001365 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1366 _PyUnicode_WSTR(unicode), end,
1367 PyUnicode_2BYTE_DATA(unicode));
1368 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1369 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1370 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001371 _PyUnicode_UTF8(unicode) = NULL;
1372 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001373 PyObject_FREE(_PyUnicode_WSTR(unicode));
1374 _PyUnicode_WSTR(unicode) = NULL;
1375 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1376#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001377 }
1378 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1379 else {
1380#if SIZEOF_WCHAR_T == 2
1381 /* in case the native representation is 2-bytes, we need to allocate a
1382 new normalized 4-byte version. */
1383 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001384 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1385 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001386 PyErr_NoMemory();
1387 return -1;
1388 }
1389 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1390 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001391 _PyUnicode_UTF8(unicode) = NULL;
1392 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001393 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1394 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001395 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001396 PyObject_FREE(_PyUnicode_WSTR(unicode));
1397 _PyUnicode_WSTR(unicode) = NULL;
1398 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1399#else
1400 assert(num_surrogates == 0);
1401
Victor Stinnerc3c74152011-10-02 20:39:55 +02001402 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001403 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001404 _PyUnicode_UTF8(unicode) = NULL;
1405 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1407#endif
1408 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1409 }
1410 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001411 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001412 return 0;
1413}
1414
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001415int
1416_PyUnicode_ReadyReplace(PyObject **op)
1417{
1418 return unicode_ready(op, 1);
1419}
1420
1421int
1422_PyUnicode_Ready(PyObject *op)
1423{
1424 return unicode_ready(&op, 0);
1425}
1426
Alexander Belopolsky40018472011-02-26 01:02:56 +00001427static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001428unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001429{
Walter Dörwald16807132007-05-25 13:52:07 +00001430 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001431 case SSTATE_NOT_INTERNED:
1432 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001433
Benjamin Peterson29060642009-01-31 22:14:21 +00001434 case SSTATE_INTERNED_MORTAL:
1435 /* revive dead object temporarily for DelItem */
1436 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001437 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001438 Py_FatalError(
1439 "deletion of interned string failed");
1440 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001441
Benjamin Peterson29060642009-01-31 22:14:21 +00001442 case SSTATE_INTERNED_IMMORTAL:
1443 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001444
Benjamin Peterson29060642009-01-31 22:14:21 +00001445 default:
1446 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001447 }
1448
Victor Stinner03490912011-10-03 23:45:12 +02001449 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001450 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001451 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001452 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001453
1454 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01001455 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001456 }
1457 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001458 if (_PyUnicode_DATA_ANY(unicode))
1459 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Victor Stinner7931d9a2011-11-04 00:22:48 +01001460 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001461 }
1462}
1463
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001464#ifdef Py_DEBUG
1465static int
1466unicode_is_singleton(PyObject *unicode)
1467{
1468 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1469 if (unicode == unicode_empty)
1470 return 1;
1471 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1472 {
1473 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1474 if (ch < 256 && unicode_latin1[ch] == unicode)
1475 return 1;
1476 }
1477 return 0;
1478}
1479#endif
1480
Alexander Belopolsky40018472011-02-26 01:02:56 +00001481static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001482unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001483{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001484 if (Py_REFCNT(unicode) != 1)
1485 return 0;
1486 if (PyUnicode_CHECK_INTERNED(unicode))
1487 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001488#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001489 /* singleton refcount is greater than 1 */
1490 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001491#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001492 return 1;
1493}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001494
Victor Stinnerfe226c02011-10-03 03:52:20 +02001495static int
1496unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1497{
1498 PyObject *unicode;
1499 Py_ssize_t old_length;
1500
1501 assert(p_unicode != NULL);
1502 unicode = *p_unicode;
1503
1504 assert(unicode != NULL);
1505 assert(PyUnicode_Check(unicode));
1506 assert(0 <= length);
1507
Victor Stinner910337b2011-10-03 03:20:16 +02001508 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001509 old_length = PyUnicode_WSTR_LENGTH(unicode);
1510 else
1511 old_length = PyUnicode_GET_LENGTH(unicode);
1512 if (old_length == length)
1513 return 0;
1514
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001515 if (length == 0) {
1516 Py_DECREF(*p_unicode);
1517 *p_unicode = unicode_empty;
1518 Py_INCREF(*p_unicode);
1519 return 0;
1520 }
1521
Victor Stinnerfe226c02011-10-03 03:52:20 +02001522 if (!unicode_resizable(unicode)) {
1523 PyObject *copy = resize_copy(unicode, length);
1524 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001525 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001526 Py_DECREF(*p_unicode);
1527 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001528 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001529 }
1530
Victor Stinnerfe226c02011-10-03 03:52:20 +02001531 if (PyUnicode_IS_COMPACT(unicode)) {
1532 *p_unicode = resize_compact(unicode, length);
1533 if (*p_unicode == NULL)
1534 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001535 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001536 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001537 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001538 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001539}
1540
Alexander Belopolsky40018472011-02-26 01:02:56 +00001541int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001542PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001543{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001544 PyObject *unicode;
1545 if (p_unicode == NULL) {
1546 PyErr_BadInternalCall();
1547 return -1;
1548 }
1549 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001550 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001551 {
1552 PyErr_BadInternalCall();
1553 return -1;
1554 }
1555 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001556}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001557
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001558static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001559unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001560{
1561 PyObject *result;
1562 assert(PyUnicode_IS_READY(*p_unicode));
1563 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1564 return 0;
1565 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1566 maxchar);
1567 if (result == NULL)
1568 return -1;
1569 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1570 PyUnicode_GET_LENGTH(*p_unicode));
1571 Py_DECREF(*p_unicode);
1572 *p_unicode = result;
1573 return 0;
1574}
1575
1576static int
1577unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1578 Py_UCS4 ch)
1579{
1580 if (unicode_widen(p_unicode, ch) < 0)
1581 return -1;
1582 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1583 PyUnicode_DATA(*p_unicode),
1584 (*pos)++, ch);
1585 return 0;
1586}
1587
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001588static PyObject*
1589get_latin1_char(unsigned char ch)
1590{
Victor Stinnera464fc12011-10-02 20:39:30 +02001591 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001592 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001593 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001594 if (!unicode)
1595 return NULL;
1596 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001597 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001598 unicode_latin1[ch] = unicode;
1599 }
1600 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001601 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001602}
1603
Alexander Belopolsky40018472011-02-26 01:02:56 +00001604PyObject *
1605PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001606{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001607 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001608 Py_UCS4 maxchar = 0;
1609 Py_ssize_t num_surrogates;
1610
1611 if (u == NULL)
1612 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001613
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001614 /* If the Unicode data is known at construction time, we can apply
1615 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001616
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001617 /* Optimization for empty strings */
1618 if (size == 0 && unicode_empty != NULL) {
1619 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001620 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001621 }
Tim Petersced69f82003-09-16 20:30:58 +00001622
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001623 /* Single character Unicode objects in the Latin-1 range are
1624 shared when using this constructor */
1625 if (size == 1 && *u < 256)
1626 return get_latin1_char((unsigned char)*u);
1627
1628 /* If not empty and not single character, copy the Unicode data
1629 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001630 if (find_maxchar_surrogates(u, u + size,
1631 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001632 return NULL;
1633
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001634 unicode = PyUnicode_New(size - num_surrogates,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001635 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001636 if (!unicode)
1637 return NULL;
1638
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001639 switch (PyUnicode_KIND(unicode)) {
1640 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001641 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001642 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1643 break;
1644 case PyUnicode_2BYTE_KIND:
1645#if Py_UNICODE_SIZE == 2
1646 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1647#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001648 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001649 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1650#endif
1651 break;
1652 case PyUnicode_4BYTE_KIND:
1653#if SIZEOF_WCHAR_T == 2
1654 /* This is the only case which has to process surrogates, thus
1655 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001656 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657#else
1658 assert(num_surrogates == 0);
1659 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1660#endif
1661 break;
1662 default:
1663 assert(0 && "Impossible state");
1664 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001665
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001666 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001667 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001668}
1669
Alexander Belopolsky40018472011-02-26 01:02:56 +00001670PyObject *
1671PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001672{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001673 if (size < 0) {
1674 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001675 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001676 return NULL;
1677 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001678
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001679 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001680 some optimizations which share commonly used objects.
1681 Also, this means the input must be UTF-8, so fall back to the
1682 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001683 if (u != NULL) {
1684
Benjamin Peterson29060642009-01-31 22:14:21 +00001685 /* Optimization for empty strings */
1686 if (size == 0 && unicode_empty != NULL) {
1687 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001688 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001689 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001690
1691 /* Single characters are shared when using this constructor.
1692 Restrict to ASCII, since the input must be UTF-8. */
Victor Stinner9faa3842011-10-23 20:06:00 +02001693 if (size == 1 && (unsigned char)*u < 128)
1694 return get_latin1_char((unsigned char)*u);
Martin v. Löwis9c121062007-08-05 20:26:11 +00001695
1696 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001697 }
1698
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001699 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001700}
1701
Alexander Belopolsky40018472011-02-26 01:02:56 +00001702PyObject *
1703PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001704{
1705 size_t size = strlen(u);
1706 if (size > PY_SSIZE_T_MAX) {
1707 PyErr_SetString(PyExc_OverflowError, "input too long");
1708 return NULL;
1709 }
1710
1711 return PyUnicode_FromStringAndSize(u, size);
1712}
1713
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001714PyObject *
1715_PyUnicode_FromId(_Py_Identifier *id)
1716{
1717 if (!id->object) {
1718 id->object = PyUnicode_FromString(id->string);
1719 if (!id->object)
1720 return NULL;
1721 PyUnicode_InternInPlace(&id->object);
1722 assert(!id->next);
1723 id->next = static_strings;
1724 static_strings = id;
1725 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001726 return id->object;
1727}
1728
1729void
1730_PyUnicode_ClearStaticStrings()
1731{
1732 _Py_Identifier *i;
1733 for (i = static_strings; i; i = i->next) {
1734 Py_DECREF(i->object);
1735 i->object = NULL;
1736 i->next = NULL;
1737 }
1738}
1739
Victor Stinnere57b1c02011-09-28 22:20:48 +02001740static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001741unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001742{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001743 PyObject *res;
1744#ifdef Py_DEBUG
1745 const unsigned char *p;
1746 const unsigned char *end = s + size;
1747 for (p=s; p < end; p++) {
1748 assert(*p < 128);
1749 }
1750#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001751 if (size == 1)
1752 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001753 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001754 if (!res)
1755 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001756 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001757 return res;
1758}
1759
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001760static Py_UCS4
1761kind_maxchar_limit(unsigned int kind)
1762{
1763 switch(kind) {
1764 case PyUnicode_1BYTE_KIND:
1765 return 0x80;
1766 case PyUnicode_2BYTE_KIND:
1767 return 0x100;
1768 case PyUnicode_4BYTE_KIND:
1769 return 0x10000;
1770 default:
1771 assert(0 && "invalid kind");
1772 return 0x10ffff;
1773 }
1774}
1775
Victor Stinner702c7342011-10-05 13:50:52 +02001776static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001777_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001778{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001779 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001780 unsigned char max_char = 127;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001781
1782 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001783 if (size == 1)
1784 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001785 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001786 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001787 if (!res)
1788 return NULL;
1789 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001790 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001791 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001792}
1793
Victor Stinnere57b1c02011-09-28 22:20:48 +02001794static PyObject*
1795_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001796{
1797 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001798 Py_UCS2 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001799
1800 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001801 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001802 return get_latin1_char((unsigned char)u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001803 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001804 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001805 if (!res)
1806 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001807 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001808 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001809 else {
1810 _PyUnicode_CONVERT_BYTES(
1811 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1812 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001813 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001814 return res;
1815}
1816
Victor Stinnere57b1c02011-09-28 22:20:48 +02001817static PyObject*
1818_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001819{
1820 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001821 Py_UCS4 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001822
1823 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001824 if (size == 1 && u[0] < 256)
1825 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001826 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001827 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001828 if (!res)
1829 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001830 if (max_char < 256)
1831 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1832 PyUnicode_1BYTE_DATA(res));
1833 else if (max_char < 0x10000)
1834 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1835 PyUnicode_2BYTE_DATA(res));
1836 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001837 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001838 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001839 return res;
1840}
1841
1842PyObject*
1843PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1844{
1845 switch(kind) {
1846 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001847 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001848 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001849 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001850 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001851 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001852 default:
1853 assert(0 && "invalid kind");
1854 PyErr_SetString(PyExc_SystemError, "invalid kind");
1855 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001856 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001857}
1858
Victor Stinner25a4b292011-10-06 12:31:55 +02001859/* Ensure that a string uses the most efficient storage, if it is not the
1860 case: create a new string with of the right kind. Write NULL into *p_unicode
1861 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001862static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001863unicode_adjust_maxchar(PyObject **p_unicode)
1864{
1865 PyObject *unicode, *copy;
1866 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001867 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001868 unsigned int kind;
1869
1870 assert(p_unicode != NULL);
1871 unicode = *p_unicode;
1872 assert(PyUnicode_IS_READY(unicode));
1873 if (PyUnicode_IS_ASCII(unicode))
1874 return;
1875
1876 len = PyUnicode_GET_LENGTH(unicode);
1877 kind = PyUnicode_KIND(unicode);
1878 if (kind == PyUnicode_1BYTE_KIND) {
1879 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001880 max_char = ucs1lib_find_max_char(u, u + len);
1881 if (max_char >= 128)
1882 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001883 }
1884 else if (kind == PyUnicode_2BYTE_KIND) {
1885 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001886 max_char = ucs2lib_find_max_char(u, u + len);
1887 if (max_char >= 256)
1888 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001889 }
1890 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001891 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001892 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001893 max_char = ucs4lib_find_max_char(u, u + len);
1894 if (max_char >= 0x10000)
1895 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001896 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001897 copy = PyUnicode_New(len, max_char);
1898 copy_characters(copy, 0, unicode, 0, len);
1899 Py_DECREF(unicode);
1900 *p_unicode = copy;
1901}
1902
Victor Stinner034f6cf2011-09-30 02:26:44 +02001903PyObject*
1904PyUnicode_Copy(PyObject *unicode)
1905{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001906 Py_ssize_t size;
1907 PyObject *copy;
1908 void *data;
1909
Victor Stinner034f6cf2011-09-30 02:26:44 +02001910 if (!PyUnicode_Check(unicode)) {
1911 PyErr_BadInternalCall();
1912 return NULL;
1913 }
1914 if (PyUnicode_READY(unicode))
1915 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001916
1917 size = PyUnicode_GET_LENGTH(unicode);
1918 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1919 if (!copy)
1920 return NULL;
1921 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1922
1923 data = PyUnicode_DATA(unicode);
1924 switch (PyUnicode_KIND(unicode))
1925 {
1926 case PyUnicode_1BYTE_KIND:
1927 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1928 break;
1929 case PyUnicode_2BYTE_KIND:
1930 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1931 break;
1932 case PyUnicode_4BYTE_KIND:
1933 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1934 break;
1935 default:
1936 assert(0);
1937 break;
1938 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001939 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001940 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001941}
1942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001943
Victor Stinnerbc603d12011-10-02 01:00:40 +02001944/* Widen Unicode objects to larger buffers. Don't write terminating null
1945 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001946
1947void*
1948_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1949{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001950 Py_ssize_t len;
1951 void *result;
1952 unsigned int skind;
1953
1954 if (PyUnicode_READY(s))
1955 return NULL;
1956
1957 len = PyUnicode_GET_LENGTH(s);
1958 skind = PyUnicode_KIND(s);
1959 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001960 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001961 return NULL;
1962 }
1963 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001964 case PyUnicode_2BYTE_KIND:
1965 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1966 if (!result)
1967 return PyErr_NoMemory();
1968 assert(skind == PyUnicode_1BYTE_KIND);
1969 _PyUnicode_CONVERT_BYTES(
1970 Py_UCS1, Py_UCS2,
1971 PyUnicode_1BYTE_DATA(s),
1972 PyUnicode_1BYTE_DATA(s) + len,
1973 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001974 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001975 case PyUnicode_4BYTE_KIND:
1976 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1977 if (!result)
1978 return PyErr_NoMemory();
1979 if (skind == PyUnicode_2BYTE_KIND) {
1980 _PyUnicode_CONVERT_BYTES(
1981 Py_UCS2, Py_UCS4,
1982 PyUnicode_2BYTE_DATA(s),
1983 PyUnicode_2BYTE_DATA(s) + len,
1984 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001985 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001986 else {
1987 assert(skind == PyUnicode_1BYTE_KIND);
1988 _PyUnicode_CONVERT_BYTES(
1989 Py_UCS1, Py_UCS4,
1990 PyUnicode_1BYTE_DATA(s),
1991 PyUnicode_1BYTE_DATA(s) + len,
1992 result);
1993 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001994 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001995 default:
1996 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001997 }
Victor Stinner01698042011-10-04 00:04:26 +02001998 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001999 return NULL;
2000}
2001
2002static Py_UCS4*
2003as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2004 int copy_null)
2005{
2006 int kind;
2007 void *data;
2008 Py_ssize_t len, targetlen;
2009 if (PyUnicode_READY(string) == -1)
2010 return NULL;
2011 kind = PyUnicode_KIND(string);
2012 data = PyUnicode_DATA(string);
2013 len = PyUnicode_GET_LENGTH(string);
2014 targetlen = len;
2015 if (copy_null)
2016 targetlen++;
2017 if (!target) {
2018 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2019 PyErr_NoMemory();
2020 return NULL;
2021 }
2022 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2023 if (!target) {
2024 PyErr_NoMemory();
2025 return NULL;
2026 }
2027 }
2028 else {
2029 if (targetsize < targetlen) {
2030 PyErr_Format(PyExc_SystemError,
2031 "string is longer than the buffer");
2032 if (copy_null && 0 < targetsize)
2033 target[0] = 0;
2034 return NULL;
2035 }
2036 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002037 if (kind == PyUnicode_1BYTE_KIND) {
2038 Py_UCS1 *start = (Py_UCS1 *) data;
2039 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002040 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002041 else if (kind == PyUnicode_2BYTE_KIND) {
2042 Py_UCS2 *start = (Py_UCS2 *) data;
2043 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2044 }
2045 else {
2046 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002048 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002049 if (copy_null)
2050 target[len] = 0;
2051 return target;
2052}
2053
2054Py_UCS4*
2055PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2056 int copy_null)
2057{
2058 if (target == NULL || targetsize < 1) {
2059 PyErr_BadInternalCall();
2060 return NULL;
2061 }
2062 return as_ucs4(string, target, targetsize, copy_null);
2063}
2064
2065Py_UCS4*
2066PyUnicode_AsUCS4Copy(PyObject *string)
2067{
2068 return as_ucs4(string, NULL, 0, 1);
2069}
2070
2071#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002072
Alexander Belopolsky40018472011-02-26 01:02:56 +00002073PyObject *
2074PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002075{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002076 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002077 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002078 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002079 PyErr_BadInternalCall();
2080 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002081 }
2082
Martin v. Löwis790465f2008-04-05 20:41:37 +00002083 if (size == -1) {
2084 size = wcslen(w);
2085 }
2086
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002087 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002088}
2089
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002090#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002091
Walter Dörwald346737f2007-05-31 10:44:43 +00002092static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002093makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2094 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002095{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002096 *fmt++ = '%';
2097 if (width) {
2098 if (zeropad)
2099 *fmt++ = '0';
2100 fmt += sprintf(fmt, "%d", width);
2101 }
2102 if (precision)
2103 fmt += sprintf(fmt, ".%d", precision);
2104 if (longflag)
2105 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002106 else if (longlongflag) {
2107 /* longlongflag should only ever be nonzero on machines with
2108 HAVE_LONG_LONG defined */
2109#ifdef HAVE_LONG_LONG
2110 char *f = PY_FORMAT_LONG_LONG;
2111 while (*f)
2112 *fmt++ = *f++;
2113#else
2114 /* we shouldn't ever get here */
2115 assert(0);
2116 *fmt++ = 'l';
2117#endif
2118 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002119 else if (size_tflag) {
2120 char *f = PY_FORMAT_SIZE_T;
2121 while (*f)
2122 *fmt++ = *f++;
2123 }
2124 *fmt++ = c;
2125 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002126}
2127
Victor Stinner96865452011-03-01 23:44:09 +00002128/* helper for PyUnicode_FromFormatV() */
2129
2130static const char*
2131parse_format_flags(const char *f,
2132 int *p_width, int *p_precision,
2133 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2134{
2135 int width, precision, longflag, longlongflag, size_tflag;
2136
2137 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2138 f++;
2139 width = 0;
2140 while (Py_ISDIGIT((unsigned)*f))
2141 width = (width*10) + *f++ - '0';
2142 precision = 0;
2143 if (*f == '.') {
2144 f++;
2145 while (Py_ISDIGIT((unsigned)*f))
2146 precision = (precision*10) + *f++ - '0';
2147 if (*f == '%') {
2148 /* "%.3%s" => f points to "3" */
2149 f--;
2150 }
2151 }
2152 if (*f == '\0') {
2153 /* bogus format "%.1" => go backward, f points to "1" */
2154 f--;
2155 }
2156 if (p_width != NULL)
2157 *p_width = width;
2158 if (p_precision != NULL)
2159 *p_precision = precision;
2160
2161 /* Handle %ld, %lu, %lld and %llu. */
2162 longflag = 0;
2163 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002164 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002165
2166 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002167 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002168 longflag = 1;
2169 ++f;
2170 }
2171#ifdef HAVE_LONG_LONG
2172 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002173 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002174 longlongflag = 1;
2175 f += 2;
2176 }
2177#endif
2178 }
2179 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002180 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002181 size_tflag = 1;
2182 ++f;
2183 }
2184 if (p_longflag != NULL)
2185 *p_longflag = longflag;
2186 if (p_longlongflag != NULL)
2187 *p_longlongflag = longlongflag;
2188 if (p_size_tflag != NULL)
2189 *p_size_tflag = size_tflag;
2190 return f;
2191}
2192
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002193/* maximum number of characters required for output of %ld. 21 characters
2194 allows for 64-bit integers (in decimal) and an optional sign. */
2195#define MAX_LONG_CHARS 21
2196/* maximum number of characters required for output of %lld.
2197 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2198 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2199#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2200
Walter Dörwaldd2034312007-05-18 16:29:38 +00002201PyObject *
2202PyUnicode_FromFormatV(const char *format, va_list vargs)
2203{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002204 va_list count;
2205 Py_ssize_t callcount = 0;
2206 PyObject **callresults = NULL;
2207 PyObject **callresult = NULL;
2208 Py_ssize_t n = 0;
2209 int width = 0;
2210 int precision = 0;
2211 int zeropad;
2212 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002213 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002214 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002215 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002216 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2217 Py_UCS4 argmaxchar;
2218 Py_ssize_t numbersize = 0;
2219 char *numberresults = NULL;
2220 char *numberresult = NULL;
2221 Py_ssize_t i;
2222 int kind;
2223 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002224
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002225 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002226 /* step 1: count the number of %S/%R/%A/%s format specifications
2227 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2228 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002229 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002230 * also estimate a upper bound for all the number formats in the string,
2231 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002232 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002233 for (f = format; *f; f++) {
2234 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002235 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002236 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2237 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2238 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2239 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002240
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002241 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002242#ifdef HAVE_LONG_LONG
2243 if (longlongflag) {
2244 if (width < MAX_LONG_LONG_CHARS)
2245 width = MAX_LONG_LONG_CHARS;
2246 }
2247 else
2248#endif
2249 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2250 including sign. Decimal takes the most space. This
2251 isn't enough for octal. If a width is specified we
2252 need more (which we allocate later). */
2253 if (width < MAX_LONG_CHARS)
2254 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002255
2256 /* account for the size + '\0' to separate numbers
2257 inside of the numberresults buffer */
2258 numbersize += (width + 1);
2259 }
2260 }
2261 else if ((unsigned char)*f > 127) {
2262 PyErr_Format(PyExc_ValueError,
2263 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2264 "string, got a non-ASCII byte: 0x%02x",
2265 (unsigned char)*f);
2266 return NULL;
2267 }
2268 }
2269 /* step 2: allocate memory for the results of
2270 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2271 if (callcount) {
2272 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2273 if (!callresults) {
2274 PyErr_NoMemory();
2275 return NULL;
2276 }
2277 callresult = callresults;
2278 }
2279 /* step 2.5: allocate memory for the results of formating numbers */
2280 if (numbersize) {
2281 numberresults = PyObject_Malloc(numbersize);
2282 if (!numberresults) {
2283 PyErr_NoMemory();
2284 goto fail;
2285 }
2286 numberresult = numberresults;
2287 }
2288
2289 /* step 3: format numbers and figure out how large a buffer we need */
2290 for (f = format; *f; f++) {
2291 if (*f == '%') {
2292 const char* p;
2293 int longflag;
2294 int longlongflag;
2295 int size_tflag;
2296 int numprinted;
2297
2298 p = f;
2299 zeropad = (f[1] == '0');
2300 f = parse_format_flags(f, &width, &precision,
2301 &longflag, &longlongflag, &size_tflag);
2302 switch (*f) {
2303 case 'c':
2304 {
2305 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002306 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002307 n++;
2308 break;
2309 }
2310 case '%':
2311 n++;
2312 break;
2313 case 'i':
2314 case 'd':
2315 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2316 width, precision, *f);
2317 if (longflag)
2318 numprinted = sprintf(numberresult, fmt,
2319 va_arg(count, long));
2320#ifdef HAVE_LONG_LONG
2321 else if (longlongflag)
2322 numprinted = sprintf(numberresult, fmt,
2323 va_arg(count, PY_LONG_LONG));
2324#endif
2325 else if (size_tflag)
2326 numprinted = sprintf(numberresult, fmt,
2327 va_arg(count, Py_ssize_t));
2328 else
2329 numprinted = sprintf(numberresult, fmt,
2330 va_arg(count, int));
2331 n += numprinted;
2332 /* advance by +1 to skip over the '\0' */
2333 numberresult += (numprinted + 1);
2334 assert(*(numberresult - 1) == '\0');
2335 assert(*(numberresult - 2) != '\0');
2336 assert(numprinted >= 0);
2337 assert(numberresult <= numberresults + numbersize);
2338 break;
2339 case 'u':
2340 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2341 width, precision, 'u');
2342 if (longflag)
2343 numprinted = sprintf(numberresult, fmt,
2344 va_arg(count, unsigned long));
2345#ifdef HAVE_LONG_LONG
2346 else if (longlongflag)
2347 numprinted = sprintf(numberresult, fmt,
2348 va_arg(count, unsigned PY_LONG_LONG));
2349#endif
2350 else if (size_tflag)
2351 numprinted = sprintf(numberresult, fmt,
2352 va_arg(count, size_t));
2353 else
2354 numprinted = sprintf(numberresult, fmt,
2355 va_arg(count, unsigned int));
2356 n += numprinted;
2357 numberresult += (numprinted + 1);
2358 assert(*(numberresult - 1) == '\0');
2359 assert(*(numberresult - 2) != '\0');
2360 assert(numprinted >= 0);
2361 assert(numberresult <= numberresults + numbersize);
2362 break;
2363 case 'x':
2364 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2365 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2366 n += numprinted;
2367 numberresult += (numprinted + 1);
2368 assert(*(numberresult - 1) == '\0');
2369 assert(*(numberresult - 2) != '\0');
2370 assert(numprinted >= 0);
2371 assert(numberresult <= numberresults + numbersize);
2372 break;
2373 case 'p':
2374 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2375 /* %p is ill-defined: ensure leading 0x. */
2376 if (numberresult[1] == 'X')
2377 numberresult[1] = 'x';
2378 else if (numberresult[1] != 'x') {
2379 memmove(numberresult + 2, numberresult,
2380 strlen(numberresult) + 1);
2381 numberresult[0] = '0';
2382 numberresult[1] = 'x';
2383 numprinted += 2;
2384 }
2385 n += numprinted;
2386 numberresult += (numprinted + 1);
2387 assert(*(numberresult - 1) == '\0');
2388 assert(*(numberresult - 2) != '\0');
2389 assert(numprinted >= 0);
2390 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002391 break;
2392 case 's':
2393 {
2394 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002395 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002396 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2397 if (!str)
2398 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002399 /* since PyUnicode_DecodeUTF8 returns already flexible
2400 unicode objects, there is no need to call ready on them */
2401 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002402 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002404 /* Remember the str and switch to the next slot */
2405 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002406 break;
2407 }
2408 case 'U':
2409 {
2410 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002411 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002412 if (PyUnicode_READY(obj) == -1)
2413 goto fail;
2414 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002415 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002416 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002417 break;
2418 }
2419 case 'V':
2420 {
2421 PyObject *obj = va_arg(count, PyObject *);
2422 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002423 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002424 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002425 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002426 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002427 if (PyUnicode_READY(obj) == -1)
2428 goto fail;
2429 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002430 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002431 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002432 *callresult++ = NULL;
2433 }
2434 else {
2435 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2436 if (!str_obj)
2437 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002438 if (PyUnicode_READY(str_obj)) {
2439 Py_DECREF(str_obj);
2440 goto fail;
2441 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002442 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002443 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002444 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002445 *callresult++ = str_obj;
2446 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002447 break;
2448 }
2449 case 'S':
2450 {
2451 PyObject *obj = va_arg(count, PyObject *);
2452 PyObject *str;
2453 assert(obj);
2454 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002455 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002456 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002457 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002458 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002459 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002460 /* Remember the str and switch to the next slot */
2461 *callresult++ = str;
2462 break;
2463 }
2464 case 'R':
2465 {
2466 PyObject *obj = va_arg(count, PyObject *);
2467 PyObject *repr;
2468 assert(obj);
2469 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002470 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002471 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002472 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002473 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002474 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002475 /* Remember the repr and switch to the next slot */
2476 *callresult++ = repr;
2477 break;
2478 }
2479 case 'A':
2480 {
2481 PyObject *obj = va_arg(count, PyObject *);
2482 PyObject *ascii;
2483 assert(obj);
2484 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002485 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002486 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002488 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002489 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002490 /* Remember the repr and switch to the next slot */
2491 *callresult++ = ascii;
2492 break;
2493 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002494 default:
2495 /* if we stumble upon an unknown
2496 formatting code, copy the rest of
2497 the format string to the output
2498 string. (we cannot just skip the
2499 code, since there's no way to know
2500 what's in the argument list) */
2501 n += strlen(p);
2502 goto expand;
2503 }
2504 } else
2505 n++;
2506 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002507 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002508 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002509 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002510 we don't have to resize the string.
2511 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002512 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002513 if (!string)
2514 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002515 kind = PyUnicode_KIND(string);
2516 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002517 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002518 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002519
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002520 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002521 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002522 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002523
2524 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002525 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2526 /* checking for == because the last argument could be a empty
2527 string, which causes i to point to end, the assert at the end of
2528 the loop */
2529 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002530
Benjamin Peterson14339b62009-01-31 16:36:08 +00002531 switch (*f) {
2532 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002533 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002534 const int ordinal = va_arg(vargs, int);
2535 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002536 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002537 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002538 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002539 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002540 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002541 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002542 case 'p':
2543 /* unused, since we already have the result */
2544 if (*f == 'p')
2545 (void) va_arg(vargs, void *);
2546 else
2547 (void) va_arg(vargs, int);
2548 /* extract the result from numberresults and append. */
2549 for (; *numberresult; ++i, ++numberresult)
2550 PyUnicode_WRITE(kind, data, i, *numberresult);
2551 /* skip over the separating '\0' */
2552 assert(*numberresult == '\0');
2553 numberresult++;
2554 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002555 break;
2556 case 's':
2557 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002558 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002559 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002560 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002561 size = PyUnicode_GET_LENGTH(*callresult);
2562 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002563 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002564 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002565 /* We're done with the unicode()/repr() => forget it */
2566 Py_DECREF(*callresult);
2567 /* switch to next unicode()/repr() result */
2568 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002569 break;
2570 }
2571 case 'U':
2572 {
2573 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002574 Py_ssize_t size;
2575 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2576 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002577 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002578 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002579 break;
2580 }
2581 case 'V':
2582 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002583 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002584 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002585 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002586 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002587 size = PyUnicode_GET_LENGTH(obj);
2588 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002589 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002590 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002591 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002592 size = PyUnicode_GET_LENGTH(*callresult);
2593 assert(PyUnicode_KIND(*callresult) <=
2594 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002595 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002596 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002597 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002598 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002599 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002600 break;
2601 }
2602 case 'S':
2603 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002604 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002605 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002606 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002607 /* unused, since we already have the result */
2608 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002609 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002610 copy_characters(string, i, *callresult, 0, size);
2611 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002612 /* We're done with the unicode()/repr() => forget it */
2613 Py_DECREF(*callresult);
2614 /* switch to next unicode()/repr() result */
2615 ++callresult;
2616 break;
2617 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002618 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002619 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002620 break;
2621 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002622 for (; *p; ++p, ++i)
2623 PyUnicode_WRITE(kind, data, i, *p);
2624 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002625 goto end;
2626 }
Victor Stinner1205f272010-09-11 00:54:47 +00002627 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002628 else {
2629 assert(i < PyUnicode_GET_LENGTH(string));
2630 PyUnicode_WRITE(kind, data, i++, *f);
2631 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002632 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002633 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002634
Benjamin Peterson29060642009-01-31 22:14:21 +00002635 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002636 if (callresults)
2637 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002638 if (numberresults)
2639 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002640 assert(_PyUnicode_CheckConsistency(string, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01002641 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002642 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002643 if (callresults) {
2644 PyObject **callresult2 = callresults;
2645 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002646 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002647 ++callresult2;
2648 }
2649 PyObject_Free(callresults);
2650 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002651 if (numberresults)
2652 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002653 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002654}
2655
Walter Dörwaldd2034312007-05-18 16:29:38 +00002656PyObject *
2657PyUnicode_FromFormat(const char *format, ...)
2658{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002659 PyObject* ret;
2660 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002661
2662#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002663 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002664#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002665 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002666#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002667 ret = PyUnicode_FromFormatV(format, vargs);
2668 va_end(vargs);
2669 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002670}
2671
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002672#ifdef HAVE_WCHAR_H
2673
Victor Stinner5593d8a2010-10-02 11:11:27 +00002674/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2675 convert a Unicode object to a wide character string.
2676
Victor Stinnerd88d9832011-09-06 02:00:05 +02002677 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002678 character) required to convert the unicode object. Ignore size argument.
2679
Victor Stinnerd88d9832011-09-06 02:00:05 +02002680 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002681 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002682 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002683static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002684unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002685 wchar_t *w,
2686 Py_ssize_t size)
2687{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002688 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002689 const wchar_t *wstr;
2690
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002691 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002692 if (wstr == NULL)
2693 return -1;
2694
Victor Stinner5593d8a2010-10-02 11:11:27 +00002695 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002696 if (size > res)
2697 size = res + 1;
2698 else
2699 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002700 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002701 return res;
2702 }
2703 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002704 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002705}
2706
2707Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002708PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002709 wchar_t *w,
2710 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002711{
2712 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002713 PyErr_BadInternalCall();
2714 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002715 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002716 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002717}
2718
Victor Stinner137c34c2010-09-29 10:25:54 +00002719wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002720PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002721 Py_ssize_t *size)
2722{
2723 wchar_t* buffer;
2724 Py_ssize_t buflen;
2725
2726 if (unicode == NULL) {
2727 PyErr_BadInternalCall();
2728 return NULL;
2729 }
2730
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002731 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002732 if (buflen == -1)
2733 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002734 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002735 PyErr_NoMemory();
2736 return NULL;
2737 }
2738
Victor Stinner137c34c2010-09-29 10:25:54 +00002739 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2740 if (buffer == NULL) {
2741 PyErr_NoMemory();
2742 return NULL;
2743 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002744 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002745 if (buflen == -1)
2746 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002747 if (size != NULL)
2748 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002749 return buffer;
2750}
2751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002752#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002753
Alexander Belopolsky40018472011-02-26 01:02:56 +00002754PyObject *
2755PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002756{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002757 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002758 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002759 PyErr_SetString(PyExc_ValueError,
2760 "chr() arg not in range(0x110000)");
2761 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002762 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002763
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002764 if (ordinal < 256)
2765 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002767 v = PyUnicode_New(1, ordinal);
2768 if (v == NULL)
2769 return NULL;
2770 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002771 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002772 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002773}
2774
Alexander Belopolsky40018472011-02-26 01:02:56 +00002775PyObject *
2776PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002777{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002778 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002779 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002780 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002781 if (PyUnicode_READY(obj))
2782 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002783 Py_INCREF(obj);
2784 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002785 }
2786 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002787 /* For a Unicode subtype that's not a Unicode object,
2788 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002789 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002790 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002791 PyErr_Format(PyExc_TypeError,
2792 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002793 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002794 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002795}
2796
Alexander Belopolsky40018472011-02-26 01:02:56 +00002797PyObject *
2798PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002799 const char *encoding,
2800 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002801{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002802 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002803 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002804
Guido van Rossumd57fd912000-03-10 22:53:23 +00002805 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002806 PyErr_BadInternalCall();
2807 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002808 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002809
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002810 /* Decoding bytes objects is the most common case and should be fast */
2811 if (PyBytes_Check(obj)) {
2812 if (PyBytes_GET_SIZE(obj) == 0) {
2813 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002814 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002815 }
2816 else {
2817 v = PyUnicode_Decode(
2818 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2819 encoding, errors);
2820 }
2821 return v;
2822 }
2823
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002824 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002825 PyErr_SetString(PyExc_TypeError,
2826 "decoding str is not supported");
2827 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002828 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002829
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002830 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2831 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2832 PyErr_Format(PyExc_TypeError,
2833 "coercing to str: need bytes, bytearray "
2834 "or buffer-like object, %.80s found",
2835 Py_TYPE(obj)->tp_name);
2836 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002837 }
Tim Petersced69f82003-09-16 20:30:58 +00002838
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002839 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002840 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002841 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002842 }
Tim Petersced69f82003-09-16 20:30:58 +00002843 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002844 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002845
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002846 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002847 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002848}
2849
Victor Stinner600d3be2010-06-10 12:00:55 +00002850/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002851 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2852 1 on success. */
2853static int
2854normalize_encoding(const char *encoding,
2855 char *lower,
2856 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002857{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002858 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002859 char *l;
2860 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002861
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002862 if (encoding == NULL) {
2863 strcpy(lower, "utf-8");
2864 return 1;
2865 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002866 e = encoding;
2867 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002868 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002869 while (*e) {
2870 if (l == l_end)
2871 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002872 if (Py_ISUPPER(*e)) {
2873 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002874 }
2875 else if (*e == '_') {
2876 *l++ = '-';
2877 e++;
2878 }
2879 else {
2880 *l++ = *e++;
2881 }
2882 }
2883 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002884 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002885}
2886
Alexander Belopolsky40018472011-02-26 01:02:56 +00002887PyObject *
2888PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002889 Py_ssize_t size,
2890 const char *encoding,
2891 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002892{
2893 PyObject *buffer = NULL, *unicode;
2894 Py_buffer info;
2895 char lower[11]; /* Enough for any encoding shortcut */
2896
Fred Drakee4315f52000-05-09 19:53:39 +00002897 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002898 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002899 if ((strcmp(lower, "utf-8") == 0) ||
2900 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002901 return PyUnicode_DecodeUTF8(s, size, errors);
2902 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002903 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002904 (strcmp(lower, "iso-8859-1") == 0))
2905 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002906#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002907 else if (strcmp(lower, "mbcs") == 0)
2908 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002909#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002910 else if (strcmp(lower, "ascii") == 0)
2911 return PyUnicode_DecodeASCII(s, size, errors);
2912 else if (strcmp(lower, "utf-16") == 0)
2913 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2914 else if (strcmp(lower, "utf-32") == 0)
2915 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2916 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002917
2918 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002919 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002920 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002921 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002922 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002923 if (buffer == NULL)
2924 goto onError;
2925 unicode = PyCodec_Decode(buffer, encoding, errors);
2926 if (unicode == NULL)
2927 goto onError;
2928 if (!PyUnicode_Check(unicode)) {
2929 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002930 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002931 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002932 Py_DECREF(unicode);
2933 goto onError;
2934 }
2935 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002936#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002937 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002938 Py_DECREF(unicode);
2939 return NULL;
2940 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002941#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002942 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002943 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002944
Benjamin Peterson29060642009-01-31 22:14:21 +00002945 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002946 Py_XDECREF(buffer);
2947 return NULL;
2948}
2949
Alexander Belopolsky40018472011-02-26 01:02:56 +00002950PyObject *
2951PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002952 const char *encoding,
2953 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002954{
2955 PyObject *v;
2956
2957 if (!PyUnicode_Check(unicode)) {
2958 PyErr_BadArgument();
2959 goto onError;
2960 }
2961
2962 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002963 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002964
2965 /* Decode via the codec registry */
2966 v = PyCodec_Decode(unicode, encoding, errors);
2967 if (v == NULL)
2968 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002969 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002970 return v;
2971
Benjamin Peterson29060642009-01-31 22:14:21 +00002972 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002973 return NULL;
2974}
2975
Alexander Belopolsky40018472011-02-26 01:02:56 +00002976PyObject *
2977PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002978 const char *encoding,
2979 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002980{
2981 PyObject *v;
2982
2983 if (!PyUnicode_Check(unicode)) {
2984 PyErr_BadArgument();
2985 goto onError;
2986 }
2987
2988 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002989 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002990
2991 /* Decode via the codec registry */
2992 v = PyCodec_Decode(unicode, encoding, errors);
2993 if (v == NULL)
2994 goto onError;
2995 if (!PyUnicode_Check(v)) {
2996 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002997 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002998 Py_TYPE(v)->tp_name);
2999 Py_DECREF(v);
3000 goto onError;
3001 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003002 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003003 return v;
3004
Benjamin Peterson29060642009-01-31 22:14:21 +00003005 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003006 return NULL;
3007}
3008
Alexander Belopolsky40018472011-02-26 01:02:56 +00003009PyObject *
3010PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003011 Py_ssize_t size,
3012 const char *encoding,
3013 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003014{
3015 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003016
Guido van Rossumd57fd912000-03-10 22:53:23 +00003017 unicode = PyUnicode_FromUnicode(s, size);
3018 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003019 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003020 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3021 Py_DECREF(unicode);
3022 return v;
3023}
3024
Alexander Belopolsky40018472011-02-26 01:02:56 +00003025PyObject *
3026PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003027 const char *encoding,
3028 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003029{
3030 PyObject *v;
3031
3032 if (!PyUnicode_Check(unicode)) {
3033 PyErr_BadArgument();
3034 goto onError;
3035 }
3036
3037 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003038 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003039
3040 /* Encode via the codec registry */
3041 v = PyCodec_Encode(unicode, encoding, errors);
3042 if (v == NULL)
3043 goto onError;
3044 return v;
3045
Benjamin Peterson29060642009-01-31 22:14:21 +00003046 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003047 return NULL;
3048}
3049
Victor Stinnerad158722010-10-27 00:25:46 +00003050PyObject *
3051PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003052{
Victor Stinner99b95382011-07-04 14:23:54 +02003053#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003054 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3055 PyUnicode_GET_SIZE(unicode),
3056 NULL);
3057#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003058 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003059#else
Victor Stinner793b5312011-04-27 00:24:21 +02003060 PyInterpreterState *interp = PyThreadState_GET()->interp;
3061 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3062 cannot use it to encode and decode filenames before it is loaded. Load
3063 the Python codec requires to encode at least its own filename. Use the C
3064 version of the locale codec until the codec registry is initialized and
3065 the Python codec is loaded.
3066
3067 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3068 cannot only rely on it: check also interp->fscodec_initialized for
3069 subinterpreters. */
3070 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003071 return PyUnicode_AsEncodedString(unicode,
3072 Py_FileSystemDefaultEncoding,
3073 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003074 }
3075 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003076 /* locale encoding with surrogateescape */
3077 wchar_t *wchar;
3078 char *bytes;
3079 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003080 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003081
3082 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3083 if (wchar == NULL)
3084 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003085 bytes = _Py_wchar2char(wchar, &error_pos);
3086 if (bytes == NULL) {
3087 if (error_pos != (size_t)-1) {
3088 char *errmsg = strerror(errno);
3089 PyObject *exc = NULL;
3090 if (errmsg == NULL)
3091 errmsg = "Py_wchar2char() failed";
3092 raise_encode_exception(&exc,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01003093 "filesystemencoding", unicode,
Victor Stinner2f02a512010-11-08 22:43:46 +00003094 error_pos, error_pos+1,
3095 errmsg);
3096 Py_XDECREF(exc);
3097 }
3098 else
3099 PyErr_NoMemory();
3100 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003101 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003102 }
3103 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003104
3105 bytes_obj = PyBytes_FromString(bytes);
3106 PyMem_Free(bytes);
3107 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003108 }
Victor Stinnerad158722010-10-27 00:25:46 +00003109#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003110}
3111
Alexander Belopolsky40018472011-02-26 01:02:56 +00003112PyObject *
3113PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003114 const char *encoding,
3115 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003116{
3117 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003118 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003119
Guido van Rossumd57fd912000-03-10 22:53:23 +00003120 if (!PyUnicode_Check(unicode)) {
3121 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003122 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003123 }
Fred Drakee4315f52000-05-09 19:53:39 +00003124
Fred Drakee4315f52000-05-09 19:53:39 +00003125 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003126 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003127 if ((strcmp(lower, "utf-8") == 0) ||
3128 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003129 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003130 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003131 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003132 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003133 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003134 }
Victor Stinner37296e82010-06-10 13:36:23 +00003135 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003136 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003137 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003138 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003139#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003140 else if (strcmp(lower, "mbcs") == 0)
3141 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3142 PyUnicode_GET_SIZE(unicode),
3143 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003144#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003145 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003146 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003147 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003148
3149 /* Encode via the codec registry */
3150 v = PyCodec_Encode(unicode, encoding, errors);
3151 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003152 return NULL;
3153
3154 /* The normal path */
3155 if (PyBytes_Check(v))
3156 return v;
3157
3158 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003159 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003160 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003161 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003162
3163 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3164 "encoder %s returned bytearray instead of bytes",
3165 encoding);
3166 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003167 Py_DECREF(v);
3168 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003169 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003170
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003171 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3172 Py_DECREF(v);
3173 return b;
3174 }
3175
3176 PyErr_Format(PyExc_TypeError,
3177 "encoder did not return a bytes object (type=%.400s)",
3178 Py_TYPE(v)->tp_name);
3179 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003180 return NULL;
3181}
3182
Alexander Belopolsky40018472011-02-26 01:02:56 +00003183PyObject *
3184PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003185 const char *encoding,
3186 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003187{
3188 PyObject *v;
3189
3190 if (!PyUnicode_Check(unicode)) {
3191 PyErr_BadArgument();
3192 goto onError;
3193 }
3194
3195 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003196 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003197
3198 /* Encode via the codec registry */
3199 v = PyCodec_Encode(unicode, encoding, errors);
3200 if (v == NULL)
3201 goto onError;
3202 if (!PyUnicode_Check(v)) {
3203 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003204 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003205 Py_TYPE(v)->tp_name);
3206 Py_DECREF(v);
3207 goto onError;
3208 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003209 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003210
Benjamin Peterson29060642009-01-31 22:14:21 +00003211 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003212 return NULL;
3213}
3214
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003215PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003216PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003217 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003218 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3219}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003220
Christian Heimes5894ba72007-11-04 11:43:14 +00003221PyObject*
3222PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3223{
Victor Stinner99b95382011-07-04 14:23:54 +02003224#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003225 return PyUnicode_DecodeMBCS(s, size, NULL);
3226#elif defined(__APPLE__)
3227 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3228#else
Victor Stinner793b5312011-04-27 00:24:21 +02003229 PyInterpreterState *interp = PyThreadState_GET()->interp;
3230 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3231 cannot use it to encode and decode filenames before it is loaded. Load
3232 the Python codec requires to encode at least its own filename. Use the C
3233 version of the locale codec until the codec registry is initialized and
3234 the Python codec is loaded.
3235
3236 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3237 cannot only rely on it: check also interp->fscodec_initialized for
3238 subinterpreters. */
3239 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003240 return PyUnicode_Decode(s, size,
3241 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003242 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003243 }
3244 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003245 /* locale encoding with surrogateescape */
3246 wchar_t *wchar;
3247 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003248 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003249
3250 if (s[size] != '\0' || size != strlen(s)) {
3251 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3252 return NULL;
3253 }
3254
Victor Stinner168e1172010-10-16 23:16:16 +00003255 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003256 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003257 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003258
Victor Stinner168e1172010-10-16 23:16:16 +00003259 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003260 PyMem_Free(wchar);
3261 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003262 }
Victor Stinnerad158722010-10-27 00:25:46 +00003263#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003264}
3265
Martin v. Löwis011e8422009-05-05 04:43:17 +00003266
3267int
3268PyUnicode_FSConverter(PyObject* arg, void* addr)
3269{
3270 PyObject *output = NULL;
3271 Py_ssize_t size;
3272 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003273 if (arg == NULL) {
3274 Py_DECREF(*(PyObject**)addr);
3275 return 1;
3276 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003277 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003278 output = arg;
3279 Py_INCREF(output);
3280 }
3281 else {
3282 arg = PyUnicode_FromObject(arg);
3283 if (!arg)
3284 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003285 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003286 Py_DECREF(arg);
3287 if (!output)
3288 return 0;
3289 if (!PyBytes_Check(output)) {
3290 Py_DECREF(output);
3291 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3292 return 0;
3293 }
3294 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003295 size = PyBytes_GET_SIZE(output);
3296 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003297 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003298 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003299 Py_DECREF(output);
3300 return 0;
3301 }
3302 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003303 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003304}
3305
3306
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003307int
3308PyUnicode_FSDecoder(PyObject* arg, void* addr)
3309{
3310 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003311 if (arg == NULL) {
3312 Py_DECREF(*(PyObject**)addr);
3313 return 1;
3314 }
3315 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003316 if (PyUnicode_READY(arg))
3317 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003318 output = arg;
3319 Py_INCREF(output);
3320 }
3321 else {
3322 arg = PyBytes_FromObject(arg);
3323 if (!arg)
3324 return 0;
3325 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3326 PyBytes_GET_SIZE(arg));
3327 Py_DECREF(arg);
3328 if (!output)
3329 return 0;
3330 if (!PyUnicode_Check(output)) {
3331 Py_DECREF(output);
3332 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3333 return 0;
3334 }
3335 }
Victor Stinner065836e2011-10-27 01:56:33 +02003336 if (PyUnicode_READY(output) < 0) {
3337 Py_DECREF(output);
3338 return 0;
3339 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003340 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003341 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003342 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3343 Py_DECREF(output);
3344 return 0;
3345 }
3346 *(PyObject**)addr = output;
3347 return Py_CLEANUP_SUPPORTED;
3348}
3349
3350
Martin v. Löwis5b222132007-06-10 09:51:05 +00003351char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003352PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003353{
Christian Heimesf3863112007-11-22 07:46:41 +00003354 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003355
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003356 if (!PyUnicode_Check(unicode)) {
3357 PyErr_BadArgument();
3358 return NULL;
3359 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003360 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003361 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003362
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003363 if (PyUnicode_UTF8(unicode) == NULL) {
3364 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003365 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3366 if (bytes == NULL)
3367 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003368 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3369 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003370 Py_DECREF(bytes);
3371 return NULL;
3372 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003373 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3374 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3375 PyBytes_AS_STRING(bytes),
3376 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003377 Py_DECREF(bytes);
3378 }
3379
3380 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003381 *psize = PyUnicode_UTF8_LENGTH(unicode);
3382 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003383}
3384
3385char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003386PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003387{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003388 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3389}
3390
3391#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003392static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003393#endif
3394
3395
3396Py_UNICODE *
3397PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3398{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003399 const unsigned char *one_byte;
3400#if SIZEOF_WCHAR_T == 4
3401 const Py_UCS2 *two_bytes;
3402#else
3403 const Py_UCS4 *four_bytes;
3404 const Py_UCS4 *ucs4_end;
3405 Py_ssize_t num_surrogates;
3406#endif
3407 wchar_t *w;
3408 wchar_t *wchar_end;
3409
3410 if (!PyUnicode_Check(unicode)) {
3411 PyErr_BadArgument();
3412 return NULL;
3413 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003414 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003415 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003416 assert(_PyUnicode_KIND(unicode) != 0);
3417 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003418
3419#ifdef Py_DEBUG
3420 ++unicode_as_unicode_calls;
3421#endif
3422
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003423 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003424#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003425 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3426 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003427 num_surrogates = 0;
3428
3429 for (; four_bytes < ucs4_end; ++four_bytes) {
3430 if (*four_bytes > 0xFFFF)
3431 ++num_surrogates;
3432 }
3433
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003434 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3435 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3436 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003437 PyErr_NoMemory();
3438 return NULL;
3439 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003440 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003441
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003442 w = _PyUnicode_WSTR(unicode);
3443 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3444 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003445 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3446 if (*four_bytes > 0xFFFF) {
3447 /* encode surrogate pair in this case */
3448 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3449 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3450 }
3451 else
3452 *w = *four_bytes;
3453
3454 if (w > wchar_end) {
3455 assert(0 && "Miscalculated string end");
3456 }
3457 }
3458 *w = 0;
3459#else
3460 /* sizeof(wchar_t) == 4 */
3461 Py_FatalError("Impossible unicode object state, wstr and str "
3462 "should share memory already.");
3463 return NULL;
3464#endif
3465 }
3466 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003467 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3468 (_PyUnicode_LENGTH(unicode) + 1));
3469 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003470 PyErr_NoMemory();
3471 return NULL;
3472 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003473 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3474 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3475 w = _PyUnicode_WSTR(unicode);
3476 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003477
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003478 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3479 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003480 for (; w < wchar_end; ++one_byte, ++w)
3481 *w = *one_byte;
3482 /* null-terminate the wstr */
3483 *w = 0;
3484 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003485 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003486#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003487 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003488 for (; w < wchar_end; ++two_bytes, ++w)
3489 *w = *two_bytes;
3490 /* null-terminate the wstr */
3491 *w = 0;
3492#else
3493 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003494 PyObject_FREE(_PyUnicode_WSTR(unicode));
3495 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003496 Py_FatalError("Impossible unicode object state, wstr "
3497 "and str should share memory already.");
3498 return NULL;
3499#endif
3500 }
3501 else {
3502 assert(0 && "This should never happen.");
3503 }
3504 }
3505 }
3506 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003507 *size = PyUnicode_WSTR_LENGTH(unicode);
3508 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003509}
3510
Alexander Belopolsky40018472011-02-26 01:02:56 +00003511Py_UNICODE *
3512PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003513{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003514 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003515}
3516
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003517
Alexander Belopolsky40018472011-02-26 01:02:56 +00003518Py_ssize_t
3519PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003520{
3521 if (!PyUnicode_Check(unicode)) {
3522 PyErr_BadArgument();
3523 goto onError;
3524 }
3525 return PyUnicode_GET_SIZE(unicode);
3526
Benjamin Peterson29060642009-01-31 22:14:21 +00003527 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003528 return -1;
3529}
3530
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003531Py_ssize_t
3532PyUnicode_GetLength(PyObject *unicode)
3533{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003534 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003535 PyErr_BadArgument();
3536 return -1;
3537 }
3538
3539 return PyUnicode_GET_LENGTH(unicode);
3540}
3541
3542Py_UCS4
3543PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3544{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003545 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3546 PyErr_BadArgument();
3547 return (Py_UCS4)-1;
3548 }
3549 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3550 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003551 return (Py_UCS4)-1;
3552 }
3553 return PyUnicode_READ_CHAR(unicode, index);
3554}
3555
3556int
3557PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3558{
3559 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003560 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003561 return -1;
3562 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003563 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3564 PyErr_SetString(PyExc_IndexError, "string index out of range");
3565 return -1;
3566 }
3567 if (_PyUnicode_Dirty(unicode))
3568 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003569 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3570 index, ch);
3571 return 0;
3572}
3573
Alexander Belopolsky40018472011-02-26 01:02:56 +00003574const char *
3575PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003576{
Victor Stinner42cb4622010-09-01 19:39:01 +00003577 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003578}
3579
Victor Stinner554f3f02010-06-16 23:33:54 +00003580/* create or adjust a UnicodeDecodeError */
3581static void
3582make_decode_exception(PyObject **exceptionObject,
3583 const char *encoding,
3584 const char *input, Py_ssize_t length,
3585 Py_ssize_t startpos, Py_ssize_t endpos,
3586 const char *reason)
3587{
3588 if (*exceptionObject == NULL) {
3589 *exceptionObject = PyUnicodeDecodeError_Create(
3590 encoding, input, length, startpos, endpos, reason);
3591 }
3592 else {
3593 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3594 goto onError;
3595 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3596 goto onError;
3597 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3598 goto onError;
3599 }
3600 return;
3601
3602onError:
3603 Py_DECREF(*exceptionObject);
3604 *exceptionObject = NULL;
3605}
3606
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003607/* error handling callback helper:
3608 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003609 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003610 and adjust various state variables.
3611 return 0 on success, -1 on error
3612*/
3613
Alexander Belopolsky40018472011-02-26 01:02:56 +00003614static int
3615unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003616 const char *encoding, const char *reason,
3617 const char **input, const char **inend, Py_ssize_t *startinpos,
3618 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003619 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003620{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003621 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003622
3623 PyObject *restuple = NULL;
3624 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003625 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003626 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003627 Py_ssize_t requiredsize;
3628 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003629 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003630 int res = -1;
3631
Victor Stinner596a6c42011-11-09 00:02:18 +01003632 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
3633 outsize = PyUnicode_GET_LENGTH(*output);
3634 else
3635 outsize = _PyUnicode_WSTR_LENGTH(*output);
3636
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003637 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003638 *errorHandler = PyCodec_LookupError(errors);
3639 if (*errorHandler == NULL)
3640 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003641 }
3642
Victor Stinner554f3f02010-06-16 23:33:54 +00003643 make_decode_exception(exceptionObject,
3644 encoding,
3645 *input, *inend - *input,
3646 *startinpos, *endinpos,
3647 reason);
3648 if (*exceptionObject == NULL)
3649 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003650
3651 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3652 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003653 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003654 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003655 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003656 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003657 }
3658 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003659 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003660 if (PyUnicode_READY(repunicode) < 0)
3661 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003662
3663 /* Copy back the bytes variables, which might have been modified by the
3664 callback */
3665 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3666 if (!inputobj)
3667 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003668 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003669 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003670 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003671 *input = PyBytes_AS_STRING(inputobj);
3672 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003673 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003674 /* we can DECREF safely, as the exception has another reference,
3675 so the object won't go away. */
3676 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003677
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003678 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003679 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003680 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003681 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3682 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003683 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003684
Victor Stinner596a6c42011-11-09 00:02:18 +01003685 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
3686 /* need more space? (at least enough for what we
3687 have+the replacement+the rest of the string (starting
3688 at the new input position), so we won't have to check space
3689 when there are no errors in the rest of the string) */
3690 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
3691 requiredsize = *outpos + replen + insize-newpos;
3692 if (requiredsize > outsize) {
3693 if (requiredsize<2*outsize)
3694 requiredsize = 2*outsize;
3695 if (unicode_resize(output, requiredsize) < 0)
3696 goto onError;
3697 }
3698 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003699 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01003700 copy_characters(*output, *outpos, repunicode, 0, replen);
3701 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003702 }
Victor Stinner596a6c42011-11-09 00:02:18 +01003703 else {
3704 wchar_t *repwstr;
3705 Py_ssize_t repwlen;
3706 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
3707 if (repwstr == NULL)
3708 goto onError;
3709 /* need more space? (at least enough for what we
3710 have+the replacement+the rest of the string (starting
3711 at the new input position), so we won't have to check space
3712 when there are no errors in the rest of the string) */
3713 requiredsize = *outpos + repwlen + insize-newpos;
3714 if (requiredsize > outsize) {
3715 if (requiredsize < 2*outsize)
3716 requiredsize = 2*outsize;
3717 if (unicode_resize(output, requiredsize) < 0)
3718 goto onError;
3719 }
3720 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
3721 *outpos += repwlen;
3722 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003723 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003724 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003725
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003726 /* we made it! */
3727 res = 0;
3728
Benjamin Peterson29060642009-01-31 22:14:21 +00003729 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003730 Py_XDECREF(restuple);
3731 return res;
3732}
3733
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003734/* --- UTF-7 Codec -------------------------------------------------------- */
3735
Antoine Pitrou244651a2009-05-04 18:56:13 +00003736/* See RFC2152 for details. We encode conservatively and decode liberally. */
3737
3738/* Three simple macros defining base-64. */
3739
3740/* Is c a base-64 character? */
3741
3742#define IS_BASE64(c) \
3743 (((c) >= 'A' && (c) <= 'Z') || \
3744 ((c) >= 'a' && (c) <= 'z') || \
3745 ((c) >= '0' && (c) <= '9') || \
3746 (c) == '+' || (c) == '/')
3747
3748/* given that c is a base-64 character, what is its base-64 value? */
3749
3750#define FROM_BASE64(c) \
3751 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3752 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3753 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3754 (c) == '+' ? 62 : 63)
3755
3756/* What is the base-64 character of the bottom 6 bits of n? */
3757
3758#define TO_BASE64(n) \
3759 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3760
3761/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3762 * decoded as itself. We are permissive on decoding; the only ASCII
3763 * byte not decoding to itself is the + which begins a base64
3764 * string. */
3765
3766#define DECODE_DIRECT(c) \
3767 ((c) <= 127 && (c) != '+')
3768
3769/* The UTF-7 encoder treats ASCII characters differently according to
3770 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3771 * the above). See RFC2152. This array identifies these different
3772 * sets:
3773 * 0 : "Set D"
3774 * alphanumeric and '(),-./:?
3775 * 1 : "Set O"
3776 * !"#$%&*;<=>@[]^_`{|}
3777 * 2 : "whitespace"
3778 * ht nl cr sp
3779 * 3 : special (must be base64 encoded)
3780 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3781 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003782
Tim Petersced69f82003-09-16 20:30:58 +00003783static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003784char utf7_category[128] = {
3785/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3786 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3787/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3788 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3789/* sp ! " # $ % & ' ( ) * + , - . / */
3790 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3791/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3792 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3793/* @ A B C D E F G H I J K L M N O */
3794 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3795/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3796 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3797/* ` a b c d e f g h i j k l m n o */
3798 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3799/* p q r s t u v w x y z { | } ~ del */
3800 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003801};
3802
Antoine Pitrou244651a2009-05-04 18:56:13 +00003803/* ENCODE_DIRECT: this character should be encoded as itself. The
3804 * answer depends on whether we are encoding set O as itself, and also
3805 * on whether we are encoding whitespace as itself. RFC2152 makes it
3806 * clear that the answers to these questions vary between
3807 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003808
Antoine Pitrou244651a2009-05-04 18:56:13 +00003809#define ENCODE_DIRECT(c, directO, directWS) \
3810 ((c) < 128 && (c) > 0 && \
3811 ((utf7_category[(c)] == 0) || \
3812 (directWS && (utf7_category[(c)] == 2)) || \
3813 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003814
Alexander Belopolsky40018472011-02-26 01:02:56 +00003815PyObject *
3816PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003817 Py_ssize_t size,
3818 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003819{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003820 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3821}
3822
Antoine Pitrou244651a2009-05-04 18:56:13 +00003823/* The decoder. The only state we preserve is our read position,
3824 * i.e. how many characters we have consumed. So if we end in the
3825 * middle of a shift sequence we have to back off the read position
3826 * and the output to the beginning of the sequence, otherwise we lose
3827 * all the shift state (seen bits, number of bits seen, high
3828 * surrogate). */
3829
Alexander Belopolsky40018472011-02-26 01:02:56 +00003830PyObject *
3831PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003832 Py_ssize_t size,
3833 const char *errors,
3834 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003835{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003836 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003837 Py_ssize_t startinpos;
3838 Py_ssize_t endinpos;
3839 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003840 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003841 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003842 const char *errmsg = "";
3843 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003844 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003845 unsigned int base64bits = 0;
3846 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01003847 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003848 PyObject *errorHandler = NULL;
3849 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003850
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003851 /* Start off assuming it's all ASCII. Widen later as necessary. */
3852 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003853 if (!unicode)
3854 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003855 if (size == 0) {
3856 if (consumed)
3857 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003858 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003859 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003860
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003861 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003862 e = s + size;
3863
3864 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003865 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003866 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003867 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003868
Antoine Pitrou244651a2009-05-04 18:56:13 +00003869 if (inShift) { /* in a base-64 section */
3870 if (IS_BASE64(ch)) { /* consume a base-64 character */
3871 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3872 base64bits += 6;
3873 s++;
3874 if (base64bits >= 16) {
3875 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01003876 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00003877 base64bits -= 16;
3878 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3879 if (surrogate) {
3880 /* expecting a second surrogate */
3881 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003882 Py_UCS4 ch2 = (((surrogate & 0x3FF)<<10)
3883 | (outCh & 0x3FF)) + 0x10000;
3884 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
3885 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003886 surrogate = 0;
3887 }
3888 else {
3889 surrogate = 0;
3890 errmsg = "second surrogate missing";
3891 goto utf7Error;
3892 }
3893 }
3894 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3895 /* first surrogate */
3896 surrogate = outCh;
3897 }
3898 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3899 errmsg = "unexpected second surrogate";
3900 goto utf7Error;
3901 }
3902 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003903 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
3904 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003905 }
3906 }
3907 }
3908 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003909 inShift = 0;
3910 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003911 if (surrogate) {
3912 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003913 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003914 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003915 if (base64bits > 0) { /* left-over bits */
3916 if (base64bits >= 6) {
3917 /* We've seen at least one base-64 character */
3918 errmsg = "partial character in shift sequence";
3919 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003920 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003921 else {
3922 /* Some bits remain; they should be zero */
3923 if (base64buffer != 0) {
3924 errmsg = "non-zero padding bits in shift sequence";
3925 goto utf7Error;
3926 }
3927 }
3928 }
3929 if (ch != '-') {
3930 /* '-' is absorbed; other terminating
3931 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003932 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3933 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003934 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003935 }
3936 }
3937 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003938 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003939 s++; /* consume '+' */
3940 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003941 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003942 if (unicode_putchar(&unicode, &outpos, '+') < 0)
3943 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003944 }
3945 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003946 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003947 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003948 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003949 }
3950 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003951 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003952 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3953 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003954 s++;
3955 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003956 else {
3957 startinpos = s-starts;
3958 s++;
3959 errmsg = "unexpected special character";
3960 goto utf7Error;
3961 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003962 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003963utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003964 endinpos = s-starts;
3965 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003966 errors, &errorHandler,
3967 "utf7", errmsg,
3968 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003969 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003970 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003971 }
3972
Antoine Pitrou244651a2009-05-04 18:56:13 +00003973 /* end of string */
3974
3975 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3976 /* if we're in an inconsistent state, that's an error */
3977 if (surrogate ||
3978 (base64bits >= 6) ||
3979 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003980 endinpos = size;
3981 if (unicode_decode_call_errorhandler(
3982 errors, &errorHandler,
3983 "utf7", "unterminated shift sequence",
3984 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003985 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00003986 goto onError;
3987 if (s < e)
3988 goto restart;
3989 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003990 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003991
3992 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003993 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003994 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003995 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003996 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003997 }
3998 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003999 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004000 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004001 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004002
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004003 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004004 goto onError;
4005
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004006 Py_XDECREF(errorHandler);
4007 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004008#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004009 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004010 Py_DECREF(unicode);
4011 return NULL;
4012 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004013#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004014 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004015 return unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004016
Benjamin Peterson29060642009-01-31 22:14:21 +00004017 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004018 Py_XDECREF(errorHandler);
4019 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004020 Py_DECREF(unicode);
4021 return NULL;
4022}
4023
4024
Alexander Belopolsky40018472011-02-26 01:02:56 +00004025PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004026_PyUnicode_EncodeUTF7(PyObject *str,
4027 int base64SetO,
4028 int base64WhiteSpace,
4029 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004030{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004031 int kind;
4032 void *data;
4033 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004034 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004035 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004036 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004037 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004038 unsigned int base64bits = 0;
4039 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004040 char * out;
4041 char * start;
4042
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004043 if (PyUnicode_READY(str) < 0)
4044 return NULL;
4045 kind = PyUnicode_KIND(str);
4046 data = PyUnicode_DATA(str);
4047 len = PyUnicode_GET_LENGTH(str);
4048
4049 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004050 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004051
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004052 /* It might be possible to tighten this worst case */
4053 allocated = 8 * len;
4054 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004055 return PyErr_NoMemory();
4056
Antoine Pitrou244651a2009-05-04 18:56:13 +00004057 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004058 if (v == NULL)
4059 return NULL;
4060
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004061 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004062 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004063 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004064
Antoine Pitrou244651a2009-05-04 18:56:13 +00004065 if (inShift) {
4066 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4067 /* shifting out */
4068 if (base64bits) { /* output remaining bits */
4069 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4070 base64buffer = 0;
4071 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004072 }
4073 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004074 /* Characters not in the BASE64 set implicitly unshift the sequence
4075 so no '-' is required, except if the character is itself a '-' */
4076 if (IS_BASE64(ch) || ch == '-') {
4077 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004078 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004079 *out++ = (char) ch;
4080 }
4081 else {
4082 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004083 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004084 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004085 else { /* not in a shift sequence */
4086 if (ch == '+') {
4087 *out++ = '+';
4088 *out++ = '-';
4089 }
4090 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4091 *out++ = (char) ch;
4092 }
4093 else {
4094 *out++ = '+';
4095 inShift = 1;
4096 goto encode_char;
4097 }
4098 }
4099 continue;
4100encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004101 if (ch >= 0x10000) {
4102 /* code first surrogate */
4103 base64bits += 16;
4104 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4105 while (base64bits >= 6) {
4106 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4107 base64bits -= 6;
4108 }
4109 /* prepare second surrogate */
4110 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4111 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004112 base64bits += 16;
4113 base64buffer = (base64buffer << 16) | ch;
4114 while (base64bits >= 6) {
4115 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4116 base64bits -= 6;
4117 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004118 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004119 if (base64bits)
4120 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4121 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004122 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004123 if (_PyBytes_Resize(&v, out - start) < 0)
4124 return NULL;
4125 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004126}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004127PyObject *
4128PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4129 Py_ssize_t size,
4130 int base64SetO,
4131 int base64WhiteSpace,
4132 const char *errors)
4133{
4134 PyObject *result;
4135 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4136 if (tmp == NULL)
4137 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004138 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004139 base64WhiteSpace, errors);
4140 Py_DECREF(tmp);
4141 return result;
4142}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004143
Antoine Pitrou244651a2009-05-04 18:56:13 +00004144#undef IS_BASE64
4145#undef FROM_BASE64
4146#undef TO_BASE64
4147#undef DECODE_DIRECT
4148#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004149
Guido van Rossumd57fd912000-03-10 22:53:23 +00004150/* --- UTF-8 Codec -------------------------------------------------------- */
4151
Tim Petersced69f82003-09-16 20:30:58 +00004152static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004153char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004154 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4155 illegal prefix. See RFC 3629 for details */
4156 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4157 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004158 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004159 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4160 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4161 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4162 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004163 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4164 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 +00004165 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4166 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004167 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4168 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4169 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4170 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4171 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 +00004172};
4173
Alexander Belopolsky40018472011-02-26 01:02:56 +00004174PyObject *
4175PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004176 Py_ssize_t size,
4177 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004178{
Walter Dörwald69652032004-09-07 20:24:22 +00004179 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4180}
4181
Antoine Pitrouab868312009-01-10 15:40:25 +00004182/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4183#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4184
4185/* Mask to quickly check whether a C 'long' contains a
4186 non-ASCII, UTF8-encoded char. */
4187#if (SIZEOF_LONG == 8)
4188# define ASCII_CHAR_MASK 0x8080808080808080L
4189#elif (SIZEOF_LONG == 4)
4190# define ASCII_CHAR_MASK 0x80808080L
4191#else
4192# error C 'long' size should be either 4 or 8!
4193#endif
4194
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004195/* Scans a UTF-8 string and returns the maximum character to be expected,
4196 the size of the decoded unicode string and if any major errors were
4197 encountered.
4198
4199 This function does check basic UTF-8 sanity, it does however NOT CHECK
4200 if the string contains surrogates, and if all continuation bytes are
4201 within the correct ranges, these checks are performed in
4202 PyUnicode_DecodeUTF8Stateful.
4203
4204 If it sets has_errors to 1, it means the value of unicode_size and max_char
4205 will be bogus and you should not rely on useful information in them.
4206 */
4207static Py_UCS4
4208utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4209 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4210 int *has_errors)
4211{
4212 Py_ssize_t n;
4213 Py_ssize_t char_count = 0;
4214 Py_UCS4 max_char = 127, new_max;
4215 Py_UCS4 upper_bound;
4216 const unsigned char *p = (const unsigned char *)s;
4217 const unsigned char *end = p + string_size;
4218 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4219 int err = 0;
4220
4221 for (; p < end && !err; ++p, ++char_count) {
4222 /* Only check value if it's not a ASCII char... */
4223 if (*p < 0x80) {
4224 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4225 an explanation. */
4226 if (!((size_t) p & LONG_PTR_MASK)) {
4227 /* Help register allocation */
4228 register const unsigned char *_p = p;
4229 while (_p < aligned_end) {
4230 unsigned long value = *(unsigned long *) _p;
4231 if (value & ASCII_CHAR_MASK)
4232 break;
4233 _p += SIZEOF_LONG;
4234 char_count += SIZEOF_LONG;
4235 }
4236 p = _p;
4237 if (p == end)
4238 break;
4239 }
4240 }
4241 if (*p >= 0x80) {
4242 n = utf8_code_length[*p];
4243 new_max = max_char;
4244 switch (n) {
4245 /* invalid start byte */
4246 case 0:
4247 err = 1;
4248 break;
4249 case 2:
4250 /* Code points between 0x00FF and 0x07FF inclusive.
4251 Approximate the upper bound of the code point,
4252 if this flips over 255 we can be sure it will be more
4253 than 255 and the string will need 2 bytes per code coint,
4254 if it stays under or equal to 255, we can be sure 1 byte
4255 is enough.
4256 ((*p & 0b00011111) << 6) | 0b00111111 */
4257 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4258 if (max_char < upper_bound)
4259 new_max = upper_bound;
4260 /* Ensure we track at least that we left ASCII space. */
4261 if (new_max < 128)
4262 new_max = 128;
4263 break;
4264 case 3:
4265 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4266 always > 255 and <= 65535 and will always need 2 bytes. */
4267 if (max_char < 65535)
4268 new_max = 65535;
4269 break;
4270 case 4:
4271 /* Code point will be above 0xFFFF for sure in this case. */
4272 new_max = 65537;
4273 break;
4274 /* Internal error, this should be caught by the first if */
4275 case 1:
4276 default:
4277 assert(0 && "Impossible case in utf8_max_char_and_size");
4278 err = 1;
4279 }
4280 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004281 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004282 --n;
4283 /* Check if the follow up chars are all valid continuation bytes */
4284 if (n >= 1) {
4285 const unsigned char *cont;
4286 if ((p + n) >= end) {
4287 if (consumed == 0)
4288 /* incomplete data, non-incremental decoding */
4289 err = 1;
4290 break;
4291 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004292 for (cont = p + 1; cont <= (p + n); ++cont) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004293 if ((*cont & 0xc0) != 0x80) {
4294 err = 1;
4295 break;
4296 }
4297 }
4298 p += n;
4299 }
4300 else
4301 err = 1;
4302 max_char = new_max;
4303 }
4304 }
4305
4306 if (unicode_size)
4307 *unicode_size = char_count;
4308 if (has_errors)
4309 *has_errors = err;
4310 return max_char;
4311}
4312
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004313/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
4314 in case of errors. Implicit parameters: unicode, kind, data, has_errors,
4315 onError. Potential resizing overallocates, so the result needs to shrink
4316 at the end.
4317*/
4318#define WRITE_MAYBE_FAIL(index, value) \
4319 do { \
4320 if (has_errors) { \
4321 Py_ssize_t pos = index; \
4322 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4323 unicode_resize(&unicode, pos + pos/8) < 0) \
4324 goto onError; \
4325 if (unicode_putchar(&unicode, &pos, value) < 0) \
4326 goto onError; \
4327 } \
4328 else \
4329 PyUnicode_WRITE(kind, data, index, value); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004330 } while (0)
4331
Alexander Belopolsky40018472011-02-26 01:02:56 +00004332PyObject *
4333PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004334 Py_ssize_t size,
4335 const char *errors,
4336 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004337{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004338 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004339 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004340 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004341 Py_ssize_t startinpos;
4342 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004343 const char *e, *aligned_end;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004344 PyObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004345 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004346 PyObject *errorHandler = NULL;
4347 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004348 Py_UCS4 maxchar = 0;
4349 Py_ssize_t unicode_size;
4350 Py_ssize_t i;
4351 int kind;
4352 void *data;
4353 int has_errors;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004354
Walter Dörwald69652032004-09-07 20:24:22 +00004355 if (size == 0) {
4356 if (consumed)
4357 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004358 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004359 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004360 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4361 consumed, &has_errors);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004362 if (has_errors)
Victor Stinner62aa4d02011-11-09 00:03:45 +01004363 /* maxchar and size computation might be incorrect;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004364 code below widens and resizes as necessary. */
4365 unicode = PyUnicode_New(size, 127);
4366 else
Victor Stinner7931d9a2011-11-04 00:22:48 +01004367 unicode = PyUnicode_New(unicode_size, maxchar);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004368 if (!unicode)
4369 return NULL;
4370 /* When the string is ASCII only, just use memcpy and return.
4371 unicode_size may be != size if there is an incomplete UTF-8
4372 sequence at the end of the ASCII block. */
4373 if (!has_errors && maxchar < 128 && size == unicode_size) {
4374 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4375 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004376 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004377 kind = PyUnicode_KIND(unicode);
4378 data = PyUnicode_DATA(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004379 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004380 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004381 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004382 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004383
4384 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004385 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004386
4387 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004388 /* Fast path for runs of ASCII characters. Given that common UTF-8
4389 input will consist of an overwhelming majority of ASCII
4390 characters, we try to optimize for this case by checking
4391 as many characters as a C 'long' can contain.
4392 First, check if we can do an aligned read, as most CPUs have
4393 a penalty for unaligned reads.
4394 */
4395 if (!((size_t) s & LONG_PTR_MASK)) {
4396 /* Help register allocation */
4397 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004398 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004399 while (_s < aligned_end) {
4400 /* Read a whole long at a time (either 4 or 8 bytes),
4401 and do a fast unrolled copy if it only contains ASCII
4402 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004403 unsigned long value = *(unsigned long *) _s;
4404 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004405 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004406 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4407 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4408 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4409 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004410#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004411 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4412 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4413 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4414 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004415#endif
4416 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004417 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004418 }
4419 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004420 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004421 if (s == e)
4422 break;
4423 ch = (unsigned char)*s;
4424 }
4425 }
4426
4427 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004428 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004429 s++;
4430 continue;
4431 }
4432
4433 n = utf8_code_length[ch];
4434
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004435 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004436 if (consumed)
4437 break;
4438 else {
4439 errmsg = "unexpected end of data";
4440 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004441 endinpos = startinpos+1;
4442 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4443 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004444 goto utf8Error;
4445 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004446 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004447
4448 switch (n) {
4449
4450 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004451 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004452 startinpos = s-starts;
4453 endinpos = startinpos+1;
4454 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004455
4456 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004457 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004458 startinpos = s-starts;
4459 endinpos = startinpos+1;
4460 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004461
4462 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004463 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004464 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004465 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004466 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004467 goto utf8Error;
4468 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004469 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004470 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004471 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004472 break;
4473
4474 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004475 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4476 will result in surrogates in range d800-dfff. Surrogates are
4477 not valid UTF-8 so they are rejected.
4478 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4479 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004480 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004481 (s[2] & 0xc0) != 0x80 ||
4482 ((unsigned char)s[0] == 0xE0 &&
4483 (unsigned char)s[1] < 0xA0) ||
4484 ((unsigned char)s[0] == 0xED &&
4485 (unsigned char)s[1] > 0x9F)) {
4486 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004487 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004488 endinpos = startinpos + 1;
4489
4490 /* if s[1] first two bits are 1 and 0, then the invalid
4491 continuation byte is s[2], so increment endinpos by 1,
4492 if not, s[1] is invalid and endinpos doesn't need to
4493 be incremented. */
4494 if ((s[1] & 0xC0) == 0x80)
4495 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004496 goto utf8Error;
4497 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004498 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004499 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004500 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004501 break;
4502
4503 case 4:
4504 if ((s[1] & 0xc0) != 0x80 ||
4505 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004506 (s[3] & 0xc0) != 0x80 ||
4507 ((unsigned char)s[0] == 0xF0 &&
4508 (unsigned char)s[1] < 0x90) ||
4509 ((unsigned char)s[0] == 0xF4 &&
4510 (unsigned char)s[1] > 0x8F)) {
4511 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004512 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004513 endinpos = startinpos + 1;
4514 if ((s[1] & 0xC0) == 0x80) {
4515 endinpos++;
4516 if ((s[2] & 0xC0) == 0x80)
4517 endinpos++;
4518 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004519 goto utf8Error;
4520 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004521 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004522 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4523 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4524
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004525 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004526 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004527 }
4528 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004529 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004530
Benjamin Peterson29060642009-01-31 22:14:21 +00004531 utf8Error:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004532 if (!has_errors) {
4533 PyObject *tmp;
4534 Py_ssize_t k;
4535 /* We encountered some error that wasn't detected in the original scan,
4536 e.g. an encoded surrogate character. The original maxchar computation may
4537 have been incorrect, so redo it now. */
4538 for (k = 0, maxchar = 0; k < i; k++)
4539 maxchar = Py_MAX(maxchar, PyUnicode_READ(kind, data, k));
4540 tmp = PyUnicode_New(PyUnicode_GET_LENGTH(unicode), maxchar);
4541 if (tmp == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004542 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004543 PyUnicode_CopyCharacters(tmp, 0, unicode, 0, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004544 Py_DECREF(unicode);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004545 unicode = tmp;
4546 has_errors = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004547 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004548 if (unicode_decode_call_errorhandler(
4549 errors, &errorHandler,
4550 "utf8", errmsg,
4551 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004552 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004553 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004554 /* Update data because unicode_decode_call_errorhandler might have
4555 re-created or resized the unicode object. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004556 data = PyUnicode_DATA(unicode);
4557 kind = PyUnicode_KIND(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004558 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004559 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004560 /* Ensure the unicode_size calculation above was correct: */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004561 assert(has_errors || i == unicode_size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004562
Walter Dörwald69652032004-09-07 20:24:22 +00004563 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004564 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004565
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004566 /* Adjust length and ready string when it contained errors and
4567 is of the old resizable kind. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004568 if (has_errors) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004569 if (PyUnicode_Resize(&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004570 goto onError;
4571 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004572
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004573 Py_XDECREF(errorHandler);
4574 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004575 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004576 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004577
Benjamin Peterson29060642009-01-31 22:14:21 +00004578 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004579 Py_XDECREF(errorHandler);
4580 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004581 Py_DECREF(unicode);
4582 return NULL;
4583}
4584
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004585#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004586
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004587#ifdef __APPLE__
4588
4589/* Simplified UTF-8 decoder using surrogateescape error handler,
4590 used to decode the command line arguments on Mac OS X. */
4591
4592wchar_t*
4593_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4594{
4595 int n;
4596 const char *e;
4597 wchar_t *unicode, *p;
4598
4599 /* Note: size will always be longer than the resulting Unicode
4600 character count */
4601 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4602 PyErr_NoMemory();
4603 return NULL;
4604 }
4605 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4606 if (!unicode)
4607 return NULL;
4608
4609 /* Unpack UTF-8 encoded data */
4610 p = unicode;
4611 e = s + size;
4612 while (s < e) {
4613 Py_UCS4 ch = (unsigned char)*s;
4614
4615 if (ch < 0x80) {
4616 *p++ = (wchar_t)ch;
4617 s++;
4618 continue;
4619 }
4620
4621 n = utf8_code_length[ch];
4622 if (s + n > e) {
4623 goto surrogateescape;
4624 }
4625
4626 switch (n) {
4627 case 0:
4628 case 1:
4629 goto surrogateescape;
4630
4631 case 2:
4632 if ((s[1] & 0xc0) != 0x80)
4633 goto surrogateescape;
4634 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4635 assert ((ch > 0x007F) && (ch <= 0x07FF));
4636 *p++ = (wchar_t)ch;
4637 break;
4638
4639 case 3:
4640 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4641 will result in surrogates in range d800-dfff. Surrogates are
4642 not valid UTF-8 so they are rejected.
4643 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4644 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4645 if ((s[1] & 0xc0) != 0x80 ||
4646 (s[2] & 0xc0) != 0x80 ||
4647 ((unsigned char)s[0] == 0xE0 &&
4648 (unsigned char)s[1] < 0xA0) ||
4649 ((unsigned char)s[0] == 0xED &&
4650 (unsigned char)s[1] > 0x9F)) {
4651
4652 goto surrogateescape;
4653 }
4654 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4655 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004656 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004657 break;
4658
4659 case 4:
4660 if ((s[1] & 0xc0) != 0x80 ||
4661 (s[2] & 0xc0) != 0x80 ||
4662 (s[3] & 0xc0) != 0x80 ||
4663 ((unsigned char)s[0] == 0xF0 &&
4664 (unsigned char)s[1] < 0x90) ||
4665 ((unsigned char)s[0] == 0xF4 &&
4666 (unsigned char)s[1] > 0x8F)) {
4667 goto surrogateescape;
4668 }
4669 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4670 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4671 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4672
4673#if SIZEOF_WCHAR_T == 4
4674 *p++ = (wchar_t)ch;
4675#else
4676 /* compute and append the two surrogates: */
4677
4678 /* translate from 10000..10FFFF to 0..FFFF */
4679 ch -= 0x10000;
4680
4681 /* high surrogate = top 10 bits added to D800 */
4682 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4683
4684 /* low surrogate = bottom 10 bits added to DC00 */
4685 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4686#endif
4687 break;
4688 }
4689 s += n;
4690 continue;
4691
4692 surrogateescape:
4693 *p++ = 0xDC00 + ch;
4694 s++;
4695 }
4696 *p = L'\0';
4697 return unicode;
4698}
4699
4700#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004701
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004702/* Primary internal function which creates utf8 encoded bytes objects.
4703
4704 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004705 and allocate exactly as much space needed at the end. Else allocate the
4706 maximum possible needed (4 result bytes per Unicode character), and return
4707 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004708*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004709PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004710_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004711{
Tim Peters602f7402002-04-27 18:03:26 +00004712#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004713
Guido van Rossum98297ee2007-11-06 21:34:58 +00004714 Py_ssize_t i; /* index into s of next input byte */
4715 PyObject *result; /* result string object */
4716 char *p; /* next free byte in output buffer */
4717 Py_ssize_t nallocated; /* number of result bytes allocated */
4718 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004719 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004720 PyObject *errorHandler = NULL;
4721 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004722 int kind;
4723 void *data;
4724 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004725
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004726 if (!PyUnicode_Check(unicode)) {
4727 PyErr_BadArgument();
4728 return NULL;
4729 }
4730
4731 if (PyUnicode_READY(unicode) == -1)
4732 return NULL;
4733
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004734 if (PyUnicode_UTF8(unicode))
4735 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4736 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004737
4738 kind = PyUnicode_KIND(unicode);
4739 data = PyUnicode_DATA(unicode);
4740 size = PyUnicode_GET_LENGTH(unicode);
4741
Tim Peters602f7402002-04-27 18:03:26 +00004742 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004743
Tim Peters602f7402002-04-27 18:03:26 +00004744 if (size <= MAX_SHORT_UNICHARS) {
4745 /* Write into the stack buffer; nallocated can't overflow.
4746 * At the end, we'll allocate exactly as much heap space as it
4747 * turns out we need.
4748 */
4749 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004750 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004751 p = stackbuf;
4752 }
4753 else {
4754 /* Overallocate on the heap, and give the excess back at the end. */
4755 nallocated = size * 4;
4756 if (nallocated / 4 != size) /* overflow! */
4757 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004758 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004759 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004760 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004761 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004762 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004763
Tim Peters602f7402002-04-27 18:03:26 +00004764 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004765 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004766
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004767 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004768 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004769 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004770
Guido van Rossumd57fd912000-03-10 22:53:23 +00004771 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004772 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004773 *p++ = (char)(0xc0 | (ch >> 6));
4774 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004775 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004776 Py_ssize_t newpos;
4777 PyObject *rep;
4778 Py_ssize_t repsize, k, startpos;
4779 startpos = i-1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004780 rep = unicode_encode_call_errorhandler(
4781 errors, &errorHandler, "utf-8", "surrogates not allowed",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004782 unicode, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004783 if (!rep)
4784 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004785
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004786 if (PyBytes_Check(rep))
4787 repsize = PyBytes_GET_SIZE(rep);
4788 else
4789 repsize = PyUnicode_GET_SIZE(rep);
4790
4791 if (repsize > 4) {
4792 Py_ssize_t offset;
4793
4794 if (result == NULL)
4795 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004796 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004797 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004799 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4800 /* integer overflow */
4801 PyErr_NoMemory();
4802 goto error;
4803 }
4804 nallocated += repsize - 4;
4805 if (result != NULL) {
4806 if (_PyBytes_Resize(&result, nallocated) < 0)
4807 goto error;
4808 } else {
4809 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004810 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004811 goto error;
4812 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4813 }
4814 p = PyBytes_AS_STRING(result) + offset;
4815 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004816
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004817 if (PyBytes_Check(rep)) {
4818 char *prep = PyBytes_AS_STRING(rep);
4819 for(k = repsize; k > 0; k--)
4820 *p++ = *prep++;
4821 } else /* rep is unicode */ {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004822 enum PyUnicode_Kind repkind;
4823 void *repdata;
4824
4825 if (PyUnicode_READY(rep) < 0) {
4826 Py_DECREF(rep);
4827 goto error;
4828 }
4829 repkind = PyUnicode_KIND(rep);
4830 repdata = PyUnicode_DATA(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004831
4832 for(k=0; k<repsize; k++) {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004833 Py_UCS4 c = PyUnicode_READ(repkind, repdata, k);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004834 if (0x80 <= c) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01004835 raise_encode_exception(&exc, "utf-8",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004836 unicode,
Martin v. Löwis9e816682011-11-02 12:45:42 +01004837 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004838 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004839 goto error;
4840 }
Victor Stinnera98b28c2011-11-10 20:21:49 +01004841 *p++ = (char)c;
Victor Stinner31be90b2010-04-22 19:38:16 +00004842 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004843 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004844 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004845 } else if (ch < 0x10000) {
4846 *p++ = (char)(0xe0 | (ch >> 12));
4847 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4848 *p++ = (char)(0x80 | (ch & 0x3f));
4849 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004850 /* Encode UCS4 Unicode ordinals */
4851 *p++ = (char)(0xf0 | (ch >> 18));
4852 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4853 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4854 *p++ = (char)(0x80 | (ch & 0x3f));
4855 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004856 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004857
Guido van Rossum98297ee2007-11-06 21:34:58 +00004858 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004859 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004860 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004861 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004862 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004863 }
4864 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004865 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004866 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004867 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004868 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004869 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004870
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004871 Py_XDECREF(errorHandler);
4872 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004873 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004874 error:
4875 Py_XDECREF(errorHandler);
4876 Py_XDECREF(exc);
4877 Py_XDECREF(result);
4878 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004879
Tim Peters602f7402002-04-27 18:03:26 +00004880#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004881}
4882
Alexander Belopolsky40018472011-02-26 01:02:56 +00004883PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004884PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4885 Py_ssize_t size,
4886 const char *errors)
4887{
4888 PyObject *v, *unicode;
4889
4890 unicode = PyUnicode_FromUnicode(s, size);
4891 if (unicode == NULL)
4892 return NULL;
4893 v = _PyUnicode_AsUTF8String(unicode, errors);
4894 Py_DECREF(unicode);
4895 return v;
4896}
4897
4898PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004899PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004900{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004901 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004902}
4903
Walter Dörwald41980ca2007-08-16 21:55:45 +00004904/* --- UTF-32 Codec ------------------------------------------------------- */
4905
4906PyObject *
4907PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004908 Py_ssize_t size,
4909 const char *errors,
4910 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004911{
4912 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4913}
4914
4915PyObject *
4916PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004917 Py_ssize_t size,
4918 const char *errors,
4919 int *byteorder,
4920 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004921{
4922 const char *starts = s;
4923 Py_ssize_t startinpos;
4924 Py_ssize_t endinpos;
4925 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004926 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004927 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004928 int bo = 0; /* assume native ordering by default */
4929 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004930 /* Offsets from q for retrieving bytes in the right order. */
4931#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4932 int iorder[] = {0, 1, 2, 3};
4933#else
4934 int iorder[] = {3, 2, 1, 0};
4935#endif
4936 PyObject *errorHandler = NULL;
4937 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004938
Walter Dörwald41980ca2007-08-16 21:55:45 +00004939 q = (unsigned char *)s;
4940 e = q + size;
4941
4942 if (byteorder)
4943 bo = *byteorder;
4944
4945 /* Check for BOM marks (U+FEFF) in the input and adjust current
4946 byte order setting accordingly. In native mode, the leading BOM
4947 mark is skipped, in all other modes, it is copied to the output
4948 stream as-is (giving a ZWNBSP character). */
4949 if (bo == 0) {
4950 if (size >= 4) {
4951 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004952 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004953#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004954 if (bom == 0x0000FEFF) {
4955 q += 4;
4956 bo = -1;
4957 }
4958 else if (bom == 0xFFFE0000) {
4959 q += 4;
4960 bo = 1;
4961 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004962#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004963 if (bom == 0x0000FEFF) {
4964 q += 4;
4965 bo = 1;
4966 }
4967 else if (bom == 0xFFFE0000) {
4968 q += 4;
4969 bo = -1;
4970 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004971#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004972 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004973 }
4974
4975 if (bo == -1) {
4976 /* force LE */
4977 iorder[0] = 0;
4978 iorder[1] = 1;
4979 iorder[2] = 2;
4980 iorder[3] = 3;
4981 }
4982 else if (bo == 1) {
4983 /* force BE */
4984 iorder[0] = 3;
4985 iorder[1] = 2;
4986 iorder[2] = 1;
4987 iorder[3] = 0;
4988 }
4989
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004990 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004991 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004992 if (!unicode)
4993 return NULL;
4994 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01004995 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004996 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004997
Walter Dörwald41980ca2007-08-16 21:55:45 +00004998 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004999 Py_UCS4 ch;
5000 /* remaining bytes at the end? (size should be divisible by 4) */
5001 if (e-q<4) {
5002 if (consumed)
5003 break;
5004 errmsg = "truncated data";
5005 startinpos = ((const char *)q)-starts;
5006 endinpos = ((const char *)e)-starts;
5007 goto utf32Error;
5008 /* The remaining input chars are ignored if the callback
5009 chooses to skip the input */
5010 }
5011 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5012 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005013
Benjamin Peterson29060642009-01-31 22:14:21 +00005014 if (ch >= 0x110000)
5015 {
5016 errmsg = "codepoint not in range(0x110000)";
5017 startinpos = ((const char *)q)-starts;
5018 endinpos = startinpos+4;
5019 goto utf32Error;
5020 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005021 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5022 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005023 q += 4;
5024 continue;
5025 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005026 if (unicode_decode_call_errorhandler(
5027 errors, &errorHandler,
5028 "utf32", errmsg,
5029 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005030 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005031 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005032 }
5033
5034 if (byteorder)
5035 *byteorder = bo;
5036
5037 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005038 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005039
5040 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005041 if (PyUnicode_Resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005042 goto onError;
5043
5044 Py_XDECREF(errorHandler);
5045 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005046#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005047 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005048 Py_DECREF(unicode);
5049 return NULL;
5050 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005051#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005052 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005053 return unicode;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005054
Benjamin Peterson29060642009-01-31 22:14:21 +00005055 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005056 Py_DECREF(unicode);
5057 Py_XDECREF(errorHandler);
5058 Py_XDECREF(exc);
5059 return NULL;
5060}
5061
5062PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005063_PyUnicode_EncodeUTF32(PyObject *str,
5064 const char *errors,
5065 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005066{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005067 int kind;
5068 void *data;
5069 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005070 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005071 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005072 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005073 /* Offsets from p for storing byte pairs in the right order. */
5074#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5075 int iorder[] = {0, 1, 2, 3};
5076#else
5077 int iorder[] = {3, 2, 1, 0};
5078#endif
5079
Benjamin Peterson29060642009-01-31 22:14:21 +00005080#define STORECHAR(CH) \
5081 do { \
5082 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5083 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5084 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5085 p[iorder[0]] = (CH) & 0xff; \
5086 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005087 } while(0)
5088
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005089 if (!PyUnicode_Check(str)) {
5090 PyErr_BadArgument();
5091 return NULL;
5092 }
5093 if (PyUnicode_READY(str) < 0)
5094 return NULL;
5095 kind = PyUnicode_KIND(str);
5096 data = PyUnicode_DATA(str);
5097 len = PyUnicode_GET_LENGTH(str);
5098
5099 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005100 bytesize = nsize * 4;
5101 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005102 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005103 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005104 if (v == NULL)
5105 return NULL;
5106
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005107 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005108 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005109 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005110 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005111 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005112
5113 if (byteorder == -1) {
5114 /* force LE */
5115 iorder[0] = 0;
5116 iorder[1] = 1;
5117 iorder[2] = 2;
5118 iorder[3] = 3;
5119 }
5120 else if (byteorder == 1) {
5121 /* force BE */
5122 iorder[0] = 3;
5123 iorder[1] = 2;
5124 iorder[2] = 1;
5125 iorder[3] = 0;
5126 }
5127
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005128 for (i = 0; i < len; i++)
5129 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005130
5131 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005132 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005133#undef STORECHAR
5134}
5135
Alexander Belopolsky40018472011-02-26 01:02:56 +00005136PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005137PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5138 Py_ssize_t size,
5139 const char *errors,
5140 int byteorder)
5141{
5142 PyObject *result;
5143 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5144 if (tmp == NULL)
5145 return NULL;
5146 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5147 Py_DECREF(tmp);
5148 return result;
5149}
5150
5151PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005152PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005153{
Walter Dörwald41980ca2007-08-16 21:55:45 +00005154 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005155 PyUnicode_GET_SIZE(unicode),
5156 NULL,
5157 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005158}
5159
Guido van Rossumd57fd912000-03-10 22:53:23 +00005160/* --- UTF-16 Codec ------------------------------------------------------- */
5161
Tim Peters772747b2001-08-09 22:21:55 +00005162PyObject *
5163PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005164 Py_ssize_t size,
5165 const char *errors,
5166 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005167{
Walter Dörwald69652032004-09-07 20:24:22 +00005168 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5169}
5170
Antoine Pitrouab868312009-01-10 15:40:25 +00005171/* Two masks for fast checking of whether a C 'long' may contain
5172 UTF16-encoded surrogate characters. This is an efficient heuristic,
5173 assuming that non-surrogate characters with a code point >= 0x8000 are
5174 rare in most input.
5175 FAST_CHAR_MASK is used when the input is in native byte ordering,
5176 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005177*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005178#if (SIZEOF_LONG == 8)
5179# define FAST_CHAR_MASK 0x8000800080008000L
5180# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5181#elif (SIZEOF_LONG == 4)
5182# define FAST_CHAR_MASK 0x80008000L
5183# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5184#else
5185# error C 'long' size should be either 4 or 8!
5186#endif
5187
Walter Dörwald69652032004-09-07 20:24:22 +00005188PyObject *
5189PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005190 Py_ssize_t size,
5191 const char *errors,
5192 int *byteorder,
5193 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005194{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005195 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005196 Py_ssize_t startinpos;
5197 Py_ssize_t endinpos;
5198 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005199 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005200 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005201 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005202 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005203 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005204 /* Offsets from q for retrieving byte pairs in the right order. */
5205#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5206 int ihi = 1, ilo = 0;
5207#else
5208 int ihi = 0, ilo = 1;
5209#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005210 PyObject *errorHandler = NULL;
5211 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005212
5213 /* Note: size will always be longer than the resulting Unicode
5214 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005215 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005216 if (!unicode)
5217 return NULL;
5218 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005219 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005220 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005221
Tim Peters772747b2001-08-09 22:21:55 +00005222 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005223 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005224
5225 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005226 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005227
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005228 /* Check for BOM marks (U+FEFF) in the input and adjust current
5229 byte order setting accordingly. In native mode, the leading BOM
5230 mark is skipped, in all other modes, it is copied to the output
5231 stream as-is (giving a ZWNBSP character). */
5232 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005233 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005234 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005235#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005236 if (bom == 0xFEFF) {
5237 q += 2;
5238 bo = -1;
5239 }
5240 else if (bom == 0xFFFE) {
5241 q += 2;
5242 bo = 1;
5243 }
Tim Petersced69f82003-09-16 20:30:58 +00005244#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005245 if (bom == 0xFEFF) {
5246 q += 2;
5247 bo = 1;
5248 }
5249 else if (bom == 0xFFFE) {
5250 q += 2;
5251 bo = -1;
5252 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005253#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005254 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005255 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005256
Tim Peters772747b2001-08-09 22:21:55 +00005257 if (bo == -1) {
5258 /* force LE */
5259 ihi = 1;
5260 ilo = 0;
5261 }
5262 else if (bo == 1) {
5263 /* force BE */
5264 ihi = 0;
5265 ilo = 1;
5266 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005267#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5268 native_ordering = ilo < ihi;
5269#else
5270 native_ordering = ilo > ihi;
5271#endif
Tim Peters772747b2001-08-09 22:21:55 +00005272
Antoine Pitrouab868312009-01-10 15:40:25 +00005273 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005274 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005275 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005276 /* First check for possible aligned read of a C 'long'. Unaligned
5277 reads are more expensive, better to defer to another iteration. */
5278 if (!((size_t) q & LONG_PTR_MASK)) {
5279 /* Fast path for runs of non-surrogate chars. */
5280 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005281 int kind = PyUnicode_KIND(unicode);
5282 void *data = PyUnicode_DATA(unicode);
5283 while (_q < aligned_end) {
5284 unsigned long block = * (unsigned long *) _q;
5285 unsigned short *pblock = (unsigned short*)&block;
5286 Py_UCS4 maxch;
5287 if (native_ordering) {
5288 /* Can use buffer directly */
5289 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005290 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005291 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005292 else {
5293 /* Need to byte-swap */
5294 unsigned char *_p = (unsigned char*)pblock;
5295 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005296 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005297 _p[0] = _q[1];
5298 _p[1] = _q[0];
5299 _p[2] = _q[3];
5300 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005301#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005302 _p[4] = _q[5];
5303 _p[5] = _q[4];
5304 _p[6] = _q[7];
5305 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005306#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005307 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005308 maxch = Py_MAX(pblock[0], pblock[1]);
5309#if SIZEOF_LONG == 8
5310 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5311#endif
5312 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5313 if (unicode_widen(&unicode, maxch) < 0)
5314 goto onError;
5315 kind = PyUnicode_KIND(unicode);
5316 data = PyUnicode_DATA(unicode);
5317 }
5318 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5319 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5320#if SIZEOF_LONG == 8
5321 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5322 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5323#endif
5324 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005325 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005326 q = _q;
5327 if (q >= e)
5328 break;
5329 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005330 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005331
Benjamin Peterson14339b62009-01-31 16:36:08 +00005332 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005333
5334 if (ch < 0xD800 || ch > 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005335 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5336 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005337 continue;
5338 }
5339
5340 /* UTF-16 code pair: */
5341 if (q > e) {
5342 errmsg = "unexpected end of data";
5343 startinpos = (((const char *)q) - 2) - starts;
5344 endinpos = ((const char *)e) + 1 - starts;
5345 goto utf16Error;
5346 }
5347 if (0xD800 <= ch && ch <= 0xDBFF) {
5348 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5349 q += 2;
5350 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005351 if (unicode_putchar(&unicode, &outpos,
5352 (((ch & 0x3FF)<<10) |
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005353 (ch2 & 0x3FF)) + 0x10000) < 0)
5354 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005355 continue;
5356 }
5357 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005358 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005359 startinpos = (((const char *)q)-4)-starts;
5360 endinpos = startinpos+2;
5361 goto utf16Error;
5362 }
5363
Benjamin Peterson14339b62009-01-31 16:36:08 +00005364 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005365 errmsg = "illegal encoding";
5366 startinpos = (((const char *)q)-2)-starts;
5367 endinpos = startinpos+2;
5368 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005369
Benjamin Peterson29060642009-01-31 22:14:21 +00005370 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005371 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005372 errors,
5373 &errorHandler,
5374 "utf16", errmsg,
5375 &starts,
5376 (const char **)&e,
5377 &startinpos,
5378 &endinpos,
5379 &exc,
5380 (const char **)&q,
5381 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005382 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005383 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005384 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005385 /* remaining byte at the end? (size should be even) */
5386 if (e == q) {
5387 if (!consumed) {
5388 errmsg = "truncated data";
5389 startinpos = ((const char *)q) - starts;
5390 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005391 if (unicode_decode_call_errorhandler(
5392 errors,
5393 &errorHandler,
5394 "utf16", errmsg,
5395 &starts,
5396 (const char **)&e,
5397 &startinpos,
5398 &endinpos,
5399 &exc,
5400 (const char **)&q,
5401 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005402 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005403 goto onError;
5404 /* The remaining input chars are ignored if the callback
5405 chooses to skip the input */
5406 }
5407 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005408
5409 if (byteorder)
5410 *byteorder = bo;
5411
Walter Dörwald69652032004-09-07 20:24:22 +00005412 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005413 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005414
Guido van Rossumd57fd912000-03-10 22:53:23 +00005415 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005416 if (PyUnicode_Resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005417 goto onError;
5418
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005419 Py_XDECREF(errorHandler);
5420 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005421 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005422 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005423
Benjamin Peterson29060642009-01-31 22:14:21 +00005424 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005425 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005426 Py_XDECREF(errorHandler);
5427 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428 return NULL;
5429}
5430
Antoine Pitrouab868312009-01-10 15:40:25 +00005431#undef FAST_CHAR_MASK
5432#undef SWAPPED_FAST_CHAR_MASK
5433
Tim Peters772747b2001-08-09 22:21:55 +00005434PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005435_PyUnicode_EncodeUTF16(PyObject *str,
5436 const char *errors,
5437 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005438{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005439 int kind;
5440 void *data;
5441 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005442 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005443 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005444 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005445 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005446 /* Offsets from p for storing byte pairs in the right order. */
5447#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5448 int ihi = 1, ilo = 0;
5449#else
5450 int ihi = 0, ilo = 1;
5451#endif
5452
Benjamin Peterson29060642009-01-31 22:14:21 +00005453#define STORECHAR(CH) \
5454 do { \
5455 p[ihi] = ((CH) >> 8) & 0xff; \
5456 p[ilo] = (CH) & 0xff; \
5457 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005458 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005459
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005460 if (!PyUnicode_Check(str)) {
5461 PyErr_BadArgument();
5462 return NULL;
5463 }
5464 if (PyUnicode_READY(str) < 0)
5465 return NULL;
5466 kind = PyUnicode_KIND(str);
5467 data = PyUnicode_DATA(str);
5468 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005469
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005470 pairs = 0;
5471 if (kind == PyUnicode_4BYTE_KIND)
5472 for (i = 0; i < len; i++)
5473 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5474 pairs++;
5475 /* 2 * (len + pairs + (byteorder == 0)) */
5476 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005477 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005478 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005479 bytesize = nsize * 2;
5480 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005481 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005482 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005483 if (v == NULL)
5484 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005485
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005486 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005487 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005488 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005489 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005490 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005491
5492 if (byteorder == -1) {
5493 /* force LE */
5494 ihi = 1;
5495 ilo = 0;
5496 }
5497 else if (byteorder == 1) {
5498 /* force BE */
5499 ihi = 0;
5500 ilo = 1;
5501 }
5502
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005503 for (i = 0; i < len; i++) {
5504 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5505 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005506 if (ch >= 0x10000) {
5507 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5508 ch = 0xD800 | ((ch-0x10000) >> 10);
5509 }
Tim Peters772747b2001-08-09 22:21:55 +00005510 STORECHAR(ch);
5511 if (ch2)
5512 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005513 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005514
5515 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005516 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005517#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005518}
5519
Alexander Belopolsky40018472011-02-26 01:02:56 +00005520PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005521PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5522 Py_ssize_t size,
5523 const char *errors,
5524 int byteorder)
5525{
5526 PyObject *result;
5527 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5528 if (tmp == NULL)
5529 return NULL;
5530 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5531 Py_DECREF(tmp);
5532 return result;
5533}
5534
5535PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005536PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005537{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005538 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005539}
5540
5541/* --- Unicode Escape Codec ----------------------------------------------- */
5542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005543/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5544 if all the escapes in the string make it still a valid ASCII string.
5545 Returns -1 if any escapes were found which cause the string to
5546 pop out of ASCII range. Otherwise returns the length of the
5547 required buffer to hold the string.
5548 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005549static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005550length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5551{
5552 const unsigned char *p = (const unsigned char *)s;
5553 const unsigned char *end = p + size;
5554 Py_ssize_t length = 0;
5555
5556 if (size < 0)
5557 return -1;
5558
5559 for (; p < end; ++p) {
5560 if (*p > 127) {
5561 /* Non-ASCII */
5562 return -1;
5563 }
5564 else if (*p != '\\') {
5565 /* Normal character */
5566 ++length;
5567 }
5568 else {
5569 /* Backslash-escape, check next char */
5570 ++p;
5571 /* Escape sequence reaches till end of string or
5572 non-ASCII follow-up. */
5573 if (p >= end || *p > 127)
5574 return -1;
5575 switch (*p) {
5576 case '\n':
5577 /* backslash + \n result in zero characters */
5578 break;
5579 case '\\': case '\'': case '\"':
5580 case 'b': case 'f': case 't':
5581 case 'n': case 'r': case 'v': case 'a':
5582 ++length;
5583 break;
5584 case '0': case '1': case '2': case '3':
5585 case '4': case '5': case '6': case '7':
5586 case 'x': case 'u': case 'U': case 'N':
5587 /* these do not guarantee ASCII characters */
5588 return -1;
5589 default:
5590 /* count the backslash + the other character */
5591 length += 2;
5592 }
5593 }
5594 }
5595 return length;
5596}
5597
5598/* Similar to PyUnicode_WRITE but either write into wstr field
5599 or treat string as ASCII. */
5600#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5601 do { \
5602 if ((kind) != PyUnicode_WCHAR_KIND) \
5603 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5604 else \
5605 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5606 } while (0)
5607
5608#define WRITE_WSTR(buf, index, value) \
5609 assert(kind == PyUnicode_WCHAR_KIND), \
5610 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5611
5612
Fredrik Lundh06d12682001-01-24 07:59:11 +00005613static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005614
Alexander Belopolsky40018472011-02-26 01:02:56 +00005615PyObject *
5616PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005617 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005618 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005619{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005620 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005621 Py_ssize_t startinpos;
5622 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005623 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005624 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005625 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005626 char* message;
5627 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005628 PyObject *errorHandler = NULL;
5629 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005630 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005631 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005632
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005633 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005634
5635 /* After length_of_escaped_ascii_string() there are two alternatives,
5636 either the string is pure ASCII with named escapes like \n, etc.
5637 and we determined it's exact size (common case)
5638 or it contains \x, \u, ... escape sequences. then we create a
5639 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005640 if (len >= 0) {
5641 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005642 if (!v)
5643 goto onError;
5644 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005645 }
5646 else {
5647 /* Escaped strings will always be longer than the resulting
5648 Unicode string, so we start with size here and then reduce the
5649 length after conversion to the true value.
5650 (but if the error callback returns a long replacement string
5651 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005652 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005653 if (!v)
5654 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005655 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005656 }
5657
Guido van Rossumd57fd912000-03-10 22:53:23 +00005658 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005659 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005660 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005661 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005662
Guido van Rossumd57fd912000-03-10 22:53:23 +00005663 while (s < end) {
5664 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005665 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005666 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005667
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005668 /* The only case in which i == ascii_length is a backslash
5669 followed by a newline. */
5670 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005671
Guido van Rossumd57fd912000-03-10 22:53:23 +00005672 /* Non-escape characters are interpreted as Unicode ordinals */
5673 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005674 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5675 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005676 continue;
5677 }
5678
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005679 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005680 /* \ - Escapes */
5681 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005682 c = *s++;
5683 if (s > end)
5684 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005685
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005686 /* The only case in which i == ascii_length is a backslash
5687 followed by a newline. */
5688 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005689
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005690 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005691
Benjamin Peterson29060642009-01-31 22:14:21 +00005692 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005693#define WRITECHAR(ch) \
5694 do { \
5695 if (unicode_putchar(&v, &i, ch) < 0) \
5696 goto onError; \
5697 }while(0)
5698
Guido van Rossumd57fd912000-03-10 22:53:23 +00005699 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005700 case '\\': WRITECHAR('\\'); break;
5701 case '\'': WRITECHAR('\''); break;
5702 case '\"': WRITECHAR('\"'); break;
5703 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005704 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005705 case 'f': WRITECHAR('\014'); break;
5706 case 't': WRITECHAR('\t'); break;
5707 case 'n': WRITECHAR('\n'); break;
5708 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005709 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005710 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005711 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005712 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005713
Benjamin Peterson29060642009-01-31 22:14:21 +00005714 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005715 case '0': case '1': case '2': case '3':
5716 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005717 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005718 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005719 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005720 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005721 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005722 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005723 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005724 break;
5725
Benjamin Peterson29060642009-01-31 22:14:21 +00005726 /* hex escapes */
5727 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005728 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005729 digits = 2;
5730 message = "truncated \\xXX escape";
5731 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732
Benjamin Peterson29060642009-01-31 22:14:21 +00005733 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005734 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005735 digits = 4;
5736 message = "truncated \\uXXXX escape";
5737 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005738
Benjamin Peterson29060642009-01-31 22:14:21 +00005739 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005740 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005741 digits = 8;
5742 message = "truncated \\UXXXXXXXX escape";
5743 hexescape:
5744 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005745 if (s+digits>end) {
5746 endinpos = size;
5747 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005748 errors, &errorHandler,
5749 "unicodeescape", "end of string in escape sequence",
5750 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005751 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005752 goto onError;
5753 goto nextByte;
5754 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005755 for (j = 0; j < digits; ++j) {
5756 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005757 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005758 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005759 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005760 errors, &errorHandler,
5761 "unicodeescape", message,
5762 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005763 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005764 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005765 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005766 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005767 }
5768 chr = (chr<<4) & ~0xF;
5769 if (c >= '0' && c <= '9')
5770 chr += c - '0';
5771 else if (c >= 'a' && c <= 'f')
5772 chr += 10 + c - 'a';
5773 else
5774 chr += 10 + c - 'A';
5775 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005776 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005777 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005778 /* _decoding_error will have already written into the
5779 target buffer. */
5780 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005781 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005782 /* when we get here, chr is a 32-bit unicode character */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005783 if (chr <= 0x10ffff) {
5784 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005785 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005786 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005787 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005788 errors, &errorHandler,
5789 "unicodeescape", "illegal Unicode character",
5790 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005791 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005792 goto onError;
5793 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005794 break;
5795
Benjamin Peterson29060642009-01-31 22:14:21 +00005796 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005797 case 'N':
5798 message = "malformed \\N character escape";
5799 if (ucnhash_CAPI == NULL) {
5800 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005801 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5802 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005803 if (ucnhash_CAPI == NULL)
5804 goto ucnhashError;
5805 }
5806 if (*s == '{') {
5807 const char *start = s+1;
5808 /* look for the closing brace */
5809 while (*s != '}' && s < end)
5810 s++;
5811 if (s > start && s < end && *s == '}') {
5812 /* found a name. look it up in the unicode database */
5813 message = "unknown Unicode character name";
5814 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005815 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005816 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005817 goto store;
5818 }
5819 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005820 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005821 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005822 errors, &errorHandler,
5823 "unicodeescape", message,
5824 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005825 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005826 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005827 break;
5828
5829 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005830 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005831 message = "\\ at end of string";
5832 s--;
5833 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005834 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005835 errors, &errorHandler,
5836 "unicodeescape", message,
5837 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005838 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005839 goto onError;
5840 }
5841 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005842 WRITECHAR('\\');
5843 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005844 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005845 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005846 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005847 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005848 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005849 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005850#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005851
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005852 if (PyUnicode_Resize(&v, i) < 0)
5853 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005854 Py_XDECREF(errorHandler);
5855 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005856#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005857 if (_PyUnicode_READY_REPLACE(&v)) {
5858 Py_DECREF(v);
5859 return NULL;
5860 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005861#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005862 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005863 return v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005864
Benjamin Peterson29060642009-01-31 22:14:21 +00005865 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005866 PyErr_SetString(
5867 PyExc_UnicodeError,
5868 "\\N escapes not supported (can't load unicodedata module)"
5869 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005870 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005871 Py_XDECREF(errorHandler);
5872 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005873 return NULL;
5874
Benjamin Peterson29060642009-01-31 22:14:21 +00005875 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005876 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005877 Py_XDECREF(errorHandler);
5878 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005879 return NULL;
5880}
5881
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005882#undef WRITE_ASCII_OR_WSTR
5883#undef WRITE_WSTR
5884
Guido van Rossumd57fd912000-03-10 22:53:23 +00005885/* Return a Unicode-Escape string version of the Unicode object.
5886
5887 If quotes is true, the string is enclosed in u"" or u'' quotes as
5888 appropriate.
5889
5890*/
5891
Alexander Belopolsky40018472011-02-26 01:02:56 +00005892PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005893PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005894{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005895 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005896 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005897 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005898 int kind;
5899 void *data;
5900 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005901
Thomas Wouters89f507f2006-12-13 04:49:30 +00005902 /* Initial allocation is based on the longest-possible unichr
5903 escape.
5904
5905 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5906 unichr, so in this case it's the longest unichr escape. In
5907 narrow (UTF-16) builds this is five chars per source unichr
5908 since there are two unichrs in the surrogate pair, so in narrow
5909 (UTF-16) builds it's not the longest unichr escape.
5910
5911 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5912 so in the narrow (UTF-16) build case it's the longest unichr
5913 escape.
5914 */
5915
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005916 if (!PyUnicode_Check(unicode)) {
5917 PyErr_BadArgument();
5918 return NULL;
5919 }
5920 if (PyUnicode_READY(unicode) < 0)
5921 return NULL;
5922 len = PyUnicode_GET_LENGTH(unicode);
5923 kind = PyUnicode_KIND(unicode);
5924 data = PyUnicode_DATA(unicode);
5925 switch(kind) {
5926 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5927 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5928 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5929 }
5930
5931 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005932 return PyBytes_FromStringAndSize(NULL, 0);
5933
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005934 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005935 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005936
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005937 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005938 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005939 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005940 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005941 if (repr == NULL)
5942 return NULL;
5943
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005944 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005945
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005946 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005947 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005948
Walter Dörwald79e913e2007-05-12 11:08:06 +00005949 /* Escape backslashes */
5950 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005951 *p++ = '\\';
5952 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005953 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005954 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005955
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005956 /* Map 21-bit characters to '\U00xxxxxx' */
5957 else if (ch >= 0x10000) {
5958 *p++ = '\\';
5959 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005960 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5961 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5962 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5963 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5964 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5965 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5966 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5967 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005968 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005969 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005970
Guido van Rossumd57fd912000-03-10 22:53:23 +00005971 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005972 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005973 *p++ = '\\';
5974 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005975 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5976 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5977 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5978 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005979 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005980
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005981 /* Map special whitespace to '\t', \n', '\r' */
5982 else if (ch == '\t') {
5983 *p++ = '\\';
5984 *p++ = 't';
5985 }
5986 else if (ch == '\n') {
5987 *p++ = '\\';
5988 *p++ = 'n';
5989 }
5990 else if (ch == '\r') {
5991 *p++ = '\\';
5992 *p++ = 'r';
5993 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005994
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005995 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005996 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005997 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005998 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005999 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6000 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006001 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006002
Guido van Rossumd57fd912000-03-10 22:53:23 +00006003 /* Copy everything else as-is */
6004 else
6005 *p++ = (char) ch;
6006 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006007
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006008 assert(p - PyBytes_AS_STRING(repr) > 0);
6009 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6010 return NULL;
6011 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006012}
6013
Alexander Belopolsky40018472011-02-26 01:02:56 +00006014PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006015PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6016 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006017{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006018 PyObject *result;
6019 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6020 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006021 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006022 result = PyUnicode_AsUnicodeEscapeString(tmp);
6023 Py_DECREF(tmp);
6024 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006025}
6026
6027/* --- Raw Unicode Escape Codec ------------------------------------------- */
6028
Alexander Belopolsky40018472011-02-26 01:02:56 +00006029PyObject *
6030PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006031 Py_ssize_t size,
6032 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006033{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006034 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006035 Py_ssize_t startinpos;
6036 Py_ssize_t endinpos;
6037 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006038 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 const char *end;
6040 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006041 PyObject *errorHandler = NULL;
6042 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006043
Guido van Rossumd57fd912000-03-10 22:53:23 +00006044 /* Escaped strings will always be longer than the resulting
6045 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006046 length after conversion to the true value. (But decoding error
6047 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006048 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006049 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006050 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006051 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006052 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006053 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006054 end = s + size;
6055 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006056 unsigned char c;
6057 Py_UCS4 x;
6058 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006059 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006060
Benjamin Peterson29060642009-01-31 22:14:21 +00006061 /* Non-escape characters are interpreted as Unicode ordinals */
6062 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006063 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6064 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006065 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006066 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006067 startinpos = s-starts;
6068
6069 /* \u-escapes are only interpreted iff the number of leading
6070 backslashes if odd */
6071 bs = s;
6072 for (;s < end;) {
6073 if (*s != '\\')
6074 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006075 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6076 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006077 }
6078 if (((s - bs) & 1) == 0 ||
6079 s >= end ||
6080 (*s != 'u' && *s != 'U')) {
6081 continue;
6082 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006083 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006084 count = *s=='u' ? 4 : 8;
6085 s++;
6086
6087 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006088 for (x = 0, i = 0; i < count; ++i, ++s) {
6089 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006090 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006091 endinpos = s-starts;
6092 if (unicode_decode_call_errorhandler(
6093 errors, &errorHandler,
6094 "rawunicodeescape", "truncated \\uXXXX",
6095 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006096 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006097 goto onError;
6098 goto nextByte;
6099 }
6100 x = (x<<4) & ~0xF;
6101 if (c >= '0' && c <= '9')
6102 x += c - '0';
6103 else if (c >= 'a' && c <= 'f')
6104 x += 10 + c - 'a';
6105 else
6106 x += 10 + c - 'A';
6107 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006108 if (x <= 0x10ffff) {
6109 if (unicode_putchar(&v, &outpos, x) < 0)
6110 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006111 } else {
6112 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006113 if (unicode_decode_call_errorhandler(
6114 errors, &errorHandler,
6115 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006116 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006117 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006118 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006119 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006120 nextByte:
6121 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006122 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006123 if (PyUnicode_Resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006124 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006125 Py_XDECREF(errorHandler);
6126 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006127 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006128 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006129
Benjamin Peterson29060642009-01-31 22:14:21 +00006130 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006131 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006132 Py_XDECREF(errorHandler);
6133 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006134 return NULL;
6135}
6136
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006137
Alexander Belopolsky40018472011-02-26 01:02:56 +00006138PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006139PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006140{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006141 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006142 char *p;
6143 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006144 Py_ssize_t expandsize, pos;
6145 int kind;
6146 void *data;
6147 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006148
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006149 if (!PyUnicode_Check(unicode)) {
6150 PyErr_BadArgument();
6151 return NULL;
6152 }
6153 if (PyUnicode_READY(unicode) < 0)
6154 return NULL;
6155 kind = PyUnicode_KIND(unicode);
6156 data = PyUnicode_DATA(unicode);
6157 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006158
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006159 switch(kind) {
6160 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6161 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6162 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6163 }
Victor Stinner0e368262011-11-10 20:12:49 +01006164
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006165 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006166 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006167
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006168 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006169 if (repr == NULL)
6170 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006171 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006172 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006173
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006174 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006175 for (pos = 0; pos < len; pos++) {
6176 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006177 /* Map 32-bit characters to '\Uxxxxxxxx' */
6178 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006179 *p++ = '\\';
6180 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006181 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6182 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6183 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6184 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6185 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6186 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6187 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6188 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006189 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006190 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006191 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006192 *p++ = '\\';
6193 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006194 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6195 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6196 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6197 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006198 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006199 /* Copy everything else as-is */
6200 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006201 *p++ = (char) ch;
6202 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006203
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006204 assert(p > q);
6205 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006206 return NULL;
6207 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006208}
6209
Alexander Belopolsky40018472011-02-26 01:02:56 +00006210PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006211PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6212 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006213{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006214 PyObject *result;
6215 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6216 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006217 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006218 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6219 Py_DECREF(tmp);
6220 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006221}
6222
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006223/* --- Unicode Internal Codec ------------------------------------------- */
6224
Alexander Belopolsky40018472011-02-26 01:02:56 +00006225PyObject *
6226_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006227 Py_ssize_t size,
6228 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006229{
6230 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006231 Py_ssize_t startinpos;
6232 Py_ssize_t endinpos;
6233 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006234 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006235 const char *end;
6236 const char *reason;
6237 PyObject *errorHandler = NULL;
6238 PyObject *exc = NULL;
6239
Thomas Wouters89f507f2006-12-13 04:49:30 +00006240 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006241 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006242 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006243 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006244 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006245 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006246 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006247 end = s + size;
6248
6249 while (s < end) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006250 Py_UCS4 ch = *(Py_UNICODE*)s;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006251 /* We have to sanity check the raw data, otherwise doom looms for
6252 some malformed UCS-4 data. */
6253 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006254#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006255 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006256#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006257 end-s < Py_UNICODE_SIZE
6258 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006259 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006260 startinpos = s - starts;
6261 if (end-s < Py_UNICODE_SIZE) {
6262 endinpos = end-starts;
6263 reason = "truncated input";
6264 }
6265 else {
6266 endinpos = s - starts + Py_UNICODE_SIZE;
6267 reason = "illegal code point (> 0x10FFFF)";
6268 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006269 if (unicode_decode_call_errorhandler(
6270 errors, &errorHandler,
6271 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006272 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006273 &v, &outpos)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006274 goto onError;
6275 }
6276 }
6277 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006278 if (unicode_putchar(&v, &outpos, ch) < 0)
6279 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006280 s += Py_UNICODE_SIZE;
6281 }
6282 }
6283
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006284 if (PyUnicode_Resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006285 goto onError;
6286 Py_XDECREF(errorHandler);
6287 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006288 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006289 return v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006290
Benjamin Peterson29060642009-01-31 22:14:21 +00006291 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006292 Py_XDECREF(v);
6293 Py_XDECREF(errorHandler);
6294 Py_XDECREF(exc);
6295 return NULL;
6296}
6297
Guido van Rossumd57fd912000-03-10 22:53:23 +00006298/* --- Latin-1 Codec ------------------------------------------------------ */
6299
Alexander Belopolsky40018472011-02-26 01:02:56 +00006300PyObject *
6301PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006302 Py_ssize_t size,
6303 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006304{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006305 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006306 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006307}
6308
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006309/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006310static void
6311make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006312 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006313 PyObject *unicode,
6314 Py_ssize_t startpos, Py_ssize_t endpos,
6315 const char *reason)
6316{
6317 if (*exceptionObject == NULL) {
6318 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006319 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006320 encoding, unicode, startpos, endpos, reason);
6321 }
6322 else {
6323 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6324 goto onError;
6325 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6326 goto onError;
6327 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6328 goto onError;
6329 return;
6330 onError:
6331 Py_DECREF(*exceptionObject);
6332 *exceptionObject = NULL;
6333 }
6334}
6335
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006336/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006337static void
6338raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006339 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006340 PyObject *unicode,
6341 Py_ssize_t startpos, Py_ssize_t endpos,
6342 const char *reason)
6343{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006344 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006345 encoding, unicode, startpos, endpos, reason);
6346 if (*exceptionObject != NULL)
6347 PyCodec_StrictErrors(*exceptionObject);
6348}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006349
6350/* error handling callback helper:
6351 build arguments, call the callback and check the arguments,
6352 put the result into newpos and return the replacement string, which
6353 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006354static PyObject *
6355unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006356 PyObject **errorHandler,
6357 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006358 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006359 Py_ssize_t startpos, Py_ssize_t endpos,
6360 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006361{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006362 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006363 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006364 PyObject *restuple;
6365 PyObject *resunicode;
6366
6367 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006368 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006369 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006370 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006371 }
6372
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006373 if (PyUnicode_READY(unicode) < 0)
6374 return NULL;
6375 len = PyUnicode_GET_LENGTH(unicode);
6376
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006377 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006378 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006379 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006380 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006381
6382 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006383 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006384 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006385 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006386 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006387 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006388 Py_DECREF(restuple);
6389 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006390 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006391 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006392 &resunicode, newpos)) {
6393 Py_DECREF(restuple);
6394 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006395 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006396 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6397 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6398 Py_DECREF(restuple);
6399 return NULL;
6400 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006401 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006402 *newpos = len + *newpos;
6403 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006404 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6405 Py_DECREF(restuple);
6406 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006407 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006408 Py_INCREF(resunicode);
6409 Py_DECREF(restuple);
6410 return resunicode;
6411}
6412
Alexander Belopolsky40018472011-02-26 01:02:56 +00006413static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006414unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006415 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006416 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006417{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006418 /* input state */
6419 Py_ssize_t pos=0, size;
6420 int kind;
6421 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006422 /* output object */
6423 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006424 /* pointer into the output */
6425 char *str;
6426 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006427 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006428 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6429 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006430 PyObject *errorHandler = NULL;
6431 PyObject *exc = NULL;
6432 /* the following variable is used for caching string comparisons
6433 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6434 int known_errorHandler = -1;
6435
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006436 if (PyUnicode_READY(unicode) < 0)
6437 return NULL;
6438 size = PyUnicode_GET_LENGTH(unicode);
6439 kind = PyUnicode_KIND(unicode);
6440 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006441 /* allocate enough for a simple encoding without
6442 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006443 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006444 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006445 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006446 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006447 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006448 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006449 ressize = size;
6450
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006451 while (pos < size) {
6452 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006453
Benjamin Peterson29060642009-01-31 22:14:21 +00006454 /* can we encode this? */
6455 if (c<limit) {
6456 /* no overflow check, because we know that the space is enough */
6457 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006458 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006459 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006460 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006461 Py_ssize_t requiredsize;
6462 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006463 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006464 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006465 Py_ssize_t collstart = pos;
6466 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006467 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006468 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006469 ++collend;
6470 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6471 if (known_errorHandler==-1) {
6472 if ((errors==NULL) || (!strcmp(errors, "strict")))
6473 known_errorHandler = 1;
6474 else if (!strcmp(errors, "replace"))
6475 known_errorHandler = 2;
6476 else if (!strcmp(errors, "ignore"))
6477 known_errorHandler = 3;
6478 else if (!strcmp(errors, "xmlcharrefreplace"))
6479 known_errorHandler = 4;
6480 else
6481 known_errorHandler = 0;
6482 }
6483 switch (known_errorHandler) {
6484 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006485 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006486 goto onError;
6487 case 2: /* replace */
6488 while (collstart++<collend)
6489 *str++ = '?'; /* fall through */
6490 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006491 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006492 break;
6493 case 4: /* xmlcharrefreplace */
6494 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006495 /* determine replacement size */
6496 for (i = collstart, repsize = 0; i < collend; ++i) {
6497 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6498 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006499 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006500 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006501 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006502 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006503 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006504 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006505 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006506#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006507 else
6508 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006509#else
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006510 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006511 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006512 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006513 repsize += 2+6+1;
6514 else
6515 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006516#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006517 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006518 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006519 if (requiredsize > ressize) {
6520 if (requiredsize<2*ressize)
6521 requiredsize = 2*ressize;
6522 if (_PyBytes_Resize(&res, requiredsize))
6523 goto onError;
6524 str = PyBytes_AS_STRING(res) + respos;
6525 ressize = requiredsize;
6526 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006527 /* generate replacement */
6528 for (i = collstart; i < collend; ++i) {
6529 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006530 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006531 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006532 break;
6533 default:
6534 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006535 encoding, reason, unicode, &exc,
6536 collstart, collend, &newpos);
6537 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6538 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006539 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006540 if (PyBytes_Check(repunicode)) {
6541 /* Directly copy bytes result to output. */
6542 repsize = PyBytes_Size(repunicode);
6543 if (repsize > 1) {
6544 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006545 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006546 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6547 Py_DECREF(repunicode);
6548 goto onError;
6549 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006550 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006551 ressize += repsize-1;
6552 }
6553 memcpy(str, PyBytes_AsString(repunicode), repsize);
6554 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006555 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006556 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006557 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006558 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006559 /* need more space? (at least enough for what we
6560 have+the replacement+the rest of the string, so
6561 we won't have to check space for encodable characters) */
6562 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006563 repsize = PyUnicode_GET_LENGTH(repunicode);
6564 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006565 if (requiredsize > ressize) {
6566 if (requiredsize<2*ressize)
6567 requiredsize = 2*ressize;
6568 if (_PyBytes_Resize(&res, requiredsize)) {
6569 Py_DECREF(repunicode);
6570 goto onError;
6571 }
6572 str = PyBytes_AS_STRING(res) + respos;
6573 ressize = requiredsize;
6574 }
6575 /* check if there is anything unencodable in the replacement
6576 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006577 for (i = 0; repsize-->0; ++i, ++str) {
6578 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006579 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006580 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006581 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006582 Py_DECREF(repunicode);
6583 goto onError;
6584 }
6585 *str = (char)c;
6586 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006587 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006588 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006589 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006590 }
6591 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006592 /* Resize if we allocated to much */
6593 size = str - PyBytes_AS_STRING(res);
6594 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006595 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006596 if (_PyBytes_Resize(&res, size) < 0)
6597 goto onError;
6598 }
6599
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006600 Py_XDECREF(errorHandler);
6601 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006602 return res;
6603
6604 onError:
6605 Py_XDECREF(res);
6606 Py_XDECREF(errorHandler);
6607 Py_XDECREF(exc);
6608 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006609}
6610
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006611/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006612PyObject *
6613PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006614 Py_ssize_t size,
6615 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006616{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006617 PyObject *result;
6618 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6619 if (unicode == NULL)
6620 return NULL;
6621 result = unicode_encode_ucs1(unicode, errors, 256);
6622 Py_DECREF(unicode);
6623 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006624}
6625
Alexander Belopolsky40018472011-02-26 01:02:56 +00006626PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006627_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006628{
6629 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006630 PyErr_BadArgument();
6631 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006632 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006633 if (PyUnicode_READY(unicode) == -1)
6634 return NULL;
6635 /* Fast path: if it is a one-byte string, construct
6636 bytes object directly. */
6637 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6638 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6639 PyUnicode_GET_LENGTH(unicode));
6640 /* Non-Latin-1 characters present. Defer to above function to
6641 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006642 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006643}
6644
6645PyObject*
6646PyUnicode_AsLatin1String(PyObject *unicode)
6647{
6648 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006649}
6650
6651/* --- 7-bit ASCII Codec -------------------------------------------------- */
6652
Alexander Belopolsky40018472011-02-26 01:02:56 +00006653PyObject *
6654PyUnicode_DecodeASCII(const char *s,
6655 Py_ssize_t size,
6656 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006657{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006658 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006659 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006660 int kind;
6661 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006662 Py_ssize_t startinpos;
6663 Py_ssize_t endinpos;
6664 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006665 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006666 int has_error;
6667 const unsigned char *p = (const unsigned char *)s;
6668 const unsigned char *end = p + size;
6669 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006670 PyObject *errorHandler = NULL;
6671 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006672
Guido van Rossumd57fd912000-03-10 22:53:23 +00006673 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006674 if (size == 1 && (unsigned char)s[0] < 128)
6675 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006676
Victor Stinner702c7342011-10-05 13:50:52 +02006677 has_error = 0;
6678 while (p < end && !has_error) {
6679 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6680 an explanation. */
6681 if (!((size_t) p & LONG_PTR_MASK)) {
6682 /* Help register allocation */
6683 register const unsigned char *_p = p;
6684 while (_p < aligned_end) {
6685 unsigned long value = *(unsigned long *) _p;
6686 if (value & ASCII_CHAR_MASK) {
6687 has_error = 1;
6688 break;
6689 }
6690 _p += SIZEOF_LONG;
6691 }
6692 if (_p == end)
6693 break;
6694 if (has_error)
6695 break;
6696 p = _p;
6697 }
6698 if (*p & 0x80) {
6699 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006700 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006701 }
6702 else {
6703 ++p;
6704 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006705 }
Victor Stinner702c7342011-10-05 13:50:52 +02006706 if (!has_error)
6707 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006708
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006709 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006710 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006711 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006712 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006713 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006714 kind = PyUnicode_KIND(v);
6715 data = PyUnicode_DATA(v);
6716 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006717 e = s + size;
6718 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006719 register unsigned char c = (unsigned char)*s;
6720 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006721 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006722 ++s;
6723 }
6724 else {
6725 startinpos = s-starts;
6726 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006727 if (unicode_decode_call_errorhandler(
6728 errors, &errorHandler,
6729 "ascii", "ordinal not in range(128)",
6730 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006731 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006732 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006733 kind = PyUnicode_KIND(v);
6734 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006735 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006736 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006737 if (PyUnicode_Resize(&v, outpos) < 0)
6738 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006739 Py_XDECREF(errorHandler);
6740 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006741 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006742 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006743
Benjamin Peterson29060642009-01-31 22:14:21 +00006744 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006745 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006746 Py_XDECREF(errorHandler);
6747 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006748 return NULL;
6749}
6750
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006751/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006752PyObject *
6753PyUnicode_EncodeASCII(const Py_UNICODE *p,
6754 Py_ssize_t size,
6755 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006756{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006757 PyObject *result;
6758 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6759 if (unicode == NULL)
6760 return NULL;
6761 result = unicode_encode_ucs1(unicode, errors, 128);
6762 Py_DECREF(unicode);
6763 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006764}
6765
Alexander Belopolsky40018472011-02-26 01:02:56 +00006766PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006767_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006768{
6769 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006770 PyErr_BadArgument();
6771 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006772 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006773 if (PyUnicode_READY(unicode) == -1)
6774 return NULL;
6775 /* Fast path: if it is an ASCII-only string, construct bytes object
6776 directly. Else defer to above function to raise the exception. */
6777 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6778 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6779 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006780 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006781}
6782
6783PyObject *
6784PyUnicode_AsASCIIString(PyObject *unicode)
6785{
6786 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006787}
6788
Victor Stinner99b95382011-07-04 14:23:54 +02006789#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006790
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006791/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006792
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006793#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006794#define NEED_RETRY
6795#endif
6796
Victor Stinner3a50e702011-10-18 21:21:00 +02006797#ifndef WC_ERR_INVALID_CHARS
6798# define WC_ERR_INVALID_CHARS 0x0080
6799#endif
6800
6801static char*
6802code_page_name(UINT code_page, PyObject **obj)
6803{
6804 *obj = NULL;
6805 if (code_page == CP_ACP)
6806 return "mbcs";
6807 if (code_page == CP_UTF7)
6808 return "CP_UTF7";
6809 if (code_page == CP_UTF8)
6810 return "CP_UTF8";
6811
6812 *obj = PyBytes_FromFormat("cp%u", code_page);
6813 if (*obj == NULL)
6814 return NULL;
6815 return PyBytes_AS_STRING(*obj);
6816}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006817
Alexander Belopolsky40018472011-02-26 01:02:56 +00006818static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006819is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006820{
6821 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006822 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006823
Victor Stinner3a50e702011-10-18 21:21:00 +02006824 if (!IsDBCSLeadByteEx(code_page, *curr))
6825 return 0;
6826
6827 prev = CharPrevExA(code_page, s, curr, 0);
6828 if (prev == curr)
6829 return 1;
6830 /* FIXME: This code is limited to "true" double-byte encodings,
6831 as it assumes an incomplete character consists of a single
6832 byte. */
6833 if (curr - prev == 2)
6834 return 1;
6835 if (!IsDBCSLeadByteEx(code_page, *prev))
6836 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006837 return 0;
6838}
6839
Victor Stinner3a50e702011-10-18 21:21:00 +02006840static DWORD
6841decode_code_page_flags(UINT code_page)
6842{
6843 if (code_page == CP_UTF7) {
6844 /* The CP_UTF7 decoder only supports flags=0 */
6845 return 0;
6846 }
6847 else
6848 return MB_ERR_INVALID_CHARS;
6849}
6850
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006851/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006852 * Decode a byte string from a Windows code page into unicode object in strict
6853 * mode.
6854 *
6855 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6856 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006857 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006858static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006859decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006860 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006861 const char *in,
6862 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006863{
Victor Stinner3a50e702011-10-18 21:21:00 +02006864 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006865 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006866 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006867
6868 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006869 assert(insize > 0);
6870 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6871 if (outsize <= 0)
6872 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006873
6874 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006875 /* Create unicode object */
Victor Stinner76a31a62011-11-04 00:05:13 +01006876 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006877 if (*v == NULL)
6878 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006879 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006880 }
6881 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006882 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006883 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner76a31a62011-11-04 00:05:13 +01006884 if (PyUnicode_Resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006885 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006886 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006887 }
6888
6889 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006890 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6891 if (outsize <= 0)
6892 goto error;
6893 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006894
Victor Stinner3a50e702011-10-18 21:21:00 +02006895error:
6896 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6897 return -2;
6898 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006899 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006900}
6901
Victor Stinner3a50e702011-10-18 21:21:00 +02006902/*
6903 * Decode a byte string from a code page into unicode object with an error
6904 * handler.
6905 *
6906 * Returns consumed size if succeed, or raise a WindowsError or
6907 * UnicodeDecodeError exception and returns -1 on error.
6908 */
6909static int
6910decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006911 PyObject **v,
6912 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006913 const char *errors)
6914{
6915 const char *startin = in;
6916 const char *endin = in + size;
6917 const DWORD flags = decode_code_page_flags(code_page);
6918 /* Ideally, we should get reason from FormatMessage. This is the Windows
6919 2000 English version of the message. */
6920 const char *reason = "No mapping for the Unicode character exists "
6921 "in the target code page.";
6922 /* each step cannot decode more than 1 character, but a character can be
6923 represented as a surrogate pair */
6924 wchar_t buffer[2], *startout, *out;
6925 int insize, outsize;
6926 PyObject *errorHandler = NULL;
6927 PyObject *exc = NULL;
6928 PyObject *encoding_obj = NULL;
6929 char *encoding;
6930 DWORD err;
6931 int ret = -1;
6932
6933 assert(size > 0);
6934
6935 encoding = code_page_name(code_page, &encoding_obj);
6936 if (encoding == NULL)
6937 return -1;
6938
6939 if (errors == NULL || strcmp(errors, "strict") == 0) {
6940 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6941 UnicodeDecodeError. */
6942 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6943 if (exc != NULL) {
6944 PyCodec_StrictErrors(exc);
6945 Py_CLEAR(exc);
6946 }
6947 goto error;
6948 }
6949
6950 if (*v == NULL) {
6951 /* Create unicode object */
6952 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6953 PyErr_NoMemory();
6954 goto error;
6955 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006956 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006957 if (*v == NULL)
6958 goto error;
6959 startout = PyUnicode_AS_UNICODE(*v);
6960 }
6961 else {
6962 /* Extend unicode object */
6963 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6964 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6965 PyErr_NoMemory();
6966 goto error;
6967 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006968 if (PyUnicode_Resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006969 goto error;
6970 startout = PyUnicode_AS_UNICODE(*v) + n;
6971 }
6972
6973 /* Decode the byte string character per character */
6974 out = startout;
6975 while (in < endin)
6976 {
6977 /* Decode a character */
6978 insize = 1;
6979 do
6980 {
6981 outsize = MultiByteToWideChar(code_page, flags,
6982 in, insize,
6983 buffer, Py_ARRAY_LENGTH(buffer));
6984 if (outsize > 0)
6985 break;
6986 err = GetLastError();
6987 if (err != ERROR_NO_UNICODE_TRANSLATION
6988 && err != ERROR_INSUFFICIENT_BUFFER)
6989 {
6990 PyErr_SetFromWindowsErr(0);
6991 goto error;
6992 }
6993 insize++;
6994 }
6995 /* 4=maximum length of a UTF-8 sequence */
6996 while (insize <= 4 && (in + insize) <= endin);
6997
6998 if (outsize <= 0) {
6999 Py_ssize_t startinpos, endinpos, outpos;
7000
7001 startinpos = in - startin;
7002 endinpos = startinpos + 1;
7003 outpos = out - PyUnicode_AS_UNICODE(*v);
7004 if (unicode_decode_call_errorhandler(
7005 errors, &errorHandler,
7006 encoding, reason,
7007 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007008 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007009 {
7010 goto error;
7011 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007012 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007013 }
7014 else {
7015 in += insize;
7016 memcpy(out, buffer, outsize * sizeof(wchar_t));
7017 out += outsize;
7018 }
7019 }
7020
7021 /* write a NUL character at the end */
7022 *out = 0;
7023
7024 /* Extend unicode object */
7025 outsize = out - startout;
7026 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner76a31a62011-11-04 00:05:13 +01007027 if (PyUnicode_Resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007028 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007029 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007030
7031error:
7032 Py_XDECREF(encoding_obj);
7033 Py_XDECREF(errorHandler);
7034 Py_XDECREF(exc);
7035 return ret;
7036}
7037
Victor Stinner3a50e702011-10-18 21:21:00 +02007038static PyObject *
7039decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007040 const char *s, Py_ssize_t size,
7041 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007042{
Victor Stinner76a31a62011-11-04 00:05:13 +01007043 PyObject *v = NULL;
7044 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007045
Victor Stinner3a50e702011-10-18 21:21:00 +02007046 if (code_page < 0) {
7047 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7048 return NULL;
7049 }
7050
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007051 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007052 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007053
Victor Stinner76a31a62011-11-04 00:05:13 +01007054 do
7055 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007056#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007057 if (size > INT_MAX) {
7058 chunk_size = INT_MAX;
7059 final = 0;
7060 done = 0;
7061 }
7062 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007063#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007064 {
7065 chunk_size = (int)size;
7066 final = (consumed == NULL);
7067 done = 1;
7068 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007069
Victor Stinner76a31a62011-11-04 00:05:13 +01007070 /* Skip trailing lead-byte unless 'final' is set */
7071 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7072 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007073
Victor Stinner76a31a62011-11-04 00:05:13 +01007074 if (chunk_size == 0 && done) {
7075 if (v != NULL)
7076 break;
7077 Py_INCREF(unicode_empty);
7078 return unicode_empty;
7079 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007080
Victor Stinner76a31a62011-11-04 00:05:13 +01007081
7082 converted = decode_code_page_strict(code_page, &v,
7083 s, chunk_size);
7084 if (converted == -2)
7085 converted = decode_code_page_errors(code_page, &v,
7086 s, chunk_size,
7087 errors);
7088 assert(converted != 0);
7089
7090 if (converted < 0) {
7091 Py_XDECREF(v);
7092 return NULL;
7093 }
7094
7095 if (consumed)
7096 *consumed += converted;
7097
7098 s += converted;
7099 size -= converted;
7100 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007101
Victor Stinner17efeed2011-10-04 20:05:46 +02007102#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007103 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007104 Py_DECREF(v);
7105 return NULL;
7106 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007107#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007108 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner76a31a62011-11-04 00:05:13 +01007109 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007110}
7111
Alexander Belopolsky40018472011-02-26 01:02:56 +00007112PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007113PyUnicode_DecodeCodePageStateful(int code_page,
7114 const char *s,
7115 Py_ssize_t size,
7116 const char *errors,
7117 Py_ssize_t *consumed)
7118{
7119 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7120}
7121
7122PyObject *
7123PyUnicode_DecodeMBCSStateful(const char *s,
7124 Py_ssize_t size,
7125 const char *errors,
7126 Py_ssize_t *consumed)
7127{
7128 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7129}
7130
7131PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007132PyUnicode_DecodeMBCS(const char *s,
7133 Py_ssize_t size,
7134 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007135{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007136 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7137}
7138
Victor Stinner3a50e702011-10-18 21:21:00 +02007139static DWORD
7140encode_code_page_flags(UINT code_page, const char *errors)
7141{
7142 if (code_page == CP_UTF8) {
7143 if (winver.dwMajorVersion >= 6)
7144 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7145 and later */
7146 return WC_ERR_INVALID_CHARS;
7147 else
7148 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7149 return 0;
7150 }
7151 else if (code_page == CP_UTF7) {
7152 /* CP_UTF7 only supports flags=0 */
7153 return 0;
7154 }
7155 else {
7156 if (errors != NULL && strcmp(errors, "replace") == 0)
7157 return 0;
7158 else
7159 return WC_NO_BEST_FIT_CHARS;
7160 }
7161}
7162
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007163/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007164 * Encode a Unicode string to a Windows code page into a byte string in strict
7165 * mode.
7166 *
7167 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7168 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007169 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007170static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007171encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007172 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007173 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007174{
Victor Stinner554f3f02010-06-16 23:33:54 +00007175 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007176 BOOL *pusedDefaultChar = &usedDefaultChar;
7177 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007178 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007179 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007180 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007181 const DWORD flags = encode_code_page_flags(code_page, NULL);
7182 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007183 /* Create a substring so that we can get the UTF-16 representation
7184 of just the slice under consideration. */
7185 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007186
Martin v. Löwis3d325192011-11-04 18:23:06 +01007187 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007188
Victor Stinner3a50e702011-10-18 21:21:00 +02007189 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007190 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007191 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007192 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007193
Victor Stinner2fc507f2011-11-04 20:06:39 +01007194 substring = PyUnicode_Substring(unicode, offset, offset+len);
7195 if (substring == NULL)
7196 return -1;
7197 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7198 if (p == NULL) {
7199 Py_DECREF(substring);
7200 return -1;
7201 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007202
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007203 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007204 outsize = WideCharToMultiByte(code_page, flags,
7205 p, size,
7206 NULL, 0,
7207 NULL, pusedDefaultChar);
7208 if (outsize <= 0)
7209 goto error;
7210 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007211 if (pusedDefaultChar && *pusedDefaultChar) {
7212 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007213 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007214 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007215
Victor Stinner3a50e702011-10-18 21:21:00 +02007216 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007217 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007218 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007219 if (*outbytes == NULL) {
7220 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007221 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007222 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007223 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007224 }
7225 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007226 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007227 const Py_ssize_t n = PyBytes_Size(*outbytes);
7228 if (outsize > PY_SSIZE_T_MAX - n) {
7229 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007230 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007231 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007232 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007233 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7234 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007235 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007236 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007237 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007238 }
7239
7240 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007241 outsize = WideCharToMultiByte(code_page, flags,
7242 p, size,
7243 out, outsize,
7244 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007245 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007246 if (outsize <= 0)
7247 goto error;
7248 if (pusedDefaultChar && *pusedDefaultChar)
7249 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007250 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007251
Victor Stinner3a50e702011-10-18 21:21:00 +02007252error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007253 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007254 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7255 return -2;
7256 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007257 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007258}
7259
Victor Stinner3a50e702011-10-18 21:21:00 +02007260/*
7261 * Encode a Unicode string to a Windows code page into a byte string using a
7262 * error handler.
7263 *
7264 * Returns consumed characters if succeed, or raise a WindowsError and returns
7265 * -1 on other error.
7266 */
7267static int
7268encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007269 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007270 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007271{
Victor Stinner3a50e702011-10-18 21:21:00 +02007272 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007273 Py_ssize_t pos = unicode_offset;
7274 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007275 /* Ideally, we should get reason from FormatMessage. This is the Windows
7276 2000 English version of the message. */
7277 const char *reason = "invalid character";
7278 /* 4=maximum length of a UTF-8 sequence */
7279 char buffer[4];
7280 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7281 Py_ssize_t outsize;
7282 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007283 PyObject *errorHandler = NULL;
7284 PyObject *exc = NULL;
7285 PyObject *encoding_obj = NULL;
7286 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007287 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007288 PyObject *rep;
7289 int ret = -1;
7290
7291 assert(insize > 0);
7292
7293 encoding = code_page_name(code_page, &encoding_obj);
7294 if (encoding == NULL)
7295 return -1;
7296
7297 if (errors == NULL || strcmp(errors, "strict") == 0) {
7298 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7299 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007300 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007301 if (exc != NULL) {
7302 PyCodec_StrictErrors(exc);
7303 Py_DECREF(exc);
7304 }
7305 Py_XDECREF(encoding_obj);
7306 return -1;
7307 }
7308
7309 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7310 pusedDefaultChar = &usedDefaultChar;
7311 else
7312 pusedDefaultChar = NULL;
7313
7314 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7315 PyErr_NoMemory();
7316 goto error;
7317 }
7318 outsize = insize * Py_ARRAY_LENGTH(buffer);
7319
7320 if (*outbytes == NULL) {
7321 /* Create string object */
7322 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7323 if (*outbytes == NULL)
7324 goto error;
7325 out = PyBytes_AS_STRING(*outbytes);
7326 }
7327 else {
7328 /* Extend string object */
7329 Py_ssize_t n = PyBytes_Size(*outbytes);
7330 if (n > PY_SSIZE_T_MAX - outsize) {
7331 PyErr_NoMemory();
7332 goto error;
7333 }
7334 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7335 goto error;
7336 out = PyBytes_AS_STRING(*outbytes) + n;
7337 }
7338
7339 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007340 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007341 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007342 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7343 wchar_t chars[2];
7344 int charsize;
7345 if (ch < 0x10000) {
7346 chars[0] = (wchar_t)ch;
7347 charsize = 1;
7348 }
7349 else {
7350 ch -= 0x10000;
7351 chars[0] = 0xd800 + (ch >> 10);
7352 chars[1] = 0xdc00 + (ch & 0x3ff);
7353 charsize = 2;
7354 }
7355
Victor Stinner3a50e702011-10-18 21:21:00 +02007356 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007357 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007358 buffer, Py_ARRAY_LENGTH(buffer),
7359 NULL, pusedDefaultChar);
7360 if (outsize > 0) {
7361 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7362 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007363 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007364 memcpy(out, buffer, outsize);
7365 out += outsize;
7366 continue;
7367 }
7368 }
7369 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7370 PyErr_SetFromWindowsErr(0);
7371 goto error;
7372 }
7373
Victor Stinner3a50e702011-10-18 21:21:00 +02007374 rep = unicode_encode_call_errorhandler(
7375 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007376 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007377 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007378 if (rep == NULL)
7379 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007380 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007381
7382 if (PyBytes_Check(rep)) {
7383 outsize = PyBytes_GET_SIZE(rep);
7384 if (outsize != 1) {
7385 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7386 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7387 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7388 Py_DECREF(rep);
7389 goto error;
7390 }
7391 out = PyBytes_AS_STRING(*outbytes) + offset;
7392 }
7393 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7394 out += outsize;
7395 }
7396 else {
7397 Py_ssize_t i;
7398 enum PyUnicode_Kind kind;
7399 void *data;
7400
7401 if (PyUnicode_READY(rep) < 0) {
7402 Py_DECREF(rep);
7403 goto error;
7404 }
7405
7406 outsize = PyUnicode_GET_LENGTH(rep);
7407 if (outsize != 1) {
7408 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7409 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7410 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7411 Py_DECREF(rep);
7412 goto error;
7413 }
7414 out = PyBytes_AS_STRING(*outbytes) + offset;
7415 }
7416 kind = PyUnicode_KIND(rep);
7417 data = PyUnicode_DATA(rep);
7418 for (i=0; i < outsize; i++) {
7419 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7420 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007421 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007422 encoding, unicode,
7423 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007424 "unable to encode error handler result to ASCII");
7425 Py_DECREF(rep);
7426 goto error;
7427 }
7428 *out = (unsigned char)ch;
7429 out++;
7430 }
7431 }
7432 Py_DECREF(rep);
7433 }
7434 /* write a NUL byte */
7435 *out = 0;
7436 outsize = out - PyBytes_AS_STRING(*outbytes);
7437 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7438 if (_PyBytes_Resize(outbytes, outsize) < 0)
7439 goto error;
7440 ret = 0;
7441
7442error:
7443 Py_XDECREF(encoding_obj);
7444 Py_XDECREF(errorHandler);
7445 Py_XDECREF(exc);
7446 return ret;
7447}
7448
Victor Stinner3a50e702011-10-18 21:21:00 +02007449static PyObject *
7450encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007451 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007452 const char *errors)
7453{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007454 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007455 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007456 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007457 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007458
Victor Stinner2fc507f2011-11-04 20:06:39 +01007459 if (PyUnicode_READY(unicode) < 0)
7460 return NULL;
7461 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007462
Victor Stinner3a50e702011-10-18 21:21:00 +02007463 if (code_page < 0) {
7464 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7465 return NULL;
7466 }
7467
Martin v. Löwis3d325192011-11-04 18:23:06 +01007468 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007469 return PyBytes_FromStringAndSize(NULL, 0);
7470
Victor Stinner7581cef2011-11-03 22:32:33 +01007471 offset = 0;
7472 do
7473 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007474#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007475 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007476 chunks. */
7477 if (len > INT_MAX/2) {
7478 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007479 done = 0;
7480 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007481 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007482#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007483 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007484 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007485 done = 1;
7486 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007487
Victor Stinner76a31a62011-11-04 00:05:13 +01007488 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007489 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007490 errors);
7491 if (ret == -2)
7492 ret = encode_code_page_errors(code_page, &outbytes,
7493 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007494 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007495 if (ret < 0) {
7496 Py_XDECREF(outbytes);
7497 return NULL;
7498 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007499
Victor Stinner7581cef2011-11-03 22:32:33 +01007500 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007501 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007502 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007503
Victor Stinner3a50e702011-10-18 21:21:00 +02007504 return outbytes;
7505}
7506
7507PyObject *
7508PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7509 Py_ssize_t size,
7510 const char *errors)
7511{
Victor Stinner7581cef2011-11-03 22:32:33 +01007512 PyObject *unicode, *res;
7513 unicode = PyUnicode_FromUnicode(p, size);
7514 if (unicode == NULL)
7515 return NULL;
7516 res = encode_code_page(CP_ACP, unicode, errors);
7517 Py_DECREF(unicode);
7518 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007519}
7520
7521PyObject *
7522PyUnicode_EncodeCodePage(int code_page,
7523 PyObject *unicode,
7524 const char *errors)
7525{
Victor Stinner7581cef2011-11-03 22:32:33 +01007526 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007527}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007528
Alexander Belopolsky40018472011-02-26 01:02:56 +00007529PyObject *
7530PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007531{
7532 if (!PyUnicode_Check(unicode)) {
7533 PyErr_BadArgument();
7534 return NULL;
7535 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007536 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007537}
7538
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007539#undef NEED_RETRY
7540
Victor Stinner99b95382011-07-04 14:23:54 +02007541#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007542
Guido van Rossumd57fd912000-03-10 22:53:23 +00007543/* --- Character Mapping Codec -------------------------------------------- */
7544
Alexander Belopolsky40018472011-02-26 01:02:56 +00007545PyObject *
7546PyUnicode_DecodeCharmap(const char *s,
7547 Py_ssize_t size,
7548 PyObject *mapping,
7549 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007550{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007551 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007552 Py_ssize_t startinpos;
7553 Py_ssize_t endinpos;
7554 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007555 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007556 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007557 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007558 PyObject *errorHandler = NULL;
7559 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007560
Guido van Rossumd57fd912000-03-10 22:53:23 +00007561 /* Default to Latin-1 */
7562 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007563 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007564
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007565 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007566 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007567 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007568 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007569 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007570 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007571 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007572 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007573 Py_ssize_t maplen;
7574 enum PyUnicode_Kind kind;
7575 void *data;
7576 Py_UCS4 x;
7577
7578 if (PyUnicode_READY(mapping) < 0)
7579 return NULL;
7580
7581 maplen = PyUnicode_GET_LENGTH(mapping);
7582 data = PyUnicode_DATA(mapping);
7583 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007584 while (s < e) {
7585 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007586
Benjamin Peterson29060642009-01-31 22:14:21 +00007587 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007588 x = PyUnicode_READ(kind, data, ch);
7589 else
7590 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007591
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007592 if (x == 0xfffe)
7593 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007594 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007595 startinpos = s-starts;
7596 endinpos = startinpos+1;
7597 if (unicode_decode_call_errorhandler(
7598 errors, &errorHandler,
7599 "charmap", "character maps to <undefined>",
7600 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007601 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007602 goto onError;
7603 }
7604 continue;
7605 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007606
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007607 if (unicode_putchar(&v, &outpos, x) < 0)
7608 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007609 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007610 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007611 }
7612 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007613 while (s < e) {
7614 unsigned char ch = *s;
7615 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007616
Benjamin Peterson29060642009-01-31 22:14:21 +00007617 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7618 w = PyLong_FromLong((long)ch);
7619 if (w == NULL)
7620 goto onError;
7621 x = PyObject_GetItem(mapping, w);
7622 Py_DECREF(w);
7623 if (x == NULL) {
7624 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7625 /* No mapping found means: mapping is undefined. */
7626 PyErr_Clear();
7627 x = Py_None;
7628 Py_INCREF(x);
7629 } else
7630 goto onError;
7631 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007632
Benjamin Peterson29060642009-01-31 22:14:21 +00007633 /* Apply mapping */
7634 if (PyLong_Check(x)) {
7635 long value = PyLong_AS_LONG(x);
7636 if (value < 0 || value > 65535) {
7637 PyErr_SetString(PyExc_TypeError,
7638 "character mapping must be in range(65536)");
7639 Py_DECREF(x);
7640 goto onError;
7641 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007642 if (unicode_putchar(&v, &outpos, value) < 0)
7643 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007644 }
7645 else if (x == Py_None) {
7646 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007647 startinpos = s-starts;
7648 endinpos = startinpos+1;
7649 if (unicode_decode_call_errorhandler(
7650 errors, &errorHandler,
7651 "charmap", "character maps to <undefined>",
7652 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007653 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007654 Py_DECREF(x);
7655 goto onError;
7656 }
7657 Py_DECREF(x);
7658 continue;
7659 }
7660 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007661 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007662
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007663 if (PyUnicode_READY(x) < 0)
7664 goto onError;
7665 targetsize = PyUnicode_GET_LENGTH(x);
7666
7667 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007668 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007669 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007670 PyUnicode_READ_CHAR(x, 0)) < 0)
7671 goto onError;
7672 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007673 else if (targetsize > 1) {
7674 /* 1-n mapping */
7675 if (targetsize > extrachars) {
7676 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007677 Py_ssize_t needed = (targetsize - extrachars) + \
7678 (targetsize << 2);
7679 extrachars += needed;
7680 /* XXX overflow detection missing */
Victor Stinner7931d9a2011-11-04 00:22:48 +01007681 if (PyUnicode_Resize(&v,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007682 PyUnicode_GET_LENGTH(v) + needed) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007683 Py_DECREF(x);
7684 goto onError;
7685 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007686 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007687 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7688 goto onError;
7689 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7690 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007691 extrachars -= targetsize;
7692 }
7693 /* 1-0 mapping: skip the character */
7694 }
7695 else {
7696 /* wrong return value */
7697 PyErr_SetString(PyExc_TypeError,
7698 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007699 Py_DECREF(x);
7700 goto onError;
7701 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007702 Py_DECREF(x);
7703 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007704 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007705 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007706 if (PyUnicode_Resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007707 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007708 Py_XDECREF(errorHandler);
7709 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007710 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01007711 return v;
Tim Petersced69f82003-09-16 20:30:58 +00007712
Benjamin Peterson29060642009-01-31 22:14:21 +00007713 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007714 Py_XDECREF(errorHandler);
7715 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007716 Py_XDECREF(v);
7717 return NULL;
7718}
7719
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007720/* Charmap encoding: the lookup table */
7721
Alexander Belopolsky40018472011-02-26 01:02:56 +00007722struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007723 PyObject_HEAD
7724 unsigned char level1[32];
7725 int count2, count3;
7726 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007727};
7728
7729static PyObject*
7730encoding_map_size(PyObject *obj, PyObject* args)
7731{
7732 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007733 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007734 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007735}
7736
7737static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007738 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007739 PyDoc_STR("Return the size (in bytes) of this object") },
7740 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007741};
7742
7743static void
7744encoding_map_dealloc(PyObject* o)
7745{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007746 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007747}
7748
7749static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007750 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007751 "EncodingMap", /*tp_name*/
7752 sizeof(struct encoding_map), /*tp_basicsize*/
7753 0, /*tp_itemsize*/
7754 /* methods */
7755 encoding_map_dealloc, /*tp_dealloc*/
7756 0, /*tp_print*/
7757 0, /*tp_getattr*/
7758 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007759 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007760 0, /*tp_repr*/
7761 0, /*tp_as_number*/
7762 0, /*tp_as_sequence*/
7763 0, /*tp_as_mapping*/
7764 0, /*tp_hash*/
7765 0, /*tp_call*/
7766 0, /*tp_str*/
7767 0, /*tp_getattro*/
7768 0, /*tp_setattro*/
7769 0, /*tp_as_buffer*/
7770 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7771 0, /*tp_doc*/
7772 0, /*tp_traverse*/
7773 0, /*tp_clear*/
7774 0, /*tp_richcompare*/
7775 0, /*tp_weaklistoffset*/
7776 0, /*tp_iter*/
7777 0, /*tp_iternext*/
7778 encoding_map_methods, /*tp_methods*/
7779 0, /*tp_members*/
7780 0, /*tp_getset*/
7781 0, /*tp_base*/
7782 0, /*tp_dict*/
7783 0, /*tp_descr_get*/
7784 0, /*tp_descr_set*/
7785 0, /*tp_dictoffset*/
7786 0, /*tp_init*/
7787 0, /*tp_alloc*/
7788 0, /*tp_new*/
7789 0, /*tp_free*/
7790 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007791};
7792
7793PyObject*
7794PyUnicode_BuildEncodingMap(PyObject* string)
7795{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007796 PyObject *result;
7797 struct encoding_map *mresult;
7798 int i;
7799 int need_dict = 0;
7800 unsigned char level1[32];
7801 unsigned char level2[512];
7802 unsigned char *mlevel1, *mlevel2, *mlevel3;
7803 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007804 int kind;
7805 void *data;
7806 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007807
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007808 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007809 PyErr_BadArgument();
7810 return NULL;
7811 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007812 kind = PyUnicode_KIND(string);
7813 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007814 memset(level1, 0xFF, sizeof level1);
7815 memset(level2, 0xFF, sizeof level2);
7816
7817 /* If there isn't a one-to-one mapping of NULL to \0,
7818 or if there are non-BMP characters, we need to use
7819 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007820 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007821 need_dict = 1;
7822 for (i = 1; i < 256; i++) {
7823 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007824 ch = PyUnicode_READ(kind, data, i);
7825 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007826 need_dict = 1;
7827 break;
7828 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007829 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007830 /* unmapped character */
7831 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007832 l1 = ch >> 11;
7833 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007834 if (level1[l1] == 0xFF)
7835 level1[l1] = count2++;
7836 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007837 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007838 }
7839
7840 if (count2 >= 0xFF || count3 >= 0xFF)
7841 need_dict = 1;
7842
7843 if (need_dict) {
7844 PyObject *result = PyDict_New();
7845 PyObject *key, *value;
7846 if (!result)
7847 return NULL;
7848 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007849 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007850 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007851 if (!key || !value)
7852 goto failed1;
7853 if (PyDict_SetItem(result, key, value) == -1)
7854 goto failed1;
7855 Py_DECREF(key);
7856 Py_DECREF(value);
7857 }
7858 return result;
7859 failed1:
7860 Py_XDECREF(key);
7861 Py_XDECREF(value);
7862 Py_DECREF(result);
7863 return NULL;
7864 }
7865
7866 /* Create a three-level trie */
7867 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7868 16*count2 + 128*count3 - 1);
7869 if (!result)
7870 return PyErr_NoMemory();
7871 PyObject_Init(result, &EncodingMapType);
7872 mresult = (struct encoding_map*)result;
7873 mresult->count2 = count2;
7874 mresult->count3 = count3;
7875 mlevel1 = mresult->level1;
7876 mlevel2 = mresult->level23;
7877 mlevel3 = mresult->level23 + 16*count2;
7878 memcpy(mlevel1, level1, 32);
7879 memset(mlevel2, 0xFF, 16*count2);
7880 memset(mlevel3, 0, 128*count3);
7881 count3 = 0;
7882 for (i = 1; i < 256; i++) {
7883 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007884 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007885 /* unmapped character */
7886 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007887 o1 = PyUnicode_READ(kind, data, i)>>11;
7888 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007889 i2 = 16*mlevel1[o1] + o2;
7890 if (mlevel2[i2] == 0xFF)
7891 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007892 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007893 i3 = 128*mlevel2[i2] + o3;
7894 mlevel3[i3] = i;
7895 }
7896 return result;
7897}
7898
7899static int
7900encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
7901{
7902 struct encoding_map *map = (struct encoding_map*)mapping;
7903 int l1 = c>>11;
7904 int l2 = (c>>7) & 0xF;
7905 int l3 = c & 0x7F;
7906 int i;
7907
7908#ifdef Py_UNICODE_WIDE
7909 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007910 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007911 }
7912#endif
7913 if (c == 0)
7914 return 0;
7915 /* level 1*/
7916 i = map->level1[l1];
7917 if (i == 0xFF) {
7918 return -1;
7919 }
7920 /* level 2*/
7921 i = map->level23[16*i+l2];
7922 if (i == 0xFF) {
7923 return -1;
7924 }
7925 /* level 3 */
7926 i = map->level23[16*map->count2 + 128*i + l3];
7927 if (i == 0) {
7928 return -1;
7929 }
7930 return i;
7931}
7932
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007933/* Lookup the character ch in the mapping. If the character
7934 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007935 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007936static PyObject *
7937charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007938{
Christian Heimes217cfd12007-12-02 14:31:20 +00007939 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007940 PyObject *x;
7941
7942 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007943 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007944 x = PyObject_GetItem(mapping, w);
7945 Py_DECREF(w);
7946 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007947 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7948 /* No mapping found means: mapping is undefined. */
7949 PyErr_Clear();
7950 x = Py_None;
7951 Py_INCREF(x);
7952 return x;
7953 } else
7954 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007955 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007956 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007957 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007958 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007959 long value = PyLong_AS_LONG(x);
7960 if (value < 0 || value > 255) {
7961 PyErr_SetString(PyExc_TypeError,
7962 "character mapping must be in range(256)");
7963 Py_DECREF(x);
7964 return NULL;
7965 }
7966 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007967 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007968 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007969 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007970 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007971 /* wrong return value */
7972 PyErr_Format(PyExc_TypeError,
7973 "character mapping must return integer, bytes or None, not %.400s",
7974 x->ob_type->tp_name);
7975 Py_DECREF(x);
7976 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007977 }
7978}
7979
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007980static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007981charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007982{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007983 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7984 /* exponentially overallocate to minimize reallocations */
7985 if (requiredsize < 2*outsize)
7986 requiredsize = 2*outsize;
7987 if (_PyBytes_Resize(outobj, requiredsize))
7988 return -1;
7989 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007990}
7991
Benjamin Peterson14339b62009-01-31 16:36:08 +00007992typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007993 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007994} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007995/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007996 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007997 space is available. Return a new reference to the object that
7998 was put in the output buffer, or Py_None, if the mapping was undefined
7999 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008000 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008001static charmapencode_result
8002charmapencode_output(Py_UNICODE c, PyObject *mapping,
8003 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008004{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008005 PyObject *rep;
8006 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008007 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008008
Christian Heimes90aa7642007-12-19 02:45:37 +00008009 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008010 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008011 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008012 if (res == -1)
8013 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008014 if (outsize<requiredsize)
8015 if (charmapencode_resize(outobj, outpos, requiredsize))
8016 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008017 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008018 outstart[(*outpos)++] = (char)res;
8019 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008020 }
8021
8022 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008023 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008024 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008025 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008026 Py_DECREF(rep);
8027 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008028 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008029 if (PyLong_Check(rep)) {
8030 Py_ssize_t requiredsize = *outpos+1;
8031 if (outsize<requiredsize)
8032 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8033 Py_DECREF(rep);
8034 return enc_EXCEPTION;
8035 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008036 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008037 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008038 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008039 else {
8040 const char *repchars = PyBytes_AS_STRING(rep);
8041 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8042 Py_ssize_t requiredsize = *outpos+repsize;
8043 if (outsize<requiredsize)
8044 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8045 Py_DECREF(rep);
8046 return enc_EXCEPTION;
8047 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008048 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008049 memcpy(outstart + *outpos, repchars, repsize);
8050 *outpos += repsize;
8051 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008052 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008053 Py_DECREF(rep);
8054 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008055}
8056
8057/* handle an error in PyUnicode_EncodeCharmap
8058 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008059static int
8060charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008061 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008062 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008063 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008064 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008065{
8066 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008067 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008068 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008069 Py_UNICODE *uni2;
8070 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008071 Py_ssize_t collstartpos = *inpos;
8072 Py_ssize_t collendpos = *inpos+1;
8073 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008074 char *encoding = "charmap";
8075 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008076 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008077 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008078 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008079
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008080 if (PyUnicode_READY(unicode) < 0)
8081 return -1;
8082 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008083 /* find all unencodable characters */
8084 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008085 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008086 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008087 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008088 val = encoding_map_lookup(ch, mapping);
8089 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008090 break;
8091 ++collendpos;
8092 continue;
8093 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008094
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008095 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8096 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008097 if (rep==NULL)
8098 return -1;
8099 else if (rep!=Py_None) {
8100 Py_DECREF(rep);
8101 break;
8102 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008103 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008104 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008105 }
8106 /* cache callback name lookup
8107 * (if not done yet, i.e. it's the first error) */
8108 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008109 if ((errors==NULL) || (!strcmp(errors, "strict")))
8110 *known_errorHandler = 1;
8111 else if (!strcmp(errors, "replace"))
8112 *known_errorHandler = 2;
8113 else if (!strcmp(errors, "ignore"))
8114 *known_errorHandler = 3;
8115 else if (!strcmp(errors, "xmlcharrefreplace"))
8116 *known_errorHandler = 4;
8117 else
8118 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008119 }
8120 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008121 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008122 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008123 return -1;
8124 case 2: /* replace */
8125 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008126 x = charmapencode_output('?', mapping, res, respos);
8127 if (x==enc_EXCEPTION) {
8128 return -1;
8129 }
8130 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008131 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008132 return -1;
8133 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008134 }
8135 /* fall through */
8136 case 3: /* ignore */
8137 *inpos = collendpos;
8138 break;
8139 case 4: /* xmlcharrefreplace */
8140 /* generate replacement (temporarily (mis)uses p) */
8141 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008142 char buffer[2+29+1+1];
8143 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008144 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008145 for (cp = buffer; *cp; ++cp) {
8146 x = charmapencode_output(*cp, mapping, res, respos);
8147 if (x==enc_EXCEPTION)
8148 return -1;
8149 else if (x==enc_FAILED) {
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 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008155 *inpos = collendpos;
8156 break;
8157 default:
8158 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008159 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008160 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008161 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008162 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008163 if (PyBytes_Check(repunicode)) {
8164 /* Directly copy bytes result to output. */
8165 Py_ssize_t outsize = PyBytes_Size(*res);
8166 Py_ssize_t requiredsize;
8167 repsize = PyBytes_Size(repunicode);
8168 requiredsize = *respos + repsize;
8169 if (requiredsize > outsize)
8170 /* Make room for all additional bytes. */
8171 if (charmapencode_resize(res, respos, requiredsize)) {
8172 Py_DECREF(repunicode);
8173 return -1;
8174 }
8175 memcpy(PyBytes_AsString(*res) + *respos,
8176 PyBytes_AsString(repunicode), repsize);
8177 *respos += repsize;
8178 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008179 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008180 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008181 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008182 /* generate replacement */
8183 repsize = PyUnicode_GET_SIZE(repunicode);
8184 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008185 x = charmapencode_output(*uni2, mapping, res, respos);
8186 if (x==enc_EXCEPTION) {
8187 return -1;
8188 }
8189 else if (x==enc_FAILED) {
8190 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008191 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008192 return -1;
8193 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008194 }
8195 *inpos = newpos;
8196 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008197 }
8198 return 0;
8199}
8200
Alexander Belopolsky40018472011-02-26 01:02:56 +00008201PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008202_PyUnicode_EncodeCharmap(PyObject *unicode,
8203 PyObject *mapping,
8204 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008205{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008206 /* output object */
8207 PyObject *res = NULL;
8208 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008209 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008210 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008211 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008212 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008213 PyObject *errorHandler = NULL;
8214 PyObject *exc = NULL;
8215 /* the following variable is used for caching string comparisons
8216 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8217 * 3=ignore, 4=xmlcharrefreplace */
8218 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008219
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008220 if (PyUnicode_READY(unicode) < 0)
8221 return NULL;
8222 size = PyUnicode_GET_LENGTH(unicode);
8223
Guido van Rossumd57fd912000-03-10 22:53:23 +00008224 /* Default to Latin-1 */
8225 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008226 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008227
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008228 /* allocate enough for a simple encoding without
8229 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008230 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008231 if (res == NULL)
8232 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008233 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008234 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008235
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008236 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008237 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008238 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008239 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008240 if (x==enc_EXCEPTION) /* error */
8241 goto onError;
8242 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008243 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008244 &exc,
8245 &known_errorHandler, &errorHandler, errors,
8246 &res, &respos)) {
8247 goto onError;
8248 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008249 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008250 else
8251 /* done with this character => adjust input position */
8252 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008253 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008254
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008255 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008256 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008257 if (_PyBytes_Resize(&res, respos) < 0)
8258 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008259
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008260 Py_XDECREF(exc);
8261 Py_XDECREF(errorHandler);
8262 return res;
8263
Benjamin Peterson29060642009-01-31 22:14:21 +00008264 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008265 Py_XDECREF(res);
8266 Py_XDECREF(exc);
8267 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008268 return NULL;
8269}
8270
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008271/* Deprecated */
8272PyObject *
8273PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8274 Py_ssize_t size,
8275 PyObject *mapping,
8276 const char *errors)
8277{
8278 PyObject *result;
8279 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8280 if (unicode == NULL)
8281 return NULL;
8282 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8283 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008284 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008285}
8286
Alexander Belopolsky40018472011-02-26 01:02:56 +00008287PyObject *
8288PyUnicode_AsCharmapString(PyObject *unicode,
8289 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008290{
8291 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008292 PyErr_BadArgument();
8293 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008294 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008295 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008296}
8297
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008298/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008299static void
8300make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008301 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008302 Py_ssize_t startpos, Py_ssize_t endpos,
8303 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008304{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008305 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008306 *exceptionObject = _PyUnicodeTranslateError_Create(
8307 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008308 }
8309 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008310 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8311 goto onError;
8312 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8313 goto onError;
8314 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8315 goto onError;
8316 return;
8317 onError:
8318 Py_DECREF(*exceptionObject);
8319 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008320 }
8321}
8322
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008323/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008324static void
8325raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008326 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008327 Py_ssize_t startpos, Py_ssize_t endpos,
8328 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008329{
8330 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008331 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008332 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008333 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008334}
8335
8336/* error handling callback helper:
8337 build arguments, call the callback and check the arguments,
8338 put the result into newpos and return the replacement string, which
8339 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008340static PyObject *
8341unicode_translate_call_errorhandler(const char *errors,
8342 PyObject **errorHandler,
8343 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008344 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008345 Py_ssize_t startpos, Py_ssize_t endpos,
8346 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008347{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008348 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008349
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008350 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008351 PyObject *restuple;
8352 PyObject *resunicode;
8353
8354 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008355 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008356 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008357 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008358 }
8359
8360 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008361 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008362 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008363 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008364
8365 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008366 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008367 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008368 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008369 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008370 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008371 Py_DECREF(restuple);
8372 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008373 }
8374 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008375 &resunicode, &i_newpos)) {
8376 Py_DECREF(restuple);
8377 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008378 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008379 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008380 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008381 else
8382 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008383 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008384 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8385 Py_DECREF(restuple);
8386 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008387 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008388 Py_INCREF(resunicode);
8389 Py_DECREF(restuple);
8390 return resunicode;
8391}
8392
8393/* Lookup the character ch in the mapping and put the result in result,
8394 which must be decrefed by the caller.
8395 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008396static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008397charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008398{
Christian Heimes217cfd12007-12-02 14:31:20 +00008399 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008400 PyObject *x;
8401
8402 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008403 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008404 x = PyObject_GetItem(mapping, w);
8405 Py_DECREF(w);
8406 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008407 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8408 /* No mapping found means: use 1:1 mapping. */
8409 PyErr_Clear();
8410 *result = NULL;
8411 return 0;
8412 } else
8413 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008414 }
8415 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 *result = x;
8417 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008418 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008419 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008420 long value = PyLong_AS_LONG(x);
8421 long max = PyUnicode_GetMax();
8422 if (value < 0 || value > max) {
8423 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008424 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008425 Py_DECREF(x);
8426 return -1;
8427 }
8428 *result = x;
8429 return 0;
8430 }
8431 else if (PyUnicode_Check(x)) {
8432 *result = x;
8433 return 0;
8434 }
8435 else {
8436 /* wrong return value */
8437 PyErr_SetString(PyExc_TypeError,
8438 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008439 Py_DECREF(x);
8440 return -1;
8441 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008442}
8443/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008444 if not reallocate and adjust various state variables.
8445 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008446static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008447charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008448 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008449{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008450 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008451 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008452 /* exponentially overallocate to minimize reallocations */
8453 if (requiredsize < 2 * oldsize)
8454 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008455 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8456 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008457 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008458 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008459 }
8460 return 0;
8461}
8462/* lookup the character, put the result in the output string and adjust
8463 various state variables. Return a new reference to the object that
8464 was put in the output buffer in *result, or Py_None, if the mapping was
8465 undefined (in which case no character was written).
8466 The called must decref result.
8467 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008468static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008469charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8470 PyObject *mapping, Py_UCS4 **output,
8471 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008472 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008473{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008474 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8475 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008476 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008477 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008478 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008479 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008480 }
8481 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008482 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008483 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008484 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008485 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008486 }
8487 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008488 Py_ssize_t repsize;
8489 if (PyUnicode_READY(*res) == -1)
8490 return -1;
8491 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008492 if (repsize==1) {
8493 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008494 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008495 }
8496 else if (repsize!=0) {
8497 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008498 Py_ssize_t requiredsize = *opos +
8499 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008500 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008501 Py_ssize_t i;
8502 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008503 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008504 for(i = 0; i < repsize; i++)
8505 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008506 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008507 }
8508 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008509 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008510 return 0;
8511}
8512
Alexander Belopolsky40018472011-02-26 01:02:56 +00008513PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008514_PyUnicode_TranslateCharmap(PyObject *input,
8515 PyObject *mapping,
8516 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008517{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008518 /* input object */
8519 char *idata;
8520 Py_ssize_t size, i;
8521 int kind;
8522 /* output buffer */
8523 Py_UCS4 *output = NULL;
8524 Py_ssize_t osize;
8525 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008526 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008527 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008528 char *reason = "character maps to <undefined>";
8529 PyObject *errorHandler = NULL;
8530 PyObject *exc = NULL;
8531 /* the following variable is used for caching string comparisons
8532 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8533 * 3=ignore, 4=xmlcharrefreplace */
8534 int known_errorHandler = -1;
8535
Guido van Rossumd57fd912000-03-10 22:53:23 +00008536 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008537 PyErr_BadArgument();
8538 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008539 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008540
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008541 if (PyUnicode_READY(input) == -1)
8542 return NULL;
8543 idata = (char*)PyUnicode_DATA(input);
8544 kind = PyUnicode_KIND(input);
8545 size = PyUnicode_GET_LENGTH(input);
8546 i = 0;
8547
8548 if (size == 0) {
8549 Py_INCREF(input);
8550 return input;
8551 }
8552
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008553 /* allocate enough for a simple 1:1 translation without
8554 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008555 osize = size;
8556 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8557 opos = 0;
8558 if (output == NULL) {
8559 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008560 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008561 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008562
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008563 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008564 /* try to encode it */
8565 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008566 if (charmaptranslate_output(input, i, mapping,
8567 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008568 Py_XDECREF(x);
8569 goto onError;
8570 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008571 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008572 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008573 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008574 else { /* untranslatable character */
8575 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8576 Py_ssize_t repsize;
8577 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008578 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008579 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008580 Py_ssize_t collstart = i;
8581 Py_ssize_t collend = i+1;
8582 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008583
Benjamin Peterson29060642009-01-31 22:14:21 +00008584 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008585 while (collend < size) {
8586 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008587 goto onError;
8588 Py_XDECREF(x);
8589 if (x!=Py_None)
8590 break;
8591 ++collend;
8592 }
8593 /* cache callback name lookup
8594 * (if not done yet, i.e. it's the first error) */
8595 if (known_errorHandler==-1) {
8596 if ((errors==NULL) || (!strcmp(errors, "strict")))
8597 known_errorHandler = 1;
8598 else if (!strcmp(errors, "replace"))
8599 known_errorHandler = 2;
8600 else if (!strcmp(errors, "ignore"))
8601 known_errorHandler = 3;
8602 else if (!strcmp(errors, "xmlcharrefreplace"))
8603 known_errorHandler = 4;
8604 else
8605 known_errorHandler = 0;
8606 }
8607 switch (known_errorHandler) {
8608 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008609 raise_translate_exception(&exc, input, collstart,
8610 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008611 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008612 case 2: /* replace */
8613 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008614 for (coll = collstart; coll<collend; coll++)
8615 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008616 /* fall through */
8617 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008618 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008619 break;
8620 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008621 /* generate replacement (temporarily (mis)uses i) */
8622 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008623 char buffer[2+29+1+1];
8624 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008625 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8626 if (charmaptranslate_makespace(&output, &osize,
8627 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008628 goto onError;
8629 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008630 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008631 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008632 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008633 break;
8634 default:
8635 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008636 reason, input, &exc,
8637 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008638 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008639 goto onError;
8640 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008641 repsize = PyUnicode_GET_LENGTH(repunicode);
8642 if (charmaptranslate_makespace(&output, &osize,
8643 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008644 Py_DECREF(repunicode);
8645 goto onError;
8646 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008647 for (uni2 = 0; repsize-->0; ++uni2)
8648 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8649 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008650 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008651 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008652 }
8653 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008654 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8655 if (!res)
8656 goto onError;
8657 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008658 Py_XDECREF(exc);
8659 Py_XDECREF(errorHandler);
8660 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008661
Benjamin Peterson29060642009-01-31 22:14:21 +00008662 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008663 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008664 Py_XDECREF(exc);
8665 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008666 return NULL;
8667}
8668
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008669/* Deprecated. Use PyUnicode_Translate instead. */
8670PyObject *
8671PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8672 Py_ssize_t size,
8673 PyObject *mapping,
8674 const char *errors)
8675{
8676 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8677 if (!unicode)
8678 return NULL;
8679 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8680}
8681
Alexander Belopolsky40018472011-02-26 01:02:56 +00008682PyObject *
8683PyUnicode_Translate(PyObject *str,
8684 PyObject *mapping,
8685 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008686{
8687 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008688
Guido van Rossumd57fd912000-03-10 22:53:23 +00008689 str = PyUnicode_FromObject(str);
8690 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008691 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008692 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008693 Py_DECREF(str);
8694 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008695
Benjamin Peterson29060642009-01-31 22:14:21 +00008696 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008697 Py_XDECREF(str);
8698 return NULL;
8699}
Tim Petersced69f82003-09-16 20:30:58 +00008700
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008701static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008702fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008703{
8704 /* No need to call PyUnicode_READY(self) because this function is only
8705 called as a callback from fixup() which does it already. */
8706 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8707 const int kind = PyUnicode_KIND(self);
8708 void *data = PyUnicode_DATA(self);
8709 Py_UCS4 maxchar = 0, ch, fixed;
8710 Py_ssize_t i;
8711
8712 for (i = 0; i < len; ++i) {
8713 ch = PyUnicode_READ(kind, data, i);
8714 fixed = 0;
8715 if (ch > 127) {
8716 if (Py_UNICODE_ISSPACE(ch))
8717 fixed = ' ';
8718 else {
8719 const int decimal = Py_UNICODE_TODECIMAL(ch);
8720 if (decimal >= 0)
8721 fixed = '0' + decimal;
8722 }
8723 if (fixed != 0) {
8724 if (fixed > maxchar)
8725 maxchar = fixed;
8726 PyUnicode_WRITE(kind, data, i, fixed);
8727 }
8728 else if (ch > maxchar)
8729 maxchar = ch;
8730 }
8731 else if (ch > maxchar)
8732 maxchar = ch;
8733 }
8734
8735 return maxchar;
8736}
8737
8738PyObject *
8739_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8740{
8741 if (!PyUnicode_Check(unicode)) {
8742 PyErr_BadInternalCall();
8743 return NULL;
8744 }
8745 if (PyUnicode_READY(unicode) == -1)
8746 return NULL;
8747 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8748 /* If the string is already ASCII, just return the same string */
8749 Py_INCREF(unicode);
8750 return unicode;
8751 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008752 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008753}
8754
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008755PyObject *
8756PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8757 Py_ssize_t length)
8758{
8759 PyObject *result;
8760 Py_UNICODE *p; /* write pointer into result */
8761 Py_ssize_t i;
8762 /* Copy to a new string */
8763 result = (PyObject *)_PyUnicode_New(length);
8764 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8765 if (result == NULL)
8766 return result;
8767 p = PyUnicode_AS_UNICODE(result);
8768 /* Iterate over code points */
8769 for (i = 0; i < length; i++) {
8770 Py_UNICODE ch =s[i];
8771 if (ch > 127) {
8772 int decimal = Py_UNICODE_TODECIMAL(ch);
8773 if (decimal >= 0)
8774 p[i] = '0' + decimal;
8775 }
8776 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008777#ifndef DONT_MAKE_RESULT_READY
8778 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008779 Py_DECREF(result);
8780 return NULL;
8781 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008782#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008783 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008784 return result;
8785}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008786/* --- Decimal Encoder ---------------------------------------------------- */
8787
Alexander Belopolsky40018472011-02-26 01:02:56 +00008788int
8789PyUnicode_EncodeDecimal(Py_UNICODE *s,
8790 Py_ssize_t length,
8791 char *output,
8792 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008793{
8794 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008795 PyObject *errorHandler = NULL;
8796 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008797 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008798 const char *encoding = "decimal";
8799 const char *reason = "invalid decimal Unicode string";
8800 /* the following variable is used for caching string comparisons
8801 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8802 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008803
8804 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008805 PyErr_BadArgument();
8806 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008807 }
8808
8809 p = s;
8810 end = s + length;
8811 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008812 register Py_UNICODE ch = *p;
8813 int decimal;
8814 PyObject *repunicode;
8815 Py_ssize_t repsize;
8816 Py_ssize_t newpos;
8817 Py_UNICODE *uni2;
8818 Py_UNICODE *collstart;
8819 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008820
Benjamin Peterson29060642009-01-31 22:14:21 +00008821 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008822 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008823 ++p;
8824 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008825 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008826 decimal = Py_UNICODE_TODECIMAL(ch);
8827 if (decimal >= 0) {
8828 *output++ = '0' + decimal;
8829 ++p;
8830 continue;
8831 }
8832 if (0 < ch && ch < 256) {
8833 *output++ = (char)ch;
8834 ++p;
8835 continue;
8836 }
8837 /* All other characters are considered unencodable */
8838 collstart = p;
8839 collend = p+1;
8840 while (collend < end) {
8841 if ((0 < *collend && *collend < 256) ||
8842 !Py_UNICODE_ISSPACE(*collend) ||
8843 Py_UNICODE_TODECIMAL(*collend))
8844 break;
8845 }
8846 /* cache callback name lookup
8847 * (if not done yet, i.e. it's the first error) */
8848 if (known_errorHandler==-1) {
8849 if ((errors==NULL) || (!strcmp(errors, "strict")))
8850 known_errorHandler = 1;
8851 else if (!strcmp(errors, "replace"))
8852 known_errorHandler = 2;
8853 else if (!strcmp(errors, "ignore"))
8854 known_errorHandler = 3;
8855 else if (!strcmp(errors, "xmlcharrefreplace"))
8856 known_errorHandler = 4;
8857 else
8858 known_errorHandler = 0;
8859 }
8860 switch (known_errorHandler) {
8861 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008862 unicode = PyUnicode_FromUnicode(s, length);
8863 if (unicode == NULL)
8864 goto onError;
8865 raise_encode_exception(&exc, encoding, unicode, collstart-s, collend-s, reason);
8866 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008867 goto onError;
8868 case 2: /* replace */
8869 for (p = collstart; p < collend; ++p)
8870 *output++ = '?';
8871 /* fall through */
8872 case 3: /* ignore */
8873 p = collend;
8874 break;
8875 case 4: /* xmlcharrefreplace */
8876 /* generate replacement (temporarily (mis)uses p) */
8877 for (p = collstart; p < collend; ++p)
8878 output += sprintf(output, "&#%d;", (int)*p);
8879 p = collend;
8880 break;
8881 default:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008882 unicode = PyUnicode_FromUnicode(s, length);
8883 if (unicode == NULL)
8884 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008885 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008886 encoding, reason, unicode, &exc,
Benjamin Peterson29060642009-01-31 22:14:21 +00008887 collstart-s, collend-s, &newpos);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008888 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008889 if (repunicode == NULL)
8890 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008891 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008892 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008893 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8894 Py_DECREF(repunicode);
8895 goto onError;
8896 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008897 /* generate replacement */
8898 repsize = PyUnicode_GET_SIZE(repunicode);
8899 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8900 Py_UNICODE ch = *uni2;
8901 if (Py_UNICODE_ISSPACE(ch))
8902 *output++ = ' ';
8903 else {
8904 decimal = Py_UNICODE_TODECIMAL(ch);
8905 if (decimal >= 0)
8906 *output++ = '0' + decimal;
8907 else if (0 < ch && ch < 256)
8908 *output++ = (char)ch;
8909 else {
8910 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008911 unicode = PyUnicode_FromUnicode(s, length);
8912 if (unicode == NULL)
8913 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008914 raise_encode_exception(&exc, encoding,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008915 unicode, collstart-s, collend-s, reason);
8916 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008917 goto onError;
8918 }
8919 }
8920 }
8921 p = s + newpos;
8922 Py_DECREF(repunicode);
8923 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008924 }
8925 /* 0-terminate the output string */
8926 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008927 Py_XDECREF(exc);
8928 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008929 return 0;
8930
Benjamin Peterson29060642009-01-31 22:14:21 +00008931 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008932 Py_XDECREF(exc);
8933 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008934 return -1;
8935}
8936
Guido van Rossumd57fd912000-03-10 22:53:23 +00008937/* --- Helpers ------------------------------------------------------------ */
8938
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008939static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008940any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008941 Py_ssize_t start,
8942 Py_ssize_t end)
8943{
8944 int kind1, kind2, kind;
8945 void *buf1, *buf2;
8946 Py_ssize_t len1, len2, result;
8947
8948 kind1 = PyUnicode_KIND(s1);
8949 kind2 = PyUnicode_KIND(s2);
8950 kind = kind1 > kind2 ? kind1 : kind2;
8951 buf1 = PyUnicode_DATA(s1);
8952 buf2 = PyUnicode_DATA(s2);
8953 if (kind1 != kind)
8954 buf1 = _PyUnicode_AsKind(s1, kind);
8955 if (!buf1)
8956 return -2;
8957 if (kind2 != kind)
8958 buf2 = _PyUnicode_AsKind(s2, kind);
8959 if (!buf2) {
8960 if (kind1 != kind) PyMem_Free(buf1);
8961 return -2;
8962 }
8963 len1 = PyUnicode_GET_LENGTH(s1);
8964 len2 = PyUnicode_GET_LENGTH(s2);
8965
Victor Stinner794d5672011-10-10 03:21:36 +02008966 if (direction > 0) {
8967 switch(kind) {
8968 case PyUnicode_1BYTE_KIND:
8969 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8970 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8971 else
8972 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8973 break;
8974 case PyUnicode_2BYTE_KIND:
8975 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8976 break;
8977 case PyUnicode_4BYTE_KIND:
8978 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8979 break;
8980 default:
8981 assert(0); result = -2;
8982 }
8983 }
8984 else {
8985 switch(kind) {
8986 case PyUnicode_1BYTE_KIND:
8987 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8988 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8989 else
8990 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8991 break;
8992 case PyUnicode_2BYTE_KIND:
8993 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8994 break;
8995 case PyUnicode_4BYTE_KIND:
8996 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8997 break;
8998 default:
8999 assert(0); result = -2;
9000 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009001 }
9002
9003 if (kind1 != kind)
9004 PyMem_Free(buf1);
9005 if (kind2 != kind)
9006 PyMem_Free(buf2);
9007
9008 return result;
9009}
9010
9011Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009012_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009013 Py_ssize_t n_buffer,
9014 void *digits, Py_ssize_t n_digits,
9015 Py_ssize_t min_width,
9016 const char *grouping,
9017 const char *thousands_sep)
9018{
9019 switch(kind) {
9020 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009021 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9022 return _PyUnicode_ascii_InsertThousandsGrouping(
9023 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9024 min_width, grouping, thousands_sep);
9025 else
9026 return _PyUnicode_ucs1_InsertThousandsGrouping(
9027 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9028 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009029 case PyUnicode_2BYTE_KIND:
9030 return _PyUnicode_ucs2_InsertThousandsGrouping(
9031 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9032 min_width, grouping, thousands_sep);
9033 case PyUnicode_4BYTE_KIND:
9034 return _PyUnicode_ucs4_InsertThousandsGrouping(
9035 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9036 min_width, grouping, thousands_sep);
9037 }
9038 assert(0);
9039 return -1;
9040}
9041
9042
Thomas Wouters477c8d52006-05-27 19:21:47 +00009043/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009044#define ADJUST_INDICES(start, end, len) \
9045 if (end > len) \
9046 end = len; \
9047 else if (end < 0) { \
9048 end += len; \
9049 if (end < 0) \
9050 end = 0; \
9051 } \
9052 if (start < 0) { \
9053 start += len; \
9054 if (start < 0) \
9055 start = 0; \
9056 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009057
Alexander Belopolsky40018472011-02-26 01:02:56 +00009058Py_ssize_t
9059PyUnicode_Count(PyObject *str,
9060 PyObject *substr,
9061 Py_ssize_t start,
9062 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009063{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009064 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009065 PyObject* str_obj;
9066 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009067 int kind1, kind2, kind;
9068 void *buf1 = NULL, *buf2 = NULL;
9069 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009070
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009071 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009072 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009073 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009074 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009075 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009076 Py_DECREF(str_obj);
9077 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009078 }
Tim Petersced69f82003-09-16 20:30:58 +00009079
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009080 kind1 = PyUnicode_KIND(str_obj);
9081 kind2 = PyUnicode_KIND(sub_obj);
9082 kind = kind1 > kind2 ? kind1 : kind2;
9083 buf1 = PyUnicode_DATA(str_obj);
9084 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009085 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009086 if (!buf1)
9087 goto onError;
9088 buf2 = PyUnicode_DATA(sub_obj);
9089 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009090 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009091 if (!buf2)
9092 goto onError;
9093 len1 = PyUnicode_GET_LENGTH(str_obj);
9094 len2 = PyUnicode_GET_LENGTH(sub_obj);
9095
9096 ADJUST_INDICES(start, end, len1);
9097 switch(kind) {
9098 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009099 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9100 result = asciilib_count(
9101 ((Py_UCS1*)buf1) + start, end - start,
9102 buf2, len2, PY_SSIZE_T_MAX
9103 );
9104 else
9105 result = ucs1lib_count(
9106 ((Py_UCS1*)buf1) + start, end - start,
9107 buf2, len2, PY_SSIZE_T_MAX
9108 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009109 break;
9110 case PyUnicode_2BYTE_KIND:
9111 result = ucs2lib_count(
9112 ((Py_UCS2*)buf1) + start, end - start,
9113 buf2, len2, PY_SSIZE_T_MAX
9114 );
9115 break;
9116 case PyUnicode_4BYTE_KIND:
9117 result = ucs4lib_count(
9118 ((Py_UCS4*)buf1) + start, end - start,
9119 buf2, len2, PY_SSIZE_T_MAX
9120 );
9121 break;
9122 default:
9123 assert(0); result = 0;
9124 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009125
9126 Py_DECREF(sub_obj);
9127 Py_DECREF(str_obj);
9128
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009129 if (kind1 != kind)
9130 PyMem_Free(buf1);
9131 if (kind2 != kind)
9132 PyMem_Free(buf2);
9133
Guido van Rossumd57fd912000-03-10 22:53:23 +00009134 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009135 onError:
9136 Py_DECREF(sub_obj);
9137 Py_DECREF(str_obj);
9138 if (kind1 != kind && buf1)
9139 PyMem_Free(buf1);
9140 if (kind2 != kind && buf2)
9141 PyMem_Free(buf2);
9142 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009143}
9144
Alexander Belopolsky40018472011-02-26 01:02:56 +00009145Py_ssize_t
9146PyUnicode_Find(PyObject *str,
9147 PyObject *sub,
9148 Py_ssize_t start,
9149 Py_ssize_t end,
9150 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009151{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009152 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009153
Guido van Rossumd57fd912000-03-10 22:53:23 +00009154 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009155 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009156 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009157 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009158 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009159 Py_DECREF(str);
9160 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009161 }
Tim Petersced69f82003-09-16 20:30:58 +00009162
Victor Stinner794d5672011-10-10 03:21:36 +02009163 result = any_find_slice(direction,
9164 str, sub, start, end
9165 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009166
Guido van Rossumd57fd912000-03-10 22:53:23 +00009167 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009168 Py_DECREF(sub);
9169
Guido van Rossumd57fd912000-03-10 22:53:23 +00009170 return result;
9171}
9172
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009173Py_ssize_t
9174PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9175 Py_ssize_t start, Py_ssize_t end,
9176 int direction)
9177{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009178 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009179 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009180 if (PyUnicode_READY(str) == -1)
9181 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009182 if (start < 0 || end < 0) {
9183 PyErr_SetString(PyExc_IndexError, "string index out of range");
9184 return -2;
9185 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009186 if (end > PyUnicode_GET_LENGTH(str))
9187 end = PyUnicode_GET_LENGTH(str);
9188 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009189 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9190 kind, end-start, ch, direction);
9191 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009192 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009193 else
9194 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009195}
9196
Alexander Belopolsky40018472011-02-26 01:02:56 +00009197static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009198tailmatch(PyObject *self,
9199 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009200 Py_ssize_t start,
9201 Py_ssize_t end,
9202 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009203{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009204 int kind_self;
9205 int kind_sub;
9206 void *data_self;
9207 void *data_sub;
9208 Py_ssize_t offset;
9209 Py_ssize_t i;
9210 Py_ssize_t end_sub;
9211
9212 if (PyUnicode_READY(self) == -1 ||
9213 PyUnicode_READY(substring) == -1)
9214 return 0;
9215
9216 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009217 return 1;
9218
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009219 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9220 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009221 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009222 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009223
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009224 kind_self = PyUnicode_KIND(self);
9225 data_self = PyUnicode_DATA(self);
9226 kind_sub = PyUnicode_KIND(substring);
9227 data_sub = PyUnicode_DATA(substring);
9228 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9229
9230 if (direction > 0)
9231 offset = end;
9232 else
9233 offset = start;
9234
9235 if (PyUnicode_READ(kind_self, data_self, offset) ==
9236 PyUnicode_READ(kind_sub, data_sub, 0) &&
9237 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9238 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9239 /* If both are of the same kind, memcmp is sufficient */
9240 if (kind_self == kind_sub) {
9241 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009242 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009243 data_sub,
9244 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009245 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009246 }
9247 /* otherwise we have to compare each character by first accesing it */
9248 else {
9249 /* We do not need to compare 0 and len(substring)-1 because
9250 the if statement above ensured already that they are equal
9251 when we end up here. */
9252 // TODO: honor direction and do a forward or backwards search
9253 for (i = 1; i < end_sub; ++i) {
9254 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9255 PyUnicode_READ(kind_sub, data_sub, i))
9256 return 0;
9257 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009258 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009259 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009260 }
9261
9262 return 0;
9263}
9264
Alexander Belopolsky40018472011-02-26 01:02:56 +00009265Py_ssize_t
9266PyUnicode_Tailmatch(PyObject *str,
9267 PyObject *substr,
9268 Py_ssize_t start,
9269 Py_ssize_t end,
9270 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009271{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009272 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009273
Guido van Rossumd57fd912000-03-10 22:53:23 +00009274 str = PyUnicode_FromObject(str);
9275 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009276 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009277 substr = PyUnicode_FromObject(substr);
9278 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009279 Py_DECREF(str);
9280 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009281 }
Tim Petersced69f82003-09-16 20:30:58 +00009282
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009283 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009284 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009285 Py_DECREF(str);
9286 Py_DECREF(substr);
9287 return result;
9288}
9289
Guido van Rossumd57fd912000-03-10 22:53:23 +00009290/* Apply fixfct filter to the Unicode object self and return a
9291 reference to the modified object */
9292
Alexander Belopolsky40018472011-02-26 01:02:56 +00009293static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009294fixup(PyObject *self,
9295 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009296{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009297 PyObject *u;
9298 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009299
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009300 if (PyUnicode_READY(self) == -1)
9301 return NULL;
9302 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
9303 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
9304 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009305 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009306 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009307
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009308 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009309 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009310
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009311 /* fix functions return the new maximum character in a string,
9312 if the kind of the resulting unicode object does not change,
9313 everything is fine. Otherwise we need to change the string kind
9314 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009315 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009316 if (maxchar_new == 0)
9317 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9318 else if (maxchar_new <= 127)
9319 maxchar_new = 127;
9320 else if (maxchar_new <= 255)
9321 maxchar_new = 255;
9322 else if (maxchar_new <= 65535)
9323 maxchar_new = 65535;
9324 else
9325 maxchar_new = 1114111; /* 0x10ffff */
9326
9327 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009328 /* fixfct should return TRUE if it modified the buffer. If
9329 FALSE, return a reference to the original buffer instead
9330 (to save space, not time) */
9331 Py_INCREF(self);
9332 Py_DECREF(u);
Victor Stinner7931d9a2011-11-04 00:22:48 +01009333 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009334 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009335 else if (maxchar_new == maxchar_old) {
9336 return u;
9337 }
9338 else {
9339 /* In case the maximum character changed, we need to
9340 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009341 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009342 if (v == NULL) {
9343 Py_DECREF(u);
9344 return NULL;
9345 }
9346 if (maxchar_new > maxchar_old) {
9347 /* If the maxchar increased so that the kind changed, not all
9348 characters are representable anymore and we need to fix the
9349 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009350 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009351 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009352 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9353 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009354 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009355 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009356 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009357
9358 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009359 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009360 return v;
9361 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009362}
9363
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009364static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009365fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009366{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009367 /* No need to call PyUnicode_READY(self) because this function is only
9368 called as a callback from fixup() which does it already. */
9369 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9370 const int kind = PyUnicode_KIND(self);
9371 void *data = PyUnicode_DATA(self);
9372 int touched = 0;
9373 Py_UCS4 maxchar = 0;
9374 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009375
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009376 for (i = 0; i < len; ++i) {
9377 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9378 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9379 if (up != ch) {
9380 if (up > maxchar)
9381 maxchar = up;
9382 PyUnicode_WRITE(kind, data, i, up);
9383 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009384 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009385 else if (ch > maxchar)
9386 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009387 }
9388
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009389 if (touched)
9390 return maxchar;
9391 else
9392 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009393}
9394
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009395static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009396fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009397{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009398 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9399 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9400 const int kind = PyUnicode_KIND(self);
9401 void *data = PyUnicode_DATA(self);
9402 int touched = 0;
9403 Py_UCS4 maxchar = 0;
9404 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009405
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009406 for(i = 0; i < len; ++i) {
9407 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9408 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9409 if (lo != ch) {
9410 if (lo > maxchar)
9411 maxchar = lo;
9412 PyUnicode_WRITE(kind, data, i, lo);
9413 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009414 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009415 else if (ch > maxchar)
9416 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009417 }
9418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009419 if (touched)
9420 return maxchar;
9421 else
9422 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009423}
9424
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009425static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009426fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009427{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009428 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9429 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9430 const int kind = PyUnicode_KIND(self);
9431 void *data = PyUnicode_DATA(self);
9432 int touched = 0;
9433 Py_UCS4 maxchar = 0;
9434 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009435
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009436 for(i = 0; i < len; ++i) {
9437 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9438 Py_UCS4 nu = 0;
9439
9440 if (Py_UNICODE_ISUPPER(ch))
9441 nu = Py_UNICODE_TOLOWER(ch);
9442 else if (Py_UNICODE_ISLOWER(ch))
9443 nu = Py_UNICODE_TOUPPER(ch);
9444
9445 if (nu != 0) {
9446 if (nu > maxchar)
9447 maxchar = nu;
9448 PyUnicode_WRITE(kind, data, i, nu);
9449 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009450 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009451 else if (ch > maxchar)
9452 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009453 }
9454
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009455 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 +02009462fixcapitalize(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 int touched = 0;
9469 Py_UCS4 maxchar = 0;
9470 Py_ssize_t i = 0;
9471 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009472
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009473 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009474 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009475
9476 ch = PyUnicode_READ(kind, data, i);
9477 if (!Py_UNICODE_ISUPPER(ch)) {
9478 maxchar = Py_UNICODE_TOUPPER(ch);
9479 PyUnicode_WRITE(kind, data, i, maxchar);
9480 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009481 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009482 ++i;
9483 for(; i < len; ++i) {
9484 ch = PyUnicode_READ(kind, data, i);
9485 if (!Py_UNICODE_ISLOWER(ch)) {
9486 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9487 if (lo > maxchar)
9488 maxchar = lo;
9489 PyUnicode_WRITE(kind, data, i, lo);
9490 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009491 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009492 else if (ch > maxchar)
9493 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009494 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009495
9496 if (touched)
9497 return maxchar;
9498 else
9499 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009500}
9501
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009502static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009503fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009504{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009505 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9506 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9507 const int kind = PyUnicode_KIND(self);
9508 void *data = PyUnicode_DATA(self);
9509 Py_UCS4 maxchar = 0;
9510 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009511 int previous_is_cased;
9512
9513 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009514 if (len == 1) {
9515 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9516 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9517 if (ti != ch) {
9518 PyUnicode_WRITE(kind, data, i, ti);
9519 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009520 }
9521 else
9522 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009523 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009524 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009525 for(; i < len; ++i) {
9526 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9527 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009528
Benjamin Peterson29060642009-01-31 22:14:21 +00009529 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009530 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009531 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009532 nu = Py_UNICODE_TOTITLE(ch);
9533
9534 if (nu > maxchar)
9535 maxchar = nu;
9536 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009537
Benjamin Peterson29060642009-01-31 22:14:21 +00009538 if (Py_UNICODE_ISLOWER(ch) ||
9539 Py_UNICODE_ISUPPER(ch) ||
9540 Py_UNICODE_ISTITLE(ch))
9541 previous_is_cased = 1;
9542 else
9543 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009544 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009545 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009546}
9547
Tim Peters8ce9f162004-08-27 01:49:32 +00009548PyObject *
9549PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009550{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009551 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009552 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009553 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009554 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009555 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9556 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009557 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009558 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009559 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009560 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009561 int use_memcpy;
9562 unsigned char *res_data = NULL, *sep_data = NULL;
9563 PyObject *last_obj;
9564 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009565
Tim Peters05eba1f2004-08-27 21:32:02 +00009566 fseq = PySequence_Fast(seq, "");
9567 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009568 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009569 }
9570
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009571 /* NOTE: the following code can't call back into Python code,
9572 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009573 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009574
Tim Peters05eba1f2004-08-27 21:32:02 +00009575 seqlen = PySequence_Fast_GET_SIZE(fseq);
9576 /* If empty sequence, return u"". */
9577 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009578 Py_DECREF(fseq);
9579 Py_INCREF(unicode_empty);
9580 res = unicode_empty;
9581 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009582 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009583
Tim Peters05eba1f2004-08-27 21:32:02 +00009584 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009585 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009586 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009587 if (seqlen == 1) {
9588 if (PyUnicode_CheckExact(items[0])) {
9589 res = items[0];
9590 Py_INCREF(res);
9591 Py_DECREF(fseq);
9592 return res;
9593 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009594 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009595 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009596 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009597 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009598 /* Set up sep and seplen */
9599 if (separator == NULL) {
9600 /* fall back to a blank space separator */
9601 sep = PyUnicode_FromOrdinal(' ');
9602 if (!sep)
9603 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009604 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009605 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009606 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009607 else {
9608 if (!PyUnicode_Check(separator)) {
9609 PyErr_Format(PyExc_TypeError,
9610 "separator: expected str instance,"
9611 " %.80s found",
9612 Py_TYPE(separator)->tp_name);
9613 goto onError;
9614 }
9615 if (PyUnicode_READY(separator))
9616 goto onError;
9617 sep = separator;
9618 seplen = PyUnicode_GET_LENGTH(separator);
9619 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9620 /* inc refcount to keep this code path symmetric with the
9621 above case of a blank separator */
9622 Py_INCREF(sep);
9623 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009624 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009625 }
9626
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009627 /* There are at least two things to join, or else we have a subclass
9628 * of str in the sequence.
9629 * Do a pre-pass to figure out the total amount of space we'll
9630 * need (sz), and see whether all argument are strings.
9631 */
9632 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009633#ifdef Py_DEBUG
9634 use_memcpy = 0;
9635#else
9636 use_memcpy = 1;
9637#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009638 for (i = 0; i < seqlen; i++) {
9639 const Py_ssize_t old_sz = sz;
9640 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009641 if (!PyUnicode_Check(item)) {
9642 PyErr_Format(PyExc_TypeError,
9643 "sequence item %zd: expected str instance,"
9644 " %.80s found",
9645 i, Py_TYPE(item)->tp_name);
9646 goto onError;
9647 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009648 if (PyUnicode_READY(item) == -1)
9649 goto onError;
9650 sz += PyUnicode_GET_LENGTH(item);
9651 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009652 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009653 if (i != 0)
9654 sz += seplen;
9655 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9656 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009657 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009658 goto onError;
9659 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009660 if (use_memcpy && last_obj != NULL) {
9661 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9662 use_memcpy = 0;
9663 }
9664 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009665 }
Tim Petersced69f82003-09-16 20:30:58 +00009666
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009667 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009668 if (res == NULL)
9669 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009670
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009671 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009672#ifdef Py_DEBUG
9673 use_memcpy = 0;
9674#else
9675 if (use_memcpy) {
9676 res_data = PyUnicode_1BYTE_DATA(res);
9677 kind = PyUnicode_KIND(res);
9678 if (seplen != 0)
9679 sep_data = PyUnicode_1BYTE_DATA(sep);
9680 }
9681#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009682 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009683 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009684 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009685 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009686 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009687 if (use_memcpy) {
9688 Py_MEMCPY(res_data,
9689 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009690 kind * seplen);
9691 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009692 }
9693 else {
9694 copy_characters(res, res_offset, sep, 0, seplen);
9695 res_offset += seplen;
9696 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009697 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009698 itemlen = PyUnicode_GET_LENGTH(item);
9699 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009700 if (use_memcpy) {
9701 Py_MEMCPY(res_data,
9702 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009703 kind * itemlen);
9704 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009705 }
9706 else {
9707 copy_characters(res, res_offset, item, 0, itemlen);
9708 res_offset += itemlen;
9709 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009710 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009711 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009712 if (use_memcpy)
9713 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009714 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009715 else
9716 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009717
Tim Peters05eba1f2004-08-27 21:32:02 +00009718 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009719 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009720 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009721 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009722
Benjamin Peterson29060642009-01-31 22:14:21 +00009723 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009724 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009725 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009726 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009727 return NULL;
9728}
9729
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009730#define FILL(kind, data, value, start, length) \
9731 do { \
9732 Py_ssize_t i_ = 0; \
9733 assert(kind != PyUnicode_WCHAR_KIND); \
9734 switch ((kind)) { \
9735 case PyUnicode_1BYTE_KIND: { \
9736 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9737 memset(to_, (unsigned char)value, length); \
9738 break; \
9739 } \
9740 case PyUnicode_2BYTE_KIND: { \
9741 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9742 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9743 break; \
9744 } \
9745 default: { \
9746 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9747 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9748 break; \
9749 } \
9750 } \
9751 } while (0)
9752
Victor Stinner9310abb2011-10-05 00:59:23 +02009753static PyObject *
9754pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009755 Py_ssize_t left,
9756 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009757 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009758{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009759 PyObject *u;
9760 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009761 int kind;
9762 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009763
9764 if (left < 0)
9765 left = 0;
9766 if (right < 0)
9767 right = 0;
9768
Tim Peters7a29bd52001-09-12 03:03:31 +00009769 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009770 Py_INCREF(self);
9771 return self;
9772 }
9773
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009774 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9775 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009776 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9777 return NULL;
9778 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009779 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9780 if (fill > maxchar)
9781 maxchar = fill;
9782 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009783 if (!u)
9784 return NULL;
9785
9786 kind = PyUnicode_KIND(u);
9787 data = PyUnicode_DATA(u);
9788 if (left)
9789 FILL(kind, data, fill, 0, left);
9790 if (right)
9791 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009792 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009793 assert(_PyUnicode_CheckConsistency(u, 1));
9794 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009795}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009796#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009797
Alexander Belopolsky40018472011-02-26 01:02:56 +00009798PyObject *
9799PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009800{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009801 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009802
9803 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009804 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009805 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009806
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009807 switch(PyUnicode_KIND(string)) {
9808 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009809 if (PyUnicode_IS_ASCII(string))
9810 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009811 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009812 PyUnicode_GET_LENGTH(string), keepends);
9813 else
9814 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009815 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009816 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009817 break;
9818 case PyUnicode_2BYTE_KIND:
9819 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009820 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009821 PyUnicode_GET_LENGTH(string), keepends);
9822 break;
9823 case PyUnicode_4BYTE_KIND:
9824 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009825 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009826 PyUnicode_GET_LENGTH(string), keepends);
9827 break;
9828 default:
9829 assert(0);
9830 list = 0;
9831 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009832 Py_DECREF(string);
9833 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009834}
9835
Alexander Belopolsky40018472011-02-26 01:02:56 +00009836static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009837split(PyObject *self,
9838 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009839 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009840{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009841 int kind1, kind2, kind;
9842 void *buf1, *buf2;
9843 Py_ssize_t len1, len2;
9844 PyObject* out;
9845
Guido van Rossumd57fd912000-03-10 22:53:23 +00009846 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009847 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009848
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009849 if (PyUnicode_READY(self) == -1)
9850 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009851
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009852 if (substring == NULL)
9853 switch(PyUnicode_KIND(self)) {
9854 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009855 if (PyUnicode_IS_ASCII(self))
9856 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009857 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009858 PyUnicode_GET_LENGTH(self), maxcount
9859 );
9860 else
9861 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009862 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009863 PyUnicode_GET_LENGTH(self), maxcount
9864 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009865 case PyUnicode_2BYTE_KIND:
9866 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009867 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009868 PyUnicode_GET_LENGTH(self), maxcount
9869 );
9870 case PyUnicode_4BYTE_KIND:
9871 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009872 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009873 PyUnicode_GET_LENGTH(self), maxcount
9874 );
9875 default:
9876 assert(0);
9877 return NULL;
9878 }
9879
9880 if (PyUnicode_READY(substring) == -1)
9881 return NULL;
9882
9883 kind1 = PyUnicode_KIND(self);
9884 kind2 = PyUnicode_KIND(substring);
9885 kind = kind1 > kind2 ? kind1 : kind2;
9886 buf1 = PyUnicode_DATA(self);
9887 buf2 = PyUnicode_DATA(substring);
9888 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009889 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009890 if (!buf1)
9891 return NULL;
9892 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009893 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009894 if (!buf2) {
9895 if (kind1 != kind) PyMem_Free(buf1);
9896 return NULL;
9897 }
9898 len1 = PyUnicode_GET_LENGTH(self);
9899 len2 = PyUnicode_GET_LENGTH(substring);
9900
9901 switch(kind) {
9902 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009903 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9904 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009905 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009906 else
9907 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009908 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009909 break;
9910 case PyUnicode_2BYTE_KIND:
9911 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009912 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009913 break;
9914 case PyUnicode_4BYTE_KIND:
9915 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009916 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009917 break;
9918 default:
9919 out = NULL;
9920 }
9921 if (kind1 != kind)
9922 PyMem_Free(buf1);
9923 if (kind2 != kind)
9924 PyMem_Free(buf2);
9925 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009926}
9927
Alexander Belopolsky40018472011-02-26 01:02:56 +00009928static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009929rsplit(PyObject *self,
9930 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009931 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009932{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009933 int kind1, kind2, kind;
9934 void *buf1, *buf2;
9935 Py_ssize_t len1, len2;
9936 PyObject* out;
9937
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009938 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009939 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009940
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009941 if (PyUnicode_READY(self) == -1)
9942 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009943
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009944 if (substring == NULL)
9945 switch(PyUnicode_KIND(self)) {
9946 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009947 if (PyUnicode_IS_ASCII(self))
9948 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009949 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009950 PyUnicode_GET_LENGTH(self), maxcount
9951 );
9952 else
9953 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009954 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009955 PyUnicode_GET_LENGTH(self), maxcount
9956 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009957 case PyUnicode_2BYTE_KIND:
9958 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009959 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009960 PyUnicode_GET_LENGTH(self), maxcount
9961 );
9962 case PyUnicode_4BYTE_KIND:
9963 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009964 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009965 PyUnicode_GET_LENGTH(self), maxcount
9966 );
9967 default:
9968 assert(0);
9969 return NULL;
9970 }
9971
9972 if (PyUnicode_READY(substring) == -1)
9973 return NULL;
9974
9975 kind1 = PyUnicode_KIND(self);
9976 kind2 = PyUnicode_KIND(substring);
9977 kind = kind1 > kind2 ? kind1 : kind2;
9978 buf1 = PyUnicode_DATA(self);
9979 buf2 = PyUnicode_DATA(substring);
9980 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009981 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009982 if (!buf1)
9983 return NULL;
9984 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009985 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009986 if (!buf2) {
9987 if (kind1 != kind) PyMem_Free(buf1);
9988 return NULL;
9989 }
9990 len1 = PyUnicode_GET_LENGTH(self);
9991 len2 = PyUnicode_GET_LENGTH(substring);
9992
9993 switch(kind) {
9994 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009995 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9996 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009997 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009998 else
9999 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010000 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010001 break;
10002 case PyUnicode_2BYTE_KIND:
10003 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010004 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010005 break;
10006 case PyUnicode_4BYTE_KIND:
10007 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010008 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010009 break;
10010 default:
10011 out = NULL;
10012 }
10013 if (kind1 != kind)
10014 PyMem_Free(buf1);
10015 if (kind2 != kind)
10016 PyMem_Free(buf2);
10017 return out;
10018}
10019
10020static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010021anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10022 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010023{
10024 switch(kind) {
10025 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010026 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10027 return asciilib_find(buf1, len1, buf2, len2, offset);
10028 else
10029 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010030 case PyUnicode_2BYTE_KIND:
10031 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10032 case PyUnicode_4BYTE_KIND:
10033 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10034 }
10035 assert(0);
10036 return -1;
10037}
10038
10039static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010040anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10041 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010042{
10043 switch(kind) {
10044 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010045 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10046 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10047 else
10048 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010049 case PyUnicode_2BYTE_KIND:
10050 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10051 case PyUnicode_4BYTE_KIND:
10052 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10053 }
10054 assert(0);
10055 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010056}
10057
Alexander Belopolsky40018472011-02-26 01:02:56 +000010058static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010059replace(PyObject *self, PyObject *str1,
10060 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010061{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010062 PyObject *u;
10063 char *sbuf = PyUnicode_DATA(self);
10064 char *buf1 = PyUnicode_DATA(str1);
10065 char *buf2 = PyUnicode_DATA(str2);
10066 int srelease = 0, release1 = 0, release2 = 0;
10067 int skind = PyUnicode_KIND(self);
10068 int kind1 = PyUnicode_KIND(str1);
10069 int kind2 = PyUnicode_KIND(str2);
10070 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10071 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10072 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010073 int mayshrink;
10074 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010075
10076 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010077 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010079 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010080
Victor Stinner59de0ee2011-10-07 10:01:28 +020010081 if (str1 == str2)
10082 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010083 if (skind < kind1)
10084 /* substring too wide to be present */
10085 goto nothing;
10086
Victor Stinner49a0a212011-10-12 23:46:10 +020010087 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10088 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10089 /* Replacing str1 with str2 may cause a maxchar reduction in the
10090 result string. */
10091 mayshrink = (maxchar_str2 < maxchar);
10092 maxchar = Py_MAX(maxchar, maxchar_str2);
10093
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010095 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010096 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010097 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010098 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010099 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010100 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010101 Py_UCS4 u1, u2;
10102 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010103 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010104 if (findchar(sbuf, PyUnicode_KIND(self),
10105 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010106 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010107 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010109 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010110 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010111 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010112 rkind = PyUnicode_KIND(u);
10113 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10114 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010115 if (--maxcount < 0)
10116 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010117 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010118 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010119 }
10120 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010121 int rkind = skind;
10122 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010123
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010124 if (kind1 < rkind) {
10125 /* widen substring */
10126 buf1 = _PyUnicode_AsKind(str1, rkind);
10127 if (!buf1) goto error;
10128 release1 = 1;
10129 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010130 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010131 if (i < 0)
10132 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010133 if (rkind > kind2) {
10134 /* widen replacement */
10135 buf2 = _PyUnicode_AsKind(str2, rkind);
10136 if (!buf2) goto error;
10137 release2 = 1;
10138 }
10139 else if (rkind < kind2) {
10140 /* widen self and buf1 */
10141 rkind = kind2;
10142 if (release1) PyMem_Free(buf1);
10143 sbuf = _PyUnicode_AsKind(self, rkind);
10144 if (!sbuf) goto error;
10145 srelease = 1;
10146 buf1 = _PyUnicode_AsKind(str1, rkind);
10147 if (!buf1) goto error;
10148 release1 = 1;
10149 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010150 u = PyUnicode_New(slen, maxchar);
10151 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010153 assert(PyUnicode_KIND(u) == rkind);
10154 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010155
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010156 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010157 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010158 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010160 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010161 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010162
10163 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010164 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010165 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010166 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010167 if (i == -1)
10168 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010169 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010171 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010172 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010173 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010174 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010175 }
10176 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 Py_ssize_t n, i, j, ires;
10178 Py_ssize_t product, new_size;
10179 int rkind = skind;
10180 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010181
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010182 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010183 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010184 buf1 = _PyUnicode_AsKind(str1, rkind);
10185 if (!buf1) goto error;
10186 release1 = 1;
10187 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010188 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010189 if (n == 0)
10190 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010192 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010193 buf2 = _PyUnicode_AsKind(str2, rkind);
10194 if (!buf2) goto error;
10195 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010196 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010197 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010198 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010199 rkind = kind2;
10200 sbuf = _PyUnicode_AsKind(self, rkind);
10201 if (!sbuf) goto error;
10202 srelease = 1;
10203 if (release1) PyMem_Free(buf1);
10204 buf1 = _PyUnicode_AsKind(str1, rkind);
10205 if (!buf1) goto error;
10206 release1 = 1;
10207 }
10208 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10209 PyUnicode_GET_LENGTH(str1))); */
10210 product = n * (len2-len1);
10211 if ((product / (len2-len1)) != n) {
10212 PyErr_SetString(PyExc_OverflowError,
10213 "replace string is too long");
10214 goto error;
10215 }
10216 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010217 if (new_size == 0) {
10218 Py_INCREF(unicode_empty);
10219 u = unicode_empty;
10220 goto done;
10221 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010222 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10223 PyErr_SetString(PyExc_OverflowError,
10224 "replace string is too long");
10225 goto error;
10226 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010227 u = PyUnicode_New(new_size, maxchar);
10228 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010230 assert(PyUnicode_KIND(u) == rkind);
10231 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 ires = i = 0;
10233 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010234 while (n-- > 0) {
10235 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010236 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010237 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010238 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010239 if (j == -1)
10240 break;
10241 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010242 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010243 memcpy(res + rkind * ires,
10244 sbuf + rkind * i,
10245 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010246 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010247 }
10248 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010249 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010250 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010251 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010252 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010253 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010254 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010255 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010256 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010257 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010258 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010259 memcpy(res + rkind * ires,
10260 sbuf + rkind * i,
10261 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010262 }
10263 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010264 /* interleave */
10265 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010266 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010267 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010268 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010270 if (--n <= 0)
10271 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010272 memcpy(res + rkind * ires,
10273 sbuf + rkind * i,
10274 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010275 ires++;
10276 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010277 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010278 memcpy(res + rkind * ires,
10279 sbuf + rkind * i,
10280 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010281 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010282 }
10283
10284 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010285 unicode_adjust_maxchar(&u);
10286 if (u == NULL)
10287 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010288 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010289
10290 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291 if (srelease)
10292 PyMem_FREE(sbuf);
10293 if (release1)
10294 PyMem_FREE(buf1);
10295 if (release2)
10296 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010297 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010298 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010299
Benjamin Peterson29060642009-01-31 22:14:21 +000010300 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010301 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010302 if (srelease)
10303 PyMem_FREE(sbuf);
10304 if (release1)
10305 PyMem_FREE(buf1);
10306 if (release2)
10307 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010308 if (PyUnicode_CheckExact(self)) {
10309 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010310 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010311 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010312 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010313 error:
10314 if (srelease && sbuf)
10315 PyMem_FREE(sbuf);
10316 if (release1 && buf1)
10317 PyMem_FREE(buf1);
10318 if (release2 && buf2)
10319 PyMem_FREE(buf2);
10320 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010321}
10322
10323/* --- Unicode Object Methods --------------------------------------------- */
10324
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010325PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010326 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010327\n\
10328Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010329characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010330
10331static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010332unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010333{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010334 return fixup(self, fixtitle);
10335}
10336
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010337PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010338 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010339\n\
10340Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010341have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010342
10343static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010344unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010345{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010346 return fixup(self, fixcapitalize);
10347}
10348
10349#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010350PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010351 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010352\n\
10353Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010354normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010355
10356static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010357unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010358{
10359 PyObject *list;
10360 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010361 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010362
Guido van Rossumd57fd912000-03-10 22:53:23 +000010363 /* Split into words */
10364 list = split(self, NULL, -1);
10365 if (!list)
10366 return NULL;
10367
10368 /* Capitalize each word */
10369 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010370 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010371 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010372 if (item == NULL)
10373 goto onError;
10374 Py_DECREF(PyList_GET_ITEM(list, i));
10375 PyList_SET_ITEM(list, i, item);
10376 }
10377
10378 /* Join the words to form a new string */
10379 item = PyUnicode_Join(NULL, list);
10380
Benjamin Peterson29060642009-01-31 22:14:21 +000010381 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010382 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010383 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010384}
10385#endif
10386
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010387/* Argument converter. Coerces to a single unicode character */
10388
10389static int
10390convert_uc(PyObject *obj, void *addr)
10391{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010392 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010393 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010394
Benjamin Peterson14339b62009-01-31 16:36:08 +000010395 uniobj = PyUnicode_FromObject(obj);
10396 if (uniobj == NULL) {
10397 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010398 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010399 return 0;
10400 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010401 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010402 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010403 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010404 Py_DECREF(uniobj);
10405 return 0;
10406 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010407 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010408 Py_DECREF(uniobj);
10409 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010410}
10411
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010412PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010413 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010414\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010415Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010416done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010417
10418static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010419unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010420{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010421 Py_ssize_t marg, left;
10422 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010423 Py_UCS4 fillchar = ' ';
10424
Victor Stinnere9a29352011-10-01 02:14:59 +020010425 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010426 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010427
Victor Stinnere9a29352011-10-01 02:14:59 +020010428 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010429 return NULL;
10430
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010431 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010432 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010433 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010434 }
10435
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010436 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010437 left = marg / 2 + (marg & width & 1);
10438
Victor Stinner9310abb2011-10-05 00:59:23 +020010439 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010440}
10441
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010442/* This function assumes that str1 and str2 are readied by the caller. */
10443
Marc-André Lemburge5034372000-08-08 08:04:29 +000010444static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010445unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010446{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010447 int kind1, kind2;
10448 void *data1, *data2;
10449 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010450
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010451 kind1 = PyUnicode_KIND(str1);
10452 kind2 = PyUnicode_KIND(str2);
10453 data1 = PyUnicode_DATA(str1);
10454 data2 = PyUnicode_DATA(str2);
10455 len1 = PyUnicode_GET_LENGTH(str1);
10456 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010457
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010458 for (i = 0; i < len1 && i < len2; ++i) {
10459 Py_UCS4 c1, c2;
10460 c1 = PyUnicode_READ(kind1, data1, i);
10461 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010462
10463 if (c1 != c2)
10464 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010465 }
10466
10467 return (len1 < len2) ? -1 : (len1 != len2);
10468}
10469
Alexander Belopolsky40018472011-02-26 01:02:56 +000010470int
10471PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010472{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010473 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10474 if (PyUnicode_READY(left) == -1 ||
10475 PyUnicode_READY(right) == -1)
10476 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010477 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010478 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010479 PyErr_Format(PyExc_TypeError,
10480 "Can't compare %.100s and %.100s",
10481 left->ob_type->tp_name,
10482 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010483 return -1;
10484}
10485
Martin v. Löwis5b222132007-06-10 09:51:05 +000010486int
10487PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10488{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010489 Py_ssize_t i;
10490 int kind;
10491 void *data;
10492 Py_UCS4 chr;
10493
Victor Stinner910337b2011-10-03 03:20:16 +020010494 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010495 if (PyUnicode_READY(uni) == -1)
10496 return -1;
10497 kind = PyUnicode_KIND(uni);
10498 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010499 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010500 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10501 if (chr != str[i])
10502 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010503 /* This check keeps Python strings that end in '\0' from comparing equal
10504 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010505 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010506 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010507 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010508 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010509 return 0;
10510}
10511
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010512
Benjamin Peterson29060642009-01-31 22:14:21 +000010513#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010514 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010515
Alexander Belopolsky40018472011-02-26 01:02:56 +000010516PyObject *
10517PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010518{
10519 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010520
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010521 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10522 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010523 if (PyUnicode_READY(left) == -1 ||
10524 PyUnicode_READY(right) == -1)
10525 return NULL;
10526 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10527 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010528 if (op == Py_EQ) {
10529 Py_INCREF(Py_False);
10530 return Py_False;
10531 }
10532 if (op == Py_NE) {
10533 Py_INCREF(Py_True);
10534 return Py_True;
10535 }
10536 }
10537 if (left == right)
10538 result = 0;
10539 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010540 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010541
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010542 /* Convert the return value to a Boolean */
10543 switch (op) {
10544 case Py_EQ:
10545 v = TEST_COND(result == 0);
10546 break;
10547 case Py_NE:
10548 v = TEST_COND(result != 0);
10549 break;
10550 case Py_LE:
10551 v = TEST_COND(result <= 0);
10552 break;
10553 case Py_GE:
10554 v = TEST_COND(result >= 0);
10555 break;
10556 case Py_LT:
10557 v = TEST_COND(result == -1);
10558 break;
10559 case Py_GT:
10560 v = TEST_COND(result == 1);
10561 break;
10562 default:
10563 PyErr_BadArgument();
10564 return NULL;
10565 }
10566 Py_INCREF(v);
10567 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010568 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010569
Brian Curtindfc80e32011-08-10 20:28:54 -050010570 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010571}
10572
Alexander Belopolsky40018472011-02-26 01:02:56 +000010573int
10574PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010575{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010576 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 int kind1, kind2, kind;
10578 void *buf1, *buf2;
10579 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010580 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010581
10582 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010583 sub = PyUnicode_FromObject(element);
10584 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010585 PyErr_Format(PyExc_TypeError,
10586 "'in <string>' requires string as left operand, not %s",
10587 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010588 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010589 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010590 if (PyUnicode_READY(sub) == -1)
10591 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010592
Thomas Wouters477c8d52006-05-27 19:21:47 +000010593 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010594 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010595 Py_DECREF(sub);
10596 return -1;
10597 }
10598
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010599 kind1 = PyUnicode_KIND(str);
10600 kind2 = PyUnicode_KIND(sub);
10601 kind = kind1 > kind2 ? kind1 : kind2;
10602 buf1 = PyUnicode_DATA(str);
10603 buf2 = PyUnicode_DATA(sub);
10604 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010605 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010606 if (!buf1) {
10607 Py_DECREF(sub);
10608 return -1;
10609 }
10610 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010611 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010612 if (!buf2) {
10613 Py_DECREF(sub);
10614 if (kind1 != kind) PyMem_Free(buf1);
10615 return -1;
10616 }
10617 len1 = PyUnicode_GET_LENGTH(str);
10618 len2 = PyUnicode_GET_LENGTH(sub);
10619
10620 switch(kind) {
10621 case PyUnicode_1BYTE_KIND:
10622 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10623 break;
10624 case PyUnicode_2BYTE_KIND:
10625 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10626 break;
10627 case PyUnicode_4BYTE_KIND:
10628 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10629 break;
10630 default:
10631 result = -1;
10632 assert(0);
10633 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010634
10635 Py_DECREF(str);
10636 Py_DECREF(sub);
10637
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010638 if (kind1 != kind)
10639 PyMem_Free(buf1);
10640 if (kind2 != kind)
10641 PyMem_Free(buf2);
10642
Guido van Rossum403d68b2000-03-13 15:55:09 +000010643 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010644}
10645
Guido van Rossumd57fd912000-03-10 22:53:23 +000010646/* Concat to string or Unicode object giving a new Unicode object. */
10647
Alexander Belopolsky40018472011-02-26 01:02:56 +000010648PyObject *
10649PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010650{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010651 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010652 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010653
10654 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010655 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010656 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010657 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010658 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010659 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010660 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010661
10662 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010663 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010664 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010665 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010666 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010667 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010668 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010669 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010670 }
10671
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010672 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010673 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10674 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010675
Guido van Rossumd57fd912000-03-10 22:53:23 +000010676 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010677 w = PyUnicode_New(
10678 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10679 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010680 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010681 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010682 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10683 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010684 Py_DECREF(u);
10685 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010686 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010687 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010688
Benjamin Peterson29060642009-01-31 22:14:21 +000010689 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010690 Py_XDECREF(u);
10691 Py_XDECREF(v);
10692 return NULL;
10693}
10694
Victor Stinnerb0923652011-10-04 01:17:31 +020010695static void
10696unicode_append_inplace(PyObject **p_left, PyObject *right)
10697{
10698 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010699
10700 assert(PyUnicode_IS_READY(*p_left));
10701 assert(PyUnicode_IS_READY(right));
10702
10703 left_len = PyUnicode_GET_LENGTH(*p_left);
10704 right_len = PyUnicode_GET_LENGTH(right);
10705 if (left_len > PY_SSIZE_T_MAX - right_len) {
10706 PyErr_SetString(PyExc_OverflowError,
10707 "strings are too large to concat");
10708 goto error;
10709 }
10710 new_len = left_len + right_len;
10711
10712 /* Now we own the last reference to 'left', so we can resize it
10713 * in-place.
10714 */
10715 if (unicode_resize(p_left, new_len) != 0) {
10716 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10717 * deallocated so it cannot be put back into
10718 * 'variable'. The MemoryError is raised when there
10719 * is no value in 'variable', which might (very
10720 * remotely) be a cause of incompatibilities.
10721 */
10722 goto error;
10723 }
10724 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010725 copy_characters(*p_left, left_len, right, 0, right_len);
10726 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010727 return;
10728
10729error:
10730 Py_DECREF(*p_left);
10731 *p_left = NULL;
10732}
10733
Walter Dörwald1ab83302007-05-18 17:15:44 +000010734void
Victor Stinner23e56682011-10-03 03:54:37 +020010735PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010736{
Victor Stinner23e56682011-10-03 03:54:37 +020010737 PyObject *left, *res;
10738
10739 if (p_left == NULL) {
10740 if (!PyErr_Occurred())
10741 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010742 return;
10743 }
Victor Stinner23e56682011-10-03 03:54:37 +020010744 left = *p_left;
10745 if (right == NULL || !PyUnicode_Check(left)) {
10746 if (!PyErr_Occurred())
10747 PyErr_BadInternalCall();
10748 goto error;
10749 }
10750
Victor Stinnere1335c72011-10-04 20:53:03 +020010751 if (PyUnicode_READY(left))
10752 goto error;
10753 if (PyUnicode_READY(right))
10754 goto error;
10755
Victor Stinner23e56682011-10-03 03:54:37 +020010756 if (PyUnicode_CheckExact(left) && left != unicode_empty
10757 && PyUnicode_CheckExact(right) && right != unicode_empty
10758 && unicode_resizable(left)
10759 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10760 || _PyUnicode_WSTR(left) != NULL))
10761 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010762 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10763 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010764 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010765 not so different than duplicating the string. */
10766 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010767 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010768 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010769 if (p_left != NULL)
10770 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010771 return;
10772 }
10773 }
10774
10775 res = PyUnicode_Concat(left, right);
10776 if (res == NULL)
10777 goto error;
10778 Py_DECREF(left);
10779 *p_left = res;
10780 return;
10781
10782error:
10783 Py_DECREF(*p_left);
10784 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010785}
10786
10787void
10788PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10789{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010790 PyUnicode_Append(pleft, right);
10791 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010792}
10793
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010794PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010795 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010796\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010797Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010798string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010799interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010800
10801static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010802unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010803{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010804 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010805 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010806 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010807 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010808 int kind1, kind2, kind;
10809 void *buf1, *buf2;
10810 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010811
Jesus Ceaac451502011-04-20 17:09:23 +020010812 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10813 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010814 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010815
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010816 kind1 = PyUnicode_KIND(self);
10817 kind2 = PyUnicode_KIND(substring);
10818 kind = kind1 > kind2 ? kind1 : kind2;
10819 buf1 = PyUnicode_DATA(self);
10820 buf2 = PyUnicode_DATA(substring);
10821 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010822 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010823 if (!buf1) {
10824 Py_DECREF(substring);
10825 return NULL;
10826 }
10827 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010828 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010829 if (!buf2) {
10830 Py_DECREF(substring);
10831 if (kind1 != kind) PyMem_Free(buf1);
10832 return NULL;
10833 }
10834 len1 = PyUnicode_GET_LENGTH(self);
10835 len2 = PyUnicode_GET_LENGTH(substring);
10836
10837 ADJUST_INDICES(start, end, len1);
10838 switch(kind) {
10839 case PyUnicode_1BYTE_KIND:
10840 iresult = ucs1lib_count(
10841 ((Py_UCS1*)buf1) + start, end - start,
10842 buf2, len2, PY_SSIZE_T_MAX
10843 );
10844 break;
10845 case PyUnicode_2BYTE_KIND:
10846 iresult = ucs2lib_count(
10847 ((Py_UCS2*)buf1) + start, end - start,
10848 buf2, len2, PY_SSIZE_T_MAX
10849 );
10850 break;
10851 case PyUnicode_4BYTE_KIND:
10852 iresult = ucs4lib_count(
10853 ((Py_UCS4*)buf1) + start, end - start,
10854 buf2, len2, PY_SSIZE_T_MAX
10855 );
10856 break;
10857 default:
10858 assert(0); iresult = 0;
10859 }
10860
10861 result = PyLong_FromSsize_t(iresult);
10862
10863 if (kind1 != kind)
10864 PyMem_Free(buf1);
10865 if (kind2 != kind)
10866 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010867
10868 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010869
Guido van Rossumd57fd912000-03-10 22:53:23 +000010870 return result;
10871}
10872
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010873PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010874 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010875\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010876Encode S using the codec registered for encoding. Default encoding\n\
10877is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010878handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010879a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10880'xmlcharrefreplace' as well as any other name registered with\n\
10881codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010882
10883static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010884unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010885{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010886 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010887 char *encoding = NULL;
10888 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010889
Benjamin Peterson308d6372009-09-18 21:42:35 +000010890 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10891 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010892 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010893 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010894}
10895
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010896PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010897 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010898\n\
10899Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010900If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010901
10902static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010903unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010904{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010905 Py_ssize_t i, j, line_pos, src_len, incr;
10906 Py_UCS4 ch;
10907 PyObject *u;
10908 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010909 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010910 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010911 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010912
10913 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010914 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010915
Antoine Pitrou22425222011-10-04 19:10:51 +020010916 if (PyUnicode_READY(self) == -1)
10917 return NULL;
10918
Thomas Wouters7e474022000-07-16 12:04:32 +000010919 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010920 src_len = PyUnicode_GET_LENGTH(self);
10921 i = j = line_pos = 0;
10922 kind = PyUnicode_KIND(self);
10923 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010924 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010925 for (; i < src_len; i++) {
10926 ch = PyUnicode_READ(kind, src_data, i);
10927 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010928 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010929 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010930 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010931 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010932 goto overflow;
10933 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010934 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010935 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010936 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010937 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010938 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010939 goto overflow;
10940 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010941 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010942 if (ch == '\n' || ch == '\r')
10943 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010944 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010945 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010946 if (!found && PyUnicode_CheckExact(self)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +010010947 Py_INCREF(self);
10948 return self;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010949 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010950
Guido van Rossumd57fd912000-03-10 22:53:23 +000010951 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010952 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010953 if (!u)
10954 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010955 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010956
Antoine Pitroue71d5742011-10-04 15:55:09 +020010957 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010958
Antoine Pitroue71d5742011-10-04 15:55:09 +020010959 for (; i < src_len; i++) {
10960 ch = PyUnicode_READ(kind, src_data, i);
10961 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010962 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010963 incr = tabsize - (line_pos % tabsize);
10964 line_pos += incr;
10965 while (incr--) {
10966 PyUnicode_WRITE(kind, dest_data, j, ' ');
10967 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010968 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010969 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010970 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010971 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010972 line_pos++;
10973 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010974 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010975 if (ch == '\n' || ch == '\r')
10976 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010977 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010978 }
10979 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020010980#ifndef DONT_MAKE_RESULT_READY
10981 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010982 Py_DECREF(u);
10983 return NULL;
10984 }
Victor Stinner17efeed2011-10-04 20:05:46 +020010985#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010986 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010010987 return u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010988
Antoine Pitroue71d5742011-10-04 15:55:09 +020010989 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010990 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10991 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010992}
10993
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010994PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010995 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010996\n\
10997Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010998such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010999arguments start and end are interpreted as in slice notation.\n\
11000\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011001Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002
11003static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011004unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011005{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011006 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011007 Py_ssize_t start;
11008 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011009 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011010
Jesus Ceaac451502011-04-20 17:09:23 +020011011 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11012 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011013 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011015 if (PyUnicode_READY(self) == -1)
11016 return NULL;
11017 if (PyUnicode_READY(substring) == -1)
11018 return NULL;
11019
Victor Stinner7931d9a2011-11-04 00:22:48 +010011020 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011021
11022 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011023
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011024 if (result == -2)
11025 return NULL;
11026
Christian Heimes217cfd12007-12-02 14:31:20 +000011027 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011028}
11029
11030static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011031unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011032{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011033 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11034 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011035 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011036 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011037}
11038
Guido van Rossumc2504932007-09-18 19:42:40 +000011039/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011040 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011041static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011042unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011043{
Guido van Rossumc2504932007-09-18 19:42:40 +000011044 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011045 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011046
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011047 if (_PyUnicode_HASH(self) != -1)
11048 return _PyUnicode_HASH(self);
11049 if (PyUnicode_READY(self) == -1)
11050 return -1;
11051 len = PyUnicode_GET_LENGTH(self);
11052
11053 /* The hash function as a macro, gets expanded three times below. */
11054#define HASH(P) \
11055 x = (Py_uhash_t)*P << 7; \
11056 while (--len >= 0) \
11057 x = (1000003*x) ^ (Py_uhash_t)*P++;
11058
11059 switch (PyUnicode_KIND(self)) {
11060 case PyUnicode_1BYTE_KIND: {
11061 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11062 HASH(c);
11063 break;
11064 }
11065 case PyUnicode_2BYTE_KIND: {
11066 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11067 HASH(s);
11068 break;
11069 }
11070 default: {
11071 Py_UCS4 *l;
11072 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11073 "Impossible switch case in unicode_hash");
11074 l = PyUnicode_4BYTE_DATA(self);
11075 HASH(l);
11076 break;
11077 }
11078 }
11079 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11080
Guido van Rossumc2504932007-09-18 19:42:40 +000011081 if (x == -1)
11082 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011083 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011084 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011085}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011086#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011087
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011088PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011089 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011090\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011091Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011092
11093static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011094unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011095{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011096 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011097 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011098 Py_ssize_t start;
11099 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011100
Jesus Ceaac451502011-04-20 17:09:23 +020011101 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11102 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011103 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011105 if (PyUnicode_READY(self) == -1)
11106 return NULL;
11107 if (PyUnicode_READY(substring) == -1)
11108 return NULL;
11109
Victor Stinner7931d9a2011-11-04 00:22:48 +010011110 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011111
11112 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011113
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011114 if (result == -2)
11115 return NULL;
11116
Guido van Rossumd57fd912000-03-10 22:53:23 +000011117 if (result < 0) {
11118 PyErr_SetString(PyExc_ValueError, "substring not found");
11119 return NULL;
11120 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011121
Christian Heimes217cfd12007-12-02 14:31:20 +000011122 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011123}
11124
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011125PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011126 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011127\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011128Return True if all cased characters in S are lowercase 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_islower(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_ISLOWER(PyUnicode_READ(kind, data, 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_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11159 return PyBool_FromLong(0);
11160 else if (!cased && Py_UNICODE_ISLOWER(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(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011167 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011168\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011169Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011170at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011171
11172static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011173unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011175 Py_ssize_t i, length;
11176 int kind;
11177 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011178 int cased;
11179
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011180 if (PyUnicode_READY(self) == -1)
11181 return NULL;
11182 length = PyUnicode_GET_LENGTH(self);
11183 kind = PyUnicode_KIND(self);
11184 data = PyUnicode_DATA(self);
11185
Guido van Rossumd57fd912000-03-10 22:53:23 +000011186 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011187 if (length == 1)
11188 return PyBool_FromLong(
11189 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011191 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011192 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011193 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011194
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011196 for (i = 0; i < length; i++) {
11197 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011198
Benjamin Peterson29060642009-01-31 22:14:21 +000011199 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11200 return PyBool_FromLong(0);
11201 else if (!cased && Py_UNICODE_ISUPPER(ch))
11202 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011203 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011204 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011205}
11206
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011207PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011208 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011209\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011210Return True if S is a titlecased string and there is at least one\n\
11211character in S, i.e. upper- and titlecase characters may only\n\
11212follow uncased characters and lowercase characters only cased ones.\n\
11213Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011214
11215static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011216unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011217{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011218 Py_ssize_t i, length;
11219 int kind;
11220 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221 int cased, previous_is_cased;
11222
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011223 if (PyUnicode_READY(self) == -1)
11224 return NULL;
11225 length = PyUnicode_GET_LENGTH(self);
11226 kind = PyUnicode_KIND(self);
11227 data = PyUnicode_DATA(self);
11228
Guido van Rossumd57fd912000-03-10 22:53:23 +000011229 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011230 if (length == 1) {
11231 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11232 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11233 (Py_UNICODE_ISUPPER(ch) != 0));
11234 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011235
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011236 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011237 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011238 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011239
Guido van Rossumd57fd912000-03-10 22:53:23 +000011240 cased = 0;
11241 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011242 for (i = 0; i < length; i++) {
11243 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011244
Benjamin Peterson29060642009-01-31 22:14:21 +000011245 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11246 if (previous_is_cased)
11247 return PyBool_FromLong(0);
11248 previous_is_cased = 1;
11249 cased = 1;
11250 }
11251 else if (Py_UNICODE_ISLOWER(ch)) {
11252 if (!previous_is_cased)
11253 return PyBool_FromLong(0);
11254 previous_is_cased = 1;
11255 cased = 1;
11256 }
11257 else
11258 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011259 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011260 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011261}
11262
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011263PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011264 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011265\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011266Return True if all characters in S are whitespace\n\
11267and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011268
11269static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011270unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011271{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011272 Py_ssize_t i, length;
11273 int kind;
11274 void *data;
11275
11276 if (PyUnicode_READY(self) == -1)
11277 return NULL;
11278 length = PyUnicode_GET_LENGTH(self);
11279 kind = PyUnicode_KIND(self);
11280 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011281
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011283 if (length == 1)
11284 return PyBool_FromLong(
11285 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011286
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011287 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011288 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011289 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011290
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011291 for (i = 0; i < length; i++) {
11292 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011293 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011294 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011295 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011296 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011297}
11298
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011299PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011300 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011301\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011302Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011303and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011304
11305static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011306unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011307{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011308 Py_ssize_t i, length;
11309 int kind;
11310 void *data;
11311
11312 if (PyUnicode_READY(self) == -1)
11313 return NULL;
11314 length = PyUnicode_GET_LENGTH(self);
11315 kind = PyUnicode_KIND(self);
11316 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011317
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011318 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011319 if (length == 1)
11320 return PyBool_FromLong(
11321 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011322
11323 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011324 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011325 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011326
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011327 for (i = 0; i < length; i++) {
11328 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011329 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011330 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011331 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011332}
11333
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011334PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011335 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011336\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011337Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011338and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011339
11340static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011341unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011342{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011343 int kind;
11344 void *data;
11345 Py_ssize_t len, i;
11346
11347 if (PyUnicode_READY(self) == -1)
11348 return NULL;
11349
11350 kind = PyUnicode_KIND(self);
11351 data = PyUnicode_DATA(self);
11352 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011353
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011354 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011355 if (len == 1) {
11356 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11357 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11358 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011359
11360 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011361 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011362 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011363
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011364 for (i = 0; i < len; i++) {
11365 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011366 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011367 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011368 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011369 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011370}
11371
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011372PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011373 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011374\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011375Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011376False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011377
11378static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011379unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011380{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011381 Py_ssize_t i, length;
11382 int kind;
11383 void *data;
11384
11385 if (PyUnicode_READY(self) == -1)
11386 return NULL;
11387 length = PyUnicode_GET_LENGTH(self);
11388 kind = PyUnicode_KIND(self);
11389 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011390
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011392 if (length == 1)
11393 return PyBool_FromLong(
11394 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011395
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011396 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011397 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011398 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011399
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011400 for (i = 0; i < length; i++) {
11401 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011402 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011403 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011404 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011405}
11406
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011407PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011408 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011410Return True if all characters in S are digits\n\
11411and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011412
11413static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011414unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011416 Py_ssize_t i, length;
11417 int kind;
11418 void *data;
11419
11420 if (PyUnicode_READY(self) == -1)
11421 return NULL;
11422 length = PyUnicode_GET_LENGTH(self);
11423 kind = PyUnicode_KIND(self);
11424 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011425
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011427 if (length == 1) {
11428 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11429 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11430 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011432 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011433 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011434 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011435
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011436 for (i = 0; i < length; i++) {
11437 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011438 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011440 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011441}
11442
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011443PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011444 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011445\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011446Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011447False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011448
11449static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011450unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011451{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011452 Py_ssize_t i, length;
11453 int kind;
11454 void *data;
11455
11456 if (PyUnicode_READY(self) == -1)
11457 return NULL;
11458 length = PyUnicode_GET_LENGTH(self);
11459 kind = PyUnicode_KIND(self);
11460 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011461
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011463 if (length == 1)
11464 return PyBool_FromLong(
11465 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011467 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011468 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011469 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011470
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011471 for (i = 0; i < length; i++) {
11472 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011473 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011475 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011476}
11477
Martin v. Löwis47383402007-08-15 07:32:56 +000011478int
11479PyUnicode_IsIdentifier(PyObject *self)
11480{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011481 int kind;
11482 void *data;
11483 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011484 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011485
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011486 if (PyUnicode_READY(self) == -1) {
11487 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011488 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011489 }
11490
11491 /* Special case for empty strings */
11492 if (PyUnicode_GET_LENGTH(self) == 0)
11493 return 0;
11494 kind = PyUnicode_KIND(self);
11495 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011496
11497 /* PEP 3131 says that the first character must be in
11498 XID_Start and subsequent characters in XID_Continue,
11499 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011500 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011501 letters, digits, underscore). However, given the current
11502 definition of XID_Start and XID_Continue, it is sufficient
11503 to check just for these, except that _ must be allowed
11504 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011505 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011506 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011507 return 0;
11508
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011509 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011510 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011511 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011512 return 1;
11513}
11514
11515PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011516 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011517\n\
11518Return True if S is a valid identifier according\n\
11519to the language definition.");
11520
11521static PyObject*
11522unicode_isidentifier(PyObject *self)
11523{
11524 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11525}
11526
Georg Brandl559e5d72008-06-11 18:37:52 +000011527PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011528 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011529\n\
11530Return True if all characters in S are considered\n\
11531printable in repr() or S is empty, False otherwise.");
11532
11533static PyObject*
11534unicode_isprintable(PyObject *self)
11535{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011536 Py_ssize_t i, length;
11537 int kind;
11538 void *data;
11539
11540 if (PyUnicode_READY(self) == -1)
11541 return NULL;
11542 length = PyUnicode_GET_LENGTH(self);
11543 kind = PyUnicode_KIND(self);
11544 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011545
11546 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011547 if (length == 1)
11548 return PyBool_FromLong(
11549 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011550
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011551 for (i = 0; i < length; i++) {
11552 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011553 Py_RETURN_FALSE;
11554 }
11555 }
11556 Py_RETURN_TRUE;
11557}
11558
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011559PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011560 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011561\n\
11562Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011563iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564
11565static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011566unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011568 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569}
11570
Martin v. Löwis18e16552006-02-15 17:27:45 +000011571static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011572unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011573{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011574 if (PyUnicode_READY(self) == -1)
11575 return -1;
11576 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011577}
11578
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011579PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011580 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011582Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011583done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584
11585static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011586unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011587{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011588 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011589 Py_UCS4 fillchar = ' ';
11590
11591 if (PyUnicode_READY(self) == -1)
11592 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011593
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011594 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595 return NULL;
11596
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011597 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011598 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011599 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011600 }
11601
Victor Stinner7931d9a2011-11-04 00:22:48 +010011602 return pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011603}
11604
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011605PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011606 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011607\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011608Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011609
11610static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011611unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011612{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613 return fixup(self, fixlower);
11614}
11615
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011616#define LEFTSTRIP 0
11617#define RIGHTSTRIP 1
11618#define BOTHSTRIP 2
11619
11620/* Arrays indexed by above */
11621static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11622
11623#define STRIPNAME(i) (stripformat[i]+3)
11624
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011625/* externally visible for str.strip(unicode) */
11626PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011627_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011628{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011629 void *data;
11630 int kind;
11631 Py_ssize_t i, j, len;
11632 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011634 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11635 return NULL;
11636
11637 kind = PyUnicode_KIND(self);
11638 data = PyUnicode_DATA(self);
11639 len = PyUnicode_GET_LENGTH(self);
11640 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11641 PyUnicode_DATA(sepobj),
11642 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011643
Benjamin Peterson14339b62009-01-31 16:36:08 +000011644 i = 0;
11645 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011646 while (i < len &&
11647 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011648 i++;
11649 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011650 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011651
Benjamin Peterson14339b62009-01-31 16:36:08 +000011652 j = len;
11653 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011654 do {
11655 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011656 } while (j >= i &&
11657 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011658 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011659 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011660
Victor Stinner7931d9a2011-11-04 00:22:48 +010011661 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011662}
11663
11664PyObject*
11665PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11666{
11667 unsigned char *data;
11668 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011669 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011670
Victor Stinnerde636f32011-10-01 03:55:54 +020011671 if (PyUnicode_READY(self) == -1)
11672 return NULL;
11673
11674 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11675
Victor Stinner12bab6d2011-10-01 01:53:49 +020011676 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011677 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011678 if (PyUnicode_CheckExact(self)) {
11679 Py_INCREF(self);
11680 return self;
11681 }
11682 else
11683 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011684 }
11685
Victor Stinner12bab6d2011-10-01 01:53:49 +020011686 length = end - start;
11687 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011688 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011689
Victor Stinnerde636f32011-10-01 03:55:54 +020011690 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011691 PyErr_SetString(PyExc_IndexError, "string index out of range");
11692 return NULL;
11693 }
11694
Victor Stinnerb9275c12011-10-05 14:01:42 +020011695 if (PyUnicode_IS_ASCII(self)) {
11696 kind = PyUnicode_KIND(self);
11697 data = PyUnicode_1BYTE_DATA(self);
11698 return unicode_fromascii(data + start, length);
11699 }
11700 else {
11701 kind = PyUnicode_KIND(self);
11702 data = PyUnicode_1BYTE_DATA(self);
11703 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011704 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011705 length);
11706 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011707}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011708
11709static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011710do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011711{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011712 int kind;
11713 void *data;
11714 Py_ssize_t len, i, j;
11715
11716 if (PyUnicode_READY(self) == -1)
11717 return NULL;
11718
11719 kind = PyUnicode_KIND(self);
11720 data = PyUnicode_DATA(self);
11721 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011722
Benjamin Peterson14339b62009-01-31 16:36:08 +000011723 i = 0;
11724 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011725 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011726 i++;
11727 }
11728 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011729
Benjamin Peterson14339b62009-01-31 16:36:08 +000011730 j = len;
11731 if (striptype != LEFTSTRIP) {
11732 do {
11733 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011734 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011735 j++;
11736 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011737
Victor Stinner7931d9a2011-11-04 00:22:48 +010011738 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011739}
11740
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011741
11742static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011743do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011744{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011745 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011746
Benjamin Peterson14339b62009-01-31 16:36:08 +000011747 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11748 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011749
Benjamin Peterson14339b62009-01-31 16:36:08 +000011750 if (sep != NULL && sep != Py_None) {
11751 if (PyUnicode_Check(sep))
11752 return _PyUnicode_XStrip(self, striptype, sep);
11753 else {
11754 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011755 "%s arg must be None or str",
11756 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011757 return NULL;
11758 }
11759 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011760
Benjamin Peterson14339b62009-01-31 16:36:08 +000011761 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011762}
11763
11764
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011765PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011766 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011767\n\
11768Return a copy of the string S with leading and trailing\n\
11769whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011770If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011771
11772static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011773unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011774{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011775 if (PyTuple_GET_SIZE(args) == 0)
11776 return do_strip(self, BOTHSTRIP); /* Common case */
11777 else
11778 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011779}
11780
11781
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011782PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011783 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011784\n\
11785Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011786If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011787
11788static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011789unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011790{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011791 if (PyTuple_GET_SIZE(args) == 0)
11792 return do_strip(self, LEFTSTRIP); /* Common case */
11793 else
11794 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011795}
11796
11797
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011798PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011799 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011800\n\
11801Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011802If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011803
11804static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011805unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011806{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011807 if (PyTuple_GET_SIZE(args) == 0)
11808 return do_strip(self, RIGHTSTRIP); /* Common case */
11809 else
11810 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011811}
11812
11813
Guido van Rossumd57fd912000-03-10 22:53:23 +000011814static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011815unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011816{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011817 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011818 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011819
Georg Brandl222de0f2009-04-12 12:01:50 +000011820 if (len < 1) {
11821 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011822 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011823 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011824
Tim Peters7a29bd52001-09-12 03:03:31 +000011825 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011826 /* no repeat, return original string */
11827 Py_INCREF(str);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011828 return str;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011829 }
Tim Peters8f422462000-09-09 06:13:41 +000011830
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011831 if (PyUnicode_READY(str) == -1)
11832 return NULL;
11833
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011834 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011835 PyErr_SetString(PyExc_OverflowError,
11836 "repeated string is too long");
11837 return NULL;
11838 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011839 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011840
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011841 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011842 if (!u)
11843 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011844 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011845
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011846 if (PyUnicode_GET_LENGTH(str) == 1) {
11847 const int kind = PyUnicode_KIND(str);
11848 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11849 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011850 if (kind == PyUnicode_1BYTE_KIND)
11851 memset(to, (unsigned char)fill_char, len);
11852 else {
11853 for (n = 0; n < len; ++n)
11854 PyUnicode_WRITE(kind, to, n, fill_char);
11855 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011856 }
11857 else {
11858 /* number of characters copied this far */
11859 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011860 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011861 char *to = (char *) PyUnicode_DATA(u);
11862 Py_MEMCPY(to, PyUnicode_DATA(str),
11863 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011864 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011865 n = (done <= nchars-done) ? done : nchars-done;
11866 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011867 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011868 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011869 }
11870
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011871 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011872 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011873}
11874
Alexander Belopolsky40018472011-02-26 01:02:56 +000011875PyObject *
11876PyUnicode_Replace(PyObject *obj,
11877 PyObject *subobj,
11878 PyObject *replobj,
11879 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011880{
11881 PyObject *self;
11882 PyObject *str1;
11883 PyObject *str2;
11884 PyObject *result;
11885
11886 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011887 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011888 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011889 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011890 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011891 Py_DECREF(self);
11892 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011893 }
11894 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011895 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011896 Py_DECREF(self);
11897 Py_DECREF(str1);
11898 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011899 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011900 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011901 Py_DECREF(self);
11902 Py_DECREF(str1);
11903 Py_DECREF(str2);
11904 return result;
11905}
11906
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011907PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011908 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011909\n\
11910Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011911old replaced by new. If the optional argument count is\n\
11912given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011913
11914static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011915unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011916{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011917 PyObject *str1;
11918 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011919 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011920 PyObject *result;
11921
Martin v. Löwis18e16552006-02-15 17:27:45 +000011922 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011924 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011925 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011926 str1 = PyUnicode_FromObject(str1);
11927 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11928 return NULL;
11929 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011930 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011931 Py_DECREF(str1);
11932 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011933 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011934
11935 result = replace(self, str1, str2, maxcount);
11936
11937 Py_DECREF(str1);
11938 Py_DECREF(str2);
11939 return result;
11940}
11941
Alexander Belopolsky40018472011-02-26 01:02:56 +000011942static PyObject *
11943unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011944{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011945 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011946 Py_ssize_t isize;
11947 Py_ssize_t osize, squote, dquote, i, o;
11948 Py_UCS4 max, quote;
11949 int ikind, okind;
11950 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011951
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011952 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011953 return NULL;
11954
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011955 isize = PyUnicode_GET_LENGTH(unicode);
11956 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011957
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011958 /* Compute length of output, quote characters, and
11959 maximum character */
11960 osize = 2; /* quotes */
11961 max = 127;
11962 squote = dquote = 0;
11963 ikind = PyUnicode_KIND(unicode);
11964 for (i = 0; i < isize; i++) {
11965 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11966 switch (ch) {
11967 case '\'': squote++; osize++; break;
11968 case '"': dquote++; osize++; break;
11969 case '\\': case '\t': case '\r': case '\n':
11970 osize += 2; break;
11971 default:
11972 /* Fast-path ASCII */
11973 if (ch < ' ' || ch == 0x7f)
11974 osize += 4; /* \xHH */
11975 else if (ch < 0x7f)
11976 osize++;
11977 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11978 osize++;
11979 max = ch > max ? ch : max;
11980 }
11981 else if (ch < 0x100)
11982 osize += 4; /* \xHH */
11983 else if (ch < 0x10000)
11984 osize += 6; /* \uHHHH */
11985 else
11986 osize += 10; /* \uHHHHHHHH */
11987 }
11988 }
11989
11990 quote = '\'';
11991 if (squote) {
11992 if (dquote)
11993 /* Both squote and dquote present. Use squote,
11994 and escape them */
11995 osize += squote;
11996 else
11997 quote = '"';
11998 }
11999
12000 repr = PyUnicode_New(osize, max);
12001 if (repr == NULL)
12002 return NULL;
12003 okind = PyUnicode_KIND(repr);
12004 odata = PyUnicode_DATA(repr);
12005
12006 PyUnicode_WRITE(okind, odata, 0, quote);
12007 PyUnicode_WRITE(okind, odata, osize-1, quote);
12008
12009 for (i = 0, o = 1; i < isize; i++) {
12010 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012011
12012 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012013 if ((ch == quote) || (ch == '\\')) {
12014 PyUnicode_WRITE(okind, odata, o++, '\\');
12015 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012016 continue;
12017 }
12018
Benjamin Peterson29060642009-01-31 22:14:21 +000012019 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012020 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012021 PyUnicode_WRITE(okind, odata, o++, '\\');
12022 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012023 }
12024 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012025 PyUnicode_WRITE(okind, odata, o++, '\\');
12026 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012027 }
12028 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012029 PyUnicode_WRITE(okind, odata, o++, '\\');
12030 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012031 }
12032
12033 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012034 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012035 PyUnicode_WRITE(okind, odata, o++, '\\');
12036 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012037 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12038 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012039 }
12040
Georg Brandl559e5d72008-06-11 18:37:52 +000012041 /* Copy ASCII characters as-is */
12042 else if (ch < 0x7F) {
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
Benjamin Peterson29060642009-01-31 22:14:21 +000012046 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012047 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012048 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012049 (categories Z* and C* except ASCII space)
12050 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012051 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012052 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012053 if (ch <= 0xff) {
12054 PyUnicode_WRITE(okind, odata, o++, '\\');
12055 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012056 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12057 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012058 }
12059 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012060 else if (ch >= 0x10000) {
12061 PyUnicode_WRITE(okind, odata, o++, '\\');
12062 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012063 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12064 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12065 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12066 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12067 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12068 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12069 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12070 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012071 }
12072 /* Map 16-bit characters to '\uxxxx' */
12073 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012074 PyUnicode_WRITE(okind, odata, o++, '\\');
12075 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012076 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12077 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12078 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12079 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012080 }
12081 }
12082 /* Copy characters as-is */
12083 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012084 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012085 }
12086 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012087 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012088 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012089 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012090 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012091}
12092
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012093PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012094 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012095\n\
12096Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012097such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012098arguments start and end are interpreted as in slice notation.\n\
12099\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012100Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012101
12102static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012103unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012104{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012105 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012106 Py_ssize_t start;
12107 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012108 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012109
Jesus Ceaac451502011-04-20 17:09:23 +020012110 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12111 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012112 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012113
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012114 if (PyUnicode_READY(self) == -1)
12115 return NULL;
12116 if (PyUnicode_READY(substring) == -1)
12117 return NULL;
12118
Victor Stinner7931d9a2011-11-04 00:22:48 +010012119 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012120
12121 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012122
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012123 if (result == -2)
12124 return NULL;
12125
Christian Heimes217cfd12007-12-02 14:31:20 +000012126 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012127}
12128
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012129PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012130 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012131\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012132Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012133
12134static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012135unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012136{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012137 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012138 Py_ssize_t start;
12139 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012140 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012141
Jesus Ceaac451502011-04-20 17:09:23 +020012142 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12143 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012144 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012145
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012146 if (PyUnicode_READY(self) == -1)
12147 return NULL;
12148 if (PyUnicode_READY(substring) == -1)
12149 return NULL;
12150
Victor Stinner7931d9a2011-11-04 00:22:48 +010012151 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012152
12153 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012154
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012155 if (result == -2)
12156 return NULL;
12157
Guido van Rossumd57fd912000-03-10 22:53:23 +000012158 if (result < 0) {
12159 PyErr_SetString(PyExc_ValueError, "substring not found");
12160 return NULL;
12161 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012162
Christian Heimes217cfd12007-12-02 14:31:20 +000012163 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012164}
12165
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012166PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012167 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012168\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012169Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012170done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012171
12172static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012173unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012174{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012175 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012176 Py_UCS4 fillchar = ' ';
12177
Victor Stinnere9a29352011-10-01 02:14:59 +020012178 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012179 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012180
Victor Stinnere9a29352011-10-01 02:14:59 +020012181 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012182 return NULL;
12183
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012184 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012185 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012186 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012187 }
12188
Victor Stinner7931d9a2011-11-04 00:22:48 +010012189 return pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012190}
12191
Alexander Belopolsky40018472011-02-26 01:02:56 +000012192PyObject *
12193PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012194{
12195 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012196
Guido van Rossumd57fd912000-03-10 22:53:23 +000012197 s = PyUnicode_FromObject(s);
12198 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012199 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012200 if (sep != NULL) {
12201 sep = PyUnicode_FromObject(sep);
12202 if (sep == NULL) {
12203 Py_DECREF(s);
12204 return NULL;
12205 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012206 }
12207
Victor Stinner9310abb2011-10-05 00:59:23 +020012208 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012209
12210 Py_DECREF(s);
12211 Py_XDECREF(sep);
12212 return result;
12213}
12214
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012215PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012216 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012217\n\
12218Return a list of the words in S, using sep as the\n\
12219delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012220splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012221whitespace string is a separator and empty strings are\n\
12222removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012223
12224static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012225unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012226{
12227 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012228 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012229
Martin v. Löwis18e16552006-02-15 17:27:45 +000012230 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012231 return NULL;
12232
12233 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012234 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012235 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012236 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012237 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012238 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012239}
12240
Thomas Wouters477c8d52006-05-27 19:21:47 +000012241PyObject *
12242PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12243{
12244 PyObject* str_obj;
12245 PyObject* sep_obj;
12246 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012247 int kind1, kind2, kind;
12248 void *buf1 = NULL, *buf2 = NULL;
12249 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012250
12251 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012252 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012253 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012254 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012255 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012256 Py_DECREF(str_obj);
12257 return NULL;
12258 }
12259
Victor Stinner14f8f022011-10-05 20:58:25 +020012260 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012261 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012262 kind = Py_MAX(kind1, kind2);
12263 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012264 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012265 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012266 if (!buf1)
12267 goto onError;
12268 buf2 = PyUnicode_DATA(sep_obj);
12269 if (kind2 != kind)
12270 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12271 if (!buf2)
12272 goto onError;
12273 len1 = PyUnicode_GET_LENGTH(str_obj);
12274 len2 = PyUnicode_GET_LENGTH(sep_obj);
12275
Victor Stinner14f8f022011-10-05 20:58:25 +020012276 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012277 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012278 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12279 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12280 else
12281 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012282 break;
12283 case PyUnicode_2BYTE_KIND:
12284 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12285 break;
12286 case PyUnicode_4BYTE_KIND:
12287 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12288 break;
12289 default:
12290 assert(0);
12291 out = 0;
12292 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012293
12294 Py_DECREF(sep_obj);
12295 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012296 if (kind1 != kind)
12297 PyMem_Free(buf1);
12298 if (kind2 != kind)
12299 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012300
12301 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012302 onError:
12303 Py_DECREF(sep_obj);
12304 Py_DECREF(str_obj);
12305 if (kind1 != kind && buf1)
12306 PyMem_Free(buf1);
12307 if (kind2 != kind && buf2)
12308 PyMem_Free(buf2);
12309 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012310}
12311
12312
12313PyObject *
12314PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12315{
12316 PyObject* str_obj;
12317 PyObject* sep_obj;
12318 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012319 int kind1, kind2, kind;
12320 void *buf1 = NULL, *buf2 = NULL;
12321 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012322
12323 str_obj = PyUnicode_FromObject(str_in);
12324 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012325 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012326 sep_obj = PyUnicode_FromObject(sep_in);
12327 if (!sep_obj) {
12328 Py_DECREF(str_obj);
12329 return NULL;
12330 }
12331
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012332 kind1 = PyUnicode_KIND(str_in);
12333 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012334 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012335 buf1 = PyUnicode_DATA(str_in);
12336 if (kind1 != kind)
12337 buf1 = _PyUnicode_AsKind(str_in, kind);
12338 if (!buf1)
12339 goto onError;
12340 buf2 = PyUnicode_DATA(sep_obj);
12341 if (kind2 != kind)
12342 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12343 if (!buf2)
12344 goto onError;
12345 len1 = PyUnicode_GET_LENGTH(str_obj);
12346 len2 = PyUnicode_GET_LENGTH(sep_obj);
12347
12348 switch(PyUnicode_KIND(str_in)) {
12349 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012350 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12351 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12352 else
12353 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012354 break;
12355 case PyUnicode_2BYTE_KIND:
12356 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12357 break;
12358 case PyUnicode_4BYTE_KIND:
12359 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12360 break;
12361 default:
12362 assert(0);
12363 out = 0;
12364 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012365
12366 Py_DECREF(sep_obj);
12367 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012368 if (kind1 != kind)
12369 PyMem_Free(buf1);
12370 if (kind2 != kind)
12371 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012372
12373 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012374 onError:
12375 Py_DECREF(sep_obj);
12376 Py_DECREF(str_obj);
12377 if (kind1 != kind && buf1)
12378 PyMem_Free(buf1);
12379 if (kind2 != kind && buf2)
12380 PyMem_Free(buf2);
12381 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012382}
12383
12384PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012385 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012386\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012387Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012388the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012389found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012390
12391static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012392unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012393{
Victor Stinner9310abb2011-10-05 00:59:23 +020012394 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012395}
12396
12397PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012398 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012399\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012400Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012401the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012402separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012403
12404static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012405unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012406{
Victor Stinner9310abb2011-10-05 00:59:23 +020012407 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012408}
12409
Alexander Belopolsky40018472011-02-26 01:02:56 +000012410PyObject *
12411PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012412{
12413 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012414
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012415 s = PyUnicode_FromObject(s);
12416 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012417 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012418 if (sep != NULL) {
12419 sep = PyUnicode_FromObject(sep);
12420 if (sep == NULL) {
12421 Py_DECREF(s);
12422 return NULL;
12423 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012424 }
12425
Victor Stinner9310abb2011-10-05 00:59:23 +020012426 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012427
12428 Py_DECREF(s);
12429 Py_XDECREF(sep);
12430 return result;
12431}
12432
12433PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012434 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012435\n\
12436Return a list of the words in S, using sep as the\n\
12437delimiter string, starting at the end of the string and\n\
12438working to the front. If maxsplit is given, at most maxsplit\n\
12439splits are done. If sep is not specified, any whitespace string\n\
12440is a separator.");
12441
12442static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012443unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012444{
12445 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012446 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012447
Martin v. Löwis18e16552006-02-15 17:27:45 +000012448 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012449 return NULL;
12450
12451 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012452 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012453 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012454 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012455 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012456 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012457}
12458
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012459PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012460 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012461\n\
12462Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012463Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012464is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012465
12466static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012467unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012468{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012469 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012470 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012471
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012472 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12473 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012474 return NULL;
12475
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012476 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012477}
12478
12479static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012480PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012481{
Walter Dörwald346737f2007-05-31 10:44:43 +000012482 if (PyUnicode_CheckExact(self)) {
12483 Py_INCREF(self);
12484 return self;
12485 } else
12486 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012487 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012488}
12489
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012490PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012491 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012492\n\
12493Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012494and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012495
12496static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012497unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012498{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012499 return fixup(self, fixswapcase);
12500}
12501
Georg Brandlceee0772007-11-27 23:48:05 +000012502PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012503 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012504\n\
12505Return a translation table usable for str.translate().\n\
12506If there is only one argument, it must be a dictionary mapping Unicode\n\
12507ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012508Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012509If there are two arguments, they must be strings of equal length, and\n\
12510in the resulting dictionary, each character in x will be mapped to the\n\
12511character at the same position in y. If there is a third argument, it\n\
12512must be a string, whose characters will be mapped to None in the result.");
12513
12514static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012515unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012516{
12517 PyObject *x, *y = NULL, *z = NULL;
12518 PyObject *new = NULL, *key, *value;
12519 Py_ssize_t i = 0;
12520 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012521
Georg Brandlceee0772007-11-27 23:48:05 +000012522 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12523 return NULL;
12524 new = PyDict_New();
12525 if (!new)
12526 return NULL;
12527 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012528 int x_kind, y_kind, z_kind;
12529 void *x_data, *y_data, *z_data;
12530
Georg Brandlceee0772007-11-27 23:48:05 +000012531 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012532 if (!PyUnicode_Check(x)) {
12533 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12534 "be a string if there is a second argument");
12535 goto err;
12536 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012537 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012538 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12539 "arguments must have equal length");
12540 goto err;
12541 }
12542 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012543 x_kind = PyUnicode_KIND(x);
12544 y_kind = PyUnicode_KIND(y);
12545 x_data = PyUnicode_DATA(x);
12546 y_data = PyUnicode_DATA(y);
12547 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12548 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12549 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012550 if (!key || !value)
12551 goto err;
12552 res = PyDict_SetItem(new, key, value);
12553 Py_DECREF(key);
12554 Py_DECREF(value);
12555 if (res < 0)
12556 goto err;
12557 }
12558 /* create entries for deleting chars in z */
12559 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012560 z_kind = PyUnicode_KIND(z);
12561 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012562 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012563 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012564 if (!key)
12565 goto err;
12566 res = PyDict_SetItem(new, key, Py_None);
12567 Py_DECREF(key);
12568 if (res < 0)
12569 goto err;
12570 }
12571 }
12572 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012573 int kind;
12574 void *data;
12575
Georg Brandlceee0772007-11-27 23:48:05 +000012576 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012577 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012578 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12579 "to maketrans it must be a dict");
12580 goto err;
12581 }
12582 /* copy entries into the new dict, converting string keys to int keys */
12583 while (PyDict_Next(x, &i, &key, &value)) {
12584 if (PyUnicode_Check(key)) {
12585 /* convert string keys to integer keys */
12586 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012587 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012588 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12589 "table must be of length 1");
12590 goto err;
12591 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012592 kind = PyUnicode_KIND(key);
12593 data = PyUnicode_DATA(key);
12594 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012595 if (!newkey)
12596 goto err;
12597 res = PyDict_SetItem(new, newkey, value);
12598 Py_DECREF(newkey);
12599 if (res < 0)
12600 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012601 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012602 /* just keep integer keys */
12603 if (PyDict_SetItem(new, key, value) < 0)
12604 goto err;
12605 } else {
12606 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12607 "be strings or integers");
12608 goto err;
12609 }
12610 }
12611 }
12612 return new;
12613 err:
12614 Py_DECREF(new);
12615 return NULL;
12616}
12617
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012618PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012619 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012620\n\
12621Return a copy of the string S, where all characters have been mapped\n\
12622through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012623Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012624Unmapped characters are left untouched. Characters mapped to None\n\
12625are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626
12627static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012628unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012629{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012630 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012631}
12632
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012633PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012634 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012635\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012636Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012637
12638static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012639unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012640{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012641 return fixup(self, fixupper);
12642}
12643
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012644PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012645 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012646\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012647Pad a numeric string S with zeros on the left, to fill a field\n\
12648of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012649
12650static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012651unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012652{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012653 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012654 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012655 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012656 int kind;
12657 void *data;
12658 Py_UCS4 chr;
12659
12660 if (PyUnicode_READY(self) == -1)
12661 return NULL;
12662
Martin v. Löwis18e16552006-02-15 17:27:45 +000012663 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012664 return NULL;
12665
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012666 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012667 if (PyUnicode_CheckExact(self)) {
12668 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012669 return self;
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012670 }
12671 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012672 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012673 }
12674
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012675 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012676
12677 u = pad(self, fill, 0, '0');
12678
Walter Dörwald068325e2002-04-15 13:36:47 +000012679 if (u == NULL)
12680 return NULL;
12681
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012682 kind = PyUnicode_KIND(u);
12683 data = PyUnicode_DATA(u);
12684 chr = PyUnicode_READ(kind, data, fill);
12685
12686 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012687 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012688 PyUnicode_WRITE(kind, data, 0, chr);
12689 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012690 }
12691
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012692 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012693 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012694}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012695
12696#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012697static PyObject *
12698unicode__decimal2ascii(PyObject *self)
12699{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012700 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012701}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012702#endif
12703
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012704PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012705 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012706\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012707Return True if S starts with the specified prefix, False otherwise.\n\
12708With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012709With optional end, stop comparing S at that position.\n\
12710prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012711
12712static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012713unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012714 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012715{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012716 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012717 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012718 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012719 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012720 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012721
Jesus Ceaac451502011-04-20 17:09:23 +020012722 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012723 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012724 if (PyTuple_Check(subobj)) {
12725 Py_ssize_t i;
12726 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012727 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012728 if (substring == NULL)
12729 return NULL;
12730 result = tailmatch(self, substring, start, end, -1);
12731 Py_DECREF(substring);
12732 if (result) {
12733 Py_RETURN_TRUE;
12734 }
12735 }
12736 /* nothing matched */
12737 Py_RETURN_FALSE;
12738 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012739 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012740 if (substring == NULL) {
12741 if (PyErr_ExceptionMatches(PyExc_TypeError))
12742 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12743 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012744 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012745 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012746 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012747 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012748 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749}
12750
12751
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012752PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012753 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012754\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012755Return True if S ends with the specified suffix, False otherwise.\n\
12756With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012757With optional end, stop comparing S at that position.\n\
12758suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012759
12760static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012761unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012762 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012763{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012764 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012765 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012766 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012767 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012768 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012769
Jesus Ceaac451502011-04-20 17:09:23 +020012770 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012771 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012772 if (PyTuple_Check(subobj)) {
12773 Py_ssize_t i;
12774 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012775 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012776 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012777 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012778 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012779 result = tailmatch(self, substring, start, end, +1);
12780 Py_DECREF(substring);
12781 if (result) {
12782 Py_RETURN_TRUE;
12783 }
12784 }
12785 Py_RETURN_FALSE;
12786 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012787 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012788 if (substring == NULL) {
12789 if (PyErr_ExceptionMatches(PyExc_TypeError))
12790 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12791 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012792 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012793 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012794 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012795 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012796 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012797}
12798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012799#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012800
12801PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012802 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012803\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012804Return a formatted version of S, using substitutions from args and kwargs.\n\
12805The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012806
Eric Smith27bbca62010-11-04 17:06:58 +000012807PyDoc_STRVAR(format_map__doc__,
12808 "S.format_map(mapping) -> str\n\
12809\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012810Return a formatted version of S, using substitutions from mapping.\n\
12811The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012812
Eric Smith4a7d76d2008-05-30 18:10:19 +000012813static PyObject *
12814unicode__format__(PyObject* self, PyObject* args)
12815{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012816 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012817
12818 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12819 return NULL;
12820
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012821 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012822 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012823 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012824}
12825
Eric Smith8c663262007-08-25 02:26:07 +000012826PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012827 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012828\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012829Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012830
12831static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012832unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012833{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012834 Py_ssize_t size;
12835
12836 /* If it's a compact object, account for base structure +
12837 character data. */
12838 if (PyUnicode_IS_COMPACT_ASCII(v))
12839 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12840 else if (PyUnicode_IS_COMPACT(v))
12841 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012842 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012843 else {
12844 /* If it is a two-block object, account for base object, and
12845 for character block if present. */
12846 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012847 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012848 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012849 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012850 }
12851 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012852 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012853 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012854 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012855 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012856 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012857
12858 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012859}
12860
12861PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012862 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012863
12864static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012865unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012866{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012867 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012868 if (!copy)
12869 return NULL;
12870 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012871}
12872
Guido van Rossumd57fd912000-03-10 22:53:23 +000012873static PyMethodDef unicode_methods[] = {
12874
12875 /* Order is according to common usage: often used methods should
12876 appear first, since lookup is done sequentially. */
12877
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012878 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012879 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12880 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012881 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012882 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12883 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12884 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12885 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12886 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12887 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12888 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012889 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012890 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12891 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12892 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012893 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012894 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12895 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12896 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012897 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012898 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012899 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012900 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012901 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12902 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12903 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12904 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12905 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12906 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12907 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12908 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12909 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12910 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12911 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12912 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12913 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12914 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012915 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012916 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012917 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012918 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012919 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012920 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012921 {"maketrans", (PyCFunction) unicode_maketrans,
12922 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012923 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012924#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012925 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012926#endif
12927
12928#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012929 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012930 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012931#endif
12932
Benjamin Peterson14339b62009-01-31 16:36:08 +000012933 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012934 {NULL, NULL}
12935};
12936
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012937static PyObject *
12938unicode_mod(PyObject *v, PyObject *w)
12939{
Brian Curtindfc80e32011-08-10 20:28:54 -050012940 if (!PyUnicode_Check(v))
12941 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012942 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012943}
12944
12945static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012946 0, /*nb_add*/
12947 0, /*nb_subtract*/
12948 0, /*nb_multiply*/
12949 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012950};
12951
Guido van Rossumd57fd912000-03-10 22:53:23 +000012952static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012953 (lenfunc) unicode_length, /* sq_length */
12954 PyUnicode_Concat, /* sq_concat */
12955 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12956 (ssizeargfunc) unicode_getitem, /* sq_item */
12957 0, /* sq_slice */
12958 0, /* sq_ass_item */
12959 0, /* sq_ass_slice */
12960 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012961};
12962
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012963static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012964unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012965{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012966 if (PyUnicode_READY(self) == -1)
12967 return NULL;
12968
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012969 if (PyIndex_Check(item)) {
12970 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012971 if (i == -1 && PyErr_Occurred())
12972 return NULL;
12973 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012974 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012975 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012976 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000012977 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012978 PyObject *result;
12979 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012980 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012981 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012983 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000012984 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012985 return NULL;
12986 }
12987
12988 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012989 return PyUnicode_New(0, 0);
12990 } else if (start == 0 && step == 1 &&
12991 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000012992 PyUnicode_CheckExact(self)) {
12993 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012994 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000012995 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012996 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020012997 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012998 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012999 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013000 src_kind = PyUnicode_KIND(self);
13001 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013002 if (!PyUnicode_IS_ASCII(self)) {
13003 kind_limit = kind_maxchar_limit(src_kind);
13004 max_char = 0;
13005 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13006 ch = PyUnicode_READ(src_kind, src_data, cur);
13007 if (ch > max_char) {
13008 max_char = ch;
13009 if (max_char >= kind_limit)
13010 break;
13011 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013012 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013013 }
Victor Stinner55c99112011-10-13 01:17:06 +020013014 else
13015 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013016 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013017 if (result == NULL)
13018 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013019 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013020 dest_data = PyUnicode_DATA(result);
13021
13022 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013023 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13024 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013025 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013026 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013027 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013028 } else {
13029 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13030 return NULL;
13031 }
13032}
13033
13034static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013035 (lenfunc)unicode_length, /* mp_length */
13036 (binaryfunc)unicode_subscript, /* mp_subscript */
13037 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013038};
13039
Guido van Rossumd57fd912000-03-10 22:53:23 +000013040
Guido van Rossumd57fd912000-03-10 22:53:23 +000013041/* Helpers for PyUnicode_Format() */
13042
13043static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013044getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013045{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013046 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013047 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013048 (*p_argidx)++;
13049 if (arglen < 0)
13050 return args;
13051 else
13052 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013053 }
13054 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013055 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013056 return NULL;
13057}
13058
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013059/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013060
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013061static PyObject *
13062formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013063{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013064 char *p;
13065 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013066 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013067
Guido van Rossumd57fd912000-03-10 22:53:23 +000013068 x = PyFloat_AsDouble(v);
13069 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013070 return NULL;
13071
Guido van Rossumd57fd912000-03-10 22:53:23 +000013072 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013073 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013074
Eric Smith0923d1d2009-04-16 20:16:10 +000013075 p = PyOS_double_to_string(x, type, prec,
13076 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013077 if (p == NULL)
13078 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013079 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013080 PyMem_Free(p);
13081 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013082}
13083
Tim Peters38fd5b62000-09-21 05:43:11 +000013084static PyObject*
13085formatlong(PyObject *val, int flags, int prec, int type)
13086{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013087 char *buf;
13088 int len;
13089 PyObject *str; /* temporary string object. */
13090 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013091
Benjamin Peterson14339b62009-01-31 16:36:08 +000013092 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13093 if (!str)
13094 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013095 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013096 Py_DECREF(str);
13097 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013098}
13099
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013100static Py_UCS4
13101formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013102{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013103 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013104 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013105 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013106 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013107 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013108 goto onError;
13109 }
13110 else {
13111 /* Integer input truncated to a character */
13112 long x;
13113 x = PyLong_AsLong(v);
13114 if (x == -1 && PyErr_Occurred())
13115 goto onError;
13116
13117 if (x < 0 || x > 0x10ffff) {
13118 PyErr_SetString(PyExc_OverflowError,
13119 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013120 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013121 }
13122
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013123 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013124 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013125
Benjamin Peterson29060642009-01-31 22:14:21 +000013126 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013127 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013128 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013129 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013130}
13131
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013132static int
13133repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13134{
13135 int r;
13136 assert(count > 0);
13137 assert(PyUnicode_Check(obj));
13138 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013139 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013140 if (repeated == NULL)
13141 return -1;
13142 r = _PyAccu_Accumulate(acc, repeated);
13143 Py_DECREF(repeated);
13144 return r;
13145 }
13146 else {
13147 do {
13148 if (_PyAccu_Accumulate(acc, obj))
13149 return -1;
13150 } while (--count);
13151 return 0;
13152 }
13153}
13154
Alexander Belopolsky40018472011-02-26 01:02:56 +000013155PyObject *
13156PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013157{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013158 void *fmt;
13159 int fmtkind;
13160 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013161 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013162 int r;
13163 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013164 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013165 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013166 PyObject *temp = NULL;
13167 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013168 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013169 _PyAccu acc;
13170 static PyObject *plus, *minus, *blank, *zero, *percent;
13171
13172 if (!plus && !(plus = get_latin1_char('+')))
13173 return NULL;
13174 if (!minus && !(minus = get_latin1_char('-')))
13175 return NULL;
13176 if (!blank && !(blank = get_latin1_char(' ')))
13177 return NULL;
13178 if (!zero && !(zero = get_latin1_char('0')))
13179 return NULL;
13180 if (!percent && !(percent = get_latin1_char('%')))
13181 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013182
Guido van Rossumd57fd912000-03-10 22:53:23 +000013183 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013184 PyErr_BadInternalCall();
13185 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013186 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013187 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013188 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013189 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013190 if (_PyAccu_Init(&acc))
13191 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013192 fmt = PyUnicode_DATA(uformat);
13193 fmtkind = PyUnicode_KIND(uformat);
13194 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13195 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013196
Guido van Rossumd57fd912000-03-10 22:53:23 +000013197 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013198 arglen = PyTuple_Size(args);
13199 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013200 }
13201 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013202 arglen = -1;
13203 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013204 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013205 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013206 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013207 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013208
13209 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013210 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013211 PyObject *nonfmt;
13212 Py_ssize_t nonfmtpos;
13213 nonfmtpos = fmtpos++;
13214 while (fmtcnt >= 0 &&
13215 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13216 fmtpos++;
13217 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013218 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013219 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013220 if (nonfmt == NULL)
13221 goto onError;
13222 r = _PyAccu_Accumulate(&acc, nonfmt);
13223 Py_DECREF(nonfmt);
13224 if (r)
13225 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013226 }
13227 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013228 /* Got a format specifier */
13229 int flags = 0;
13230 Py_ssize_t width = -1;
13231 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013232 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013233 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013234 int isnumok;
13235 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013236 void *pbuf = NULL;
13237 Py_ssize_t pindex, len;
13238 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013239
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013240 fmtpos++;
13241 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13242 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013243 Py_ssize_t keylen;
13244 PyObject *key;
13245 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013246
Benjamin Peterson29060642009-01-31 22:14:21 +000013247 if (dict == NULL) {
13248 PyErr_SetString(PyExc_TypeError,
13249 "format requires a mapping");
13250 goto onError;
13251 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013252 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013253 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013254 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013255 /* Skip over balanced parentheses */
13256 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013257 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013258 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013259 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013260 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013261 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013262 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013263 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013264 if (fmtcnt < 0 || pcount > 0) {
13265 PyErr_SetString(PyExc_ValueError,
13266 "incomplete format key");
13267 goto onError;
13268 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013269 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013270 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013271 if (key == NULL)
13272 goto onError;
13273 if (args_owned) {
13274 Py_DECREF(args);
13275 args_owned = 0;
13276 }
13277 args = PyObject_GetItem(dict, key);
13278 Py_DECREF(key);
13279 if (args == NULL) {
13280 goto onError;
13281 }
13282 args_owned = 1;
13283 arglen = -1;
13284 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013285 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013286 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013287 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013288 case '-': flags |= F_LJUST; continue;
13289 case '+': flags |= F_SIGN; continue;
13290 case ' ': flags |= F_BLANK; continue;
13291 case '#': flags |= F_ALT; continue;
13292 case '0': flags |= F_ZERO; continue;
13293 }
13294 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013295 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013296 if (c == '*') {
13297 v = getnextarg(args, arglen, &argidx);
13298 if (v == NULL)
13299 goto onError;
13300 if (!PyLong_Check(v)) {
13301 PyErr_SetString(PyExc_TypeError,
13302 "* wants int");
13303 goto onError;
13304 }
13305 width = PyLong_AsLong(v);
13306 if (width == -1 && PyErr_Occurred())
13307 goto onError;
13308 if (width < 0) {
13309 flags |= F_LJUST;
13310 width = -width;
13311 }
13312 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013313 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013314 }
13315 else if (c >= '0' && c <= '9') {
13316 width = c - '0';
13317 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013318 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013319 if (c < '0' || c > '9')
13320 break;
13321 if ((width*10) / 10 != width) {
13322 PyErr_SetString(PyExc_ValueError,
13323 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013324 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013325 }
13326 width = width*10 + (c - '0');
13327 }
13328 }
13329 if (c == '.') {
13330 prec = 0;
13331 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013332 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013333 if (c == '*') {
13334 v = getnextarg(args, arglen, &argidx);
13335 if (v == NULL)
13336 goto onError;
13337 if (!PyLong_Check(v)) {
13338 PyErr_SetString(PyExc_TypeError,
13339 "* wants int");
13340 goto onError;
13341 }
13342 prec = PyLong_AsLong(v);
13343 if (prec == -1 && PyErr_Occurred())
13344 goto onError;
13345 if (prec < 0)
13346 prec = 0;
13347 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013348 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013349 }
13350 else if (c >= '0' && c <= '9') {
13351 prec = c - '0';
13352 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013353 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013354 if (c < '0' || c > '9')
13355 break;
13356 if ((prec*10) / 10 != prec) {
13357 PyErr_SetString(PyExc_ValueError,
13358 "prec too big");
13359 goto onError;
13360 }
13361 prec = prec*10 + (c - '0');
13362 }
13363 }
13364 } /* prec */
13365 if (fmtcnt >= 0) {
13366 if (c == 'h' || c == 'l' || c == 'L') {
13367 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013368 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013369 }
13370 }
13371 if (fmtcnt < 0) {
13372 PyErr_SetString(PyExc_ValueError,
13373 "incomplete format");
13374 goto onError;
13375 }
13376 if (c != '%') {
13377 v = getnextarg(args, arglen, &argidx);
13378 if (v == NULL)
13379 goto onError;
13380 }
13381 sign = 0;
13382 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013383 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013384 switch (c) {
13385
13386 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013387 _PyAccu_Accumulate(&acc, percent);
13388 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013389
13390 case 's':
13391 case 'r':
13392 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013393 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013394 temp = v;
13395 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013396 }
13397 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013398 if (c == 's')
13399 temp = PyObject_Str(v);
13400 else if (c == 'r')
13401 temp = PyObject_Repr(v);
13402 else
13403 temp = PyObject_ASCII(v);
13404 if (temp == NULL)
13405 goto onError;
13406 if (PyUnicode_Check(temp))
13407 /* nothing to do */;
13408 else {
13409 Py_DECREF(temp);
13410 PyErr_SetString(PyExc_TypeError,
13411 "%s argument has non-string str()");
13412 goto onError;
13413 }
13414 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013415 if (PyUnicode_READY(temp) == -1) {
13416 Py_CLEAR(temp);
13417 goto onError;
13418 }
13419 pbuf = PyUnicode_DATA(temp);
13420 kind = PyUnicode_KIND(temp);
13421 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013422 if (prec >= 0 && len > prec)
13423 len = prec;
13424 break;
13425
13426 case 'i':
13427 case 'd':
13428 case 'u':
13429 case 'o':
13430 case 'x':
13431 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013432 isnumok = 0;
13433 if (PyNumber_Check(v)) {
13434 PyObject *iobj=NULL;
13435
13436 if (PyLong_Check(v)) {
13437 iobj = v;
13438 Py_INCREF(iobj);
13439 }
13440 else {
13441 iobj = PyNumber_Long(v);
13442 }
13443 if (iobj!=NULL) {
13444 if (PyLong_Check(iobj)) {
13445 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013446 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013447 Py_DECREF(iobj);
13448 if (!temp)
13449 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013450 if (PyUnicode_READY(temp) == -1) {
13451 Py_CLEAR(temp);
13452 goto onError;
13453 }
13454 pbuf = PyUnicode_DATA(temp);
13455 kind = PyUnicode_KIND(temp);
13456 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013457 sign = 1;
13458 }
13459 else {
13460 Py_DECREF(iobj);
13461 }
13462 }
13463 }
13464 if (!isnumok) {
13465 PyErr_Format(PyExc_TypeError,
13466 "%%%c format: a number is required, "
13467 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13468 goto onError;
13469 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013470 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013471 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013472 fillobj = zero;
13473 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013474 break;
13475
13476 case 'e':
13477 case 'E':
13478 case 'f':
13479 case 'F':
13480 case 'g':
13481 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013482 temp = formatfloat(v, flags, prec, c);
13483 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013484 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013485 if (PyUnicode_READY(temp) == -1) {
13486 Py_CLEAR(temp);
13487 goto onError;
13488 }
13489 pbuf = PyUnicode_DATA(temp);
13490 kind = PyUnicode_KIND(temp);
13491 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013492 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013493 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013494 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013495 fillobj = zero;
13496 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013497 break;
13498
13499 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013500 {
13501 Py_UCS4 ch = formatchar(v);
13502 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013503 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013504 temp = _PyUnicode_FromUCS4(&ch, 1);
13505 if (temp == NULL)
13506 goto onError;
13507 pbuf = PyUnicode_DATA(temp);
13508 kind = PyUnicode_KIND(temp);
13509 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013510 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013511 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013512
13513 default:
13514 PyErr_Format(PyExc_ValueError,
13515 "unsupported format character '%c' (0x%x) "
13516 "at index %zd",
13517 (31<=c && c<=126) ? (char)c : '?',
13518 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013519 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013520 goto onError;
13521 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013522 /* pbuf is initialized here. */
13523 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013524 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013525 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13526 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013527 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013528 pindex++;
13529 }
13530 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13531 signobj = plus;
13532 len--;
13533 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013534 }
13535 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013536 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013537 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013538 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013539 else
13540 sign = 0;
13541 }
13542 if (width < len)
13543 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013544 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013545 if (fill != ' ') {
13546 assert(signobj != NULL);
13547 if (_PyAccu_Accumulate(&acc, signobj))
13548 goto onError;
13549 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013550 if (width > len)
13551 width--;
13552 }
13553 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013554 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013555 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013556 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013557 second = get_latin1_char(
13558 PyUnicode_READ(kind, pbuf, pindex + 1));
13559 pindex += 2;
13560 if (second == NULL ||
13561 _PyAccu_Accumulate(&acc, zero) ||
13562 _PyAccu_Accumulate(&acc, second))
13563 goto onError;
13564 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013565 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013566 width -= 2;
13567 if (width < 0)
13568 width = 0;
13569 len -= 2;
13570 }
13571 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013572 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013573 if (repeat_accumulate(&acc, fillobj, width - len))
13574 goto onError;
13575 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013576 }
13577 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013578 if (sign) {
13579 assert(signobj != NULL);
13580 if (_PyAccu_Accumulate(&acc, signobj))
13581 goto onError;
13582 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013583 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013584 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13585 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013586 second = get_latin1_char(
13587 PyUnicode_READ(kind, pbuf, pindex + 1));
13588 pindex += 2;
13589 if (second == NULL ||
13590 _PyAccu_Accumulate(&acc, zero) ||
13591 _PyAccu_Accumulate(&acc, second))
13592 goto onError;
13593 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013594 }
13595 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013596 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013597 if (temp != NULL) {
13598 assert(pbuf == PyUnicode_DATA(temp));
13599 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013600 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013601 else {
13602 const char *p = (const char *) pbuf;
13603 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013604 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013605 v = PyUnicode_FromKindAndData(kind, p, len);
13606 }
13607 if (v == NULL)
13608 goto onError;
13609 r = _PyAccu_Accumulate(&acc, v);
13610 Py_DECREF(v);
13611 if (r)
13612 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013613 if (width > len && repeat_accumulate(&acc, blank, width - len))
13614 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013615 if (dict && (argidx < arglen) && c != '%') {
13616 PyErr_SetString(PyExc_TypeError,
13617 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013618 goto onError;
13619 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013620 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013621 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013622 } /* until end */
13623 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013624 PyErr_SetString(PyExc_TypeError,
13625 "not all arguments converted during string formatting");
13626 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013627 }
13628
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013629 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013630 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013631 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013632 }
13633 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013634 Py_XDECREF(temp);
13635 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013636 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013637
Benjamin Peterson29060642009-01-31 22:14:21 +000013638 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013639 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013640 Py_XDECREF(temp);
13641 Py_XDECREF(second);
13642 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013643 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013644 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013645 }
13646 return NULL;
13647}
13648
Jeremy Hylton938ace62002-07-17 16:30:39 +000013649static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013650unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13651
Tim Peters6d6c1a32001-08-02 04:15:00 +000013652static PyObject *
13653unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13654{
Benjamin Peterson29060642009-01-31 22:14:21 +000013655 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013656 static char *kwlist[] = {"object", "encoding", "errors", 0};
13657 char *encoding = NULL;
13658 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013659
Benjamin Peterson14339b62009-01-31 16:36:08 +000013660 if (type != &PyUnicode_Type)
13661 return unicode_subtype_new(type, args, kwds);
13662 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013663 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013664 return NULL;
13665 if (x == NULL)
Victor Stinner7931d9a2011-11-04 00:22:48 +010013666 return PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013667 if (encoding == NULL && errors == NULL)
13668 return PyObject_Str(x);
13669 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013670 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013671}
13672
Guido van Rossume023fe02001-08-30 03:12:59 +000013673static PyObject *
13674unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13675{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013676 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013677 Py_ssize_t length, char_size;
13678 int share_wstr, share_utf8;
13679 unsigned int kind;
13680 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013681
Benjamin Peterson14339b62009-01-31 16:36:08 +000013682 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013683
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013684 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013685 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013686 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013687 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013688 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013689 return NULL;
13690
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013691 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013692 if (self == NULL) {
13693 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013694 return NULL;
13695 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013696 kind = PyUnicode_KIND(unicode);
13697 length = PyUnicode_GET_LENGTH(unicode);
13698
13699 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013700#ifdef Py_DEBUG
13701 _PyUnicode_HASH(self) = -1;
13702#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013703 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013704#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013705 _PyUnicode_STATE(self).interned = 0;
13706 _PyUnicode_STATE(self).kind = kind;
13707 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013708 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013709 _PyUnicode_STATE(self).ready = 1;
13710 _PyUnicode_WSTR(self) = NULL;
13711 _PyUnicode_UTF8_LENGTH(self) = 0;
13712 _PyUnicode_UTF8(self) = NULL;
13713 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013714 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013715
13716 share_utf8 = 0;
13717 share_wstr = 0;
13718 if (kind == PyUnicode_1BYTE_KIND) {
13719 char_size = 1;
13720 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13721 share_utf8 = 1;
13722 }
13723 else if (kind == PyUnicode_2BYTE_KIND) {
13724 char_size = 2;
13725 if (sizeof(wchar_t) == 2)
13726 share_wstr = 1;
13727 }
13728 else {
13729 assert(kind == PyUnicode_4BYTE_KIND);
13730 char_size = 4;
13731 if (sizeof(wchar_t) == 4)
13732 share_wstr = 1;
13733 }
13734
13735 /* Ensure we won't overflow the length. */
13736 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13737 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013738 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013739 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013740 data = PyObject_MALLOC((length + 1) * char_size);
13741 if (data == NULL) {
13742 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013743 goto onError;
13744 }
13745
Victor Stinnerc3c74152011-10-02 20:39:55 +020013746 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013747 if (share_utf8) {
13748 _PyUnicode_UTF8_LENGTH(self) = length;
13749 _PyUnicode_UTF8(self) = data;
13750 }
13751 if (share_wstr) {
13752 _PyUnicode_WSTR_LENGTH(self) = length;
13753 _PyUnicode_WSTR(self) = (wchar_t *)data;
13754 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013755
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013756 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013757 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013758 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013759#ifdef Py_DEBUG
13760 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13761#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013762 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013763 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013764
13765onError:
13766 Py_DECREF(unicode);
13767 Py_DECREF(self);
13768 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013769}
13770
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013771PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013772 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013773\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013774Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013775encoding defaults to the current default string encoding.\n\
13776errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013777
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013778static PyObject *unicode_iter(PyObject *seq);
13779
Guido van Rossumd57fd912000-03-10 22:53:23 +000013780PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013781 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013782 "str", /* tp_name */
13783 sizeof(PyUnicodeObject), /* tp_size */
13784 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013785 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013786 (destructor)unicode_dealloc, /* tp_dealloc */
13787 0, /* tp_print */
13788 0, /* tp_getattr */
13789 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013790 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013791 unicode_repr, /* tp_repr */
13792 &unicode_as_number, /* tp_as_number */
13793 &unicode_as_sequence, /* tp_as_sequence */
13794 &unicode_as_mapping, /* tp_as_mapping */
13795 (hashfunc) unicode_hash, /* tp_hash*/
13796 0, /* tp_call*/
13797 (reprfunc) unicode_str, /* tp_str */
13798 PyObject_GenericGetAttr, /* tp_getattro */
13799 0, /* tp_setattro */
13800 0, /* tp_as_buffer */
13801 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013802 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013803 unicode_doc, /* tp_doc */
13804 0, /* tp_traverse */
13805 0, /* tp_clear */
13806 PyUnicode_RichCompare, /* tp_richcompare */
13807 0, /* tp_weaklistoffset */
13808 unicode_iter, /* tp_iter */
13809 0, /* tp_iternext */
13810 unicode_methods, /* tp_methods */
13811 0, /* tp_members */
13812 0, /* tp_getset */
13813 &PyBaseObject_Type, /* tp_base */
13814 0, /* tp_dict */
13815 0, /* tp_descr_get */
13816 0, /* tp_descr_set */
13817 0, /* tp_dictoffset */
13818 0, /* tp_init */
13819 0, /* tp_alloc */
13820 unicode_new, /* tp_new */
13821 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013822};
13823
13824/* Initialize the Unicode implementation */
13825
Victor Stinner3a50e702011-10-18 21:21:00 +020013826int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013827{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013828 int i;
13829
Thomas Wouters477c8d52006-05-27 19:21:47 +000013830 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013831 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013832 0x000A, /* LINE FEED */
13833 0x000D, /* CARRIAGE RETURN */
13834 0x001C, /* FILE SEPARATOR */
13835 0x001D, /* GROUP SEPARATOR */
13836 0x001E, /* RECORD SEPARATOR */
13837 0x0085, /* NEXT LINE */
13838 0x2028, /* LINE SEPARATOR */
13839 0x2029, /* PARAGRAPH SEPARATOR */
13840 };
13841
Fred Drakee4315f52000-05-09 19:53:39 +000013842 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013843 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013844 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013845 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013846 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013847
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013848 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013849 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013850 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013851 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013852
13853 /* initialize the linebreak bloom filter */
13854 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013855 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013856 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013857
13858 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013859
13860#ifdef HAVE_MBCS
13861 winver.dwOSVersionInfoSize = sizeof(winver);
13862 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13863 PyErr_SetFromWindowsErr(0);
13864 return -1;
13865 }
13866#endif
13867 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013868}
13869
13870/* Finalize the Unicode implementation */
13871
Christian Heimesa156e092008-02-16 07:38:31 +000013872int
13873PyUnicode_ClearFreeList(void)
13874{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013875 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013876}
13877
Guido van Rossumd57fd912000-03-10 22:53:23 +000013878void
Thomas Wouters78890102000-07-22 19:25:51 +000013879_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013880{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013881 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013882
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013883 Py_XDECREF(unicode_empty);
13884 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013885
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013886 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013887 if (unicode_latin1[i]) {
13888 Py_DECREF(unicode_latin1[i]);
13889 unicode_latin1[i] = NULL;
13890 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013891 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013892 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013893 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013894}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013895
Walter Dörwald16807132007-05-25 13:52:07 +000013896void
13897PyUnicode_InternInPlace(PyObject **p)
13898{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013899 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013900 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013901#ifdef Py_DEBUG
13902 assert(s != NULL);
13903 assert(_PyUnicode_CHECK(s));
13904#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013905 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013906 return;
13907#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013908 /* If it's a subclass, we don't really know what putting
13909 it in the interned dict might do. */
13910 if (!PyUnicode_CheckExact(s))
13911 return;
13912 if (PyUnicode_CHECK_INTERNED(s))
13913 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013914 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013915 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013916 return;
13917 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013918 s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013919 if (interned == NULL) {
13920 interned = PyDict_New();
13921 if (interned == NULL) {
13922 PyErr_Clear(); /* Don't leave an exception */
13923 return;
13924 }
13925 }
13926 /* It might be that the GetItem call fails even
13927 though the key is present in the dictionary,
13928 namely when this happens during a stack overflow. */
13929 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010013930 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013931 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013932
Benjamin Peterson29060642009-01-31 22:14:21 +000013933 if (t) {
13934 Py_INCREF(t);
13935 Py_DECREF(*p);
13936 *p = t;
13937 return;
13938 }
Walter Dörwald16807132007-05-25 13:52:07 +000013939
Benjamin Peterson14339b62009-01-31 16:36:08 +000013940 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010013941 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013942 PyErr_Clear();
13943 PyThreadState_GET()->recursion_critical = 0;
13944 return;
13945 }
13946 PyThreadState_GET()->recursion_critical = 0;
13947 /* The two references in interned are not counted by refcnt.
13948 The deallocator will take care of this */
13949 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013950 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013951}
13952
13953void
13954PyUnicode_InternImmortal(PyObject **p)
13955{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013956 PyUnicode_InternInPlace(p);
13957 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020013958 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013959 Py_INCREF(*p);
13960 }
Walter Dörwald16807132007-05-25 13:52:07 +000013961}
13962
13963PyObject *
13964PyUnicode_InternFromString(const char *cp)
13965{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013966 PyObject *s = PyUnicode_FromString(cp);
13967 if (s == NULL)
13968 return NULL;
13969 PyUnicode_InternInPlace(&s);
13970 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000013971}
13972
Alexander Belopolsky40018472011-02-26 01:02:56 +000013973void
13974_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000013975{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013976 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013977 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013978 Py_ssize_t i, n;
13979 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000013980
Benjamin Peterson14339b62009-01-31 16:36:08 +000013981 if (interned == NULL || !PyDict_Check(interned))
13982 return;
13983 keys = PyDict_Keys(interned);
13984 if (keys == NULL || !PyList_Check(keys)) {
13985 PyErr_Clear();
13986 return;
13987 }
Walter Dörwald16807132007-05-25 13:52:07 +000013988
Benjamin Peterson14339b62009-01-31 16:36:08 +000013989 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
13990 detector, interned unicode strings are not forcibly deallocated;
13991 rather, we give them their stolen references back, and then clear
13992 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000013993
Benjamin Peterson14339b62009-01-31 16:36:08 +000013994 n = PyList_GET_SIZE(keys);
13995 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000013996 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013997 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013998 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013999 if (PyUnicode_READY(s) == -1) {
14000 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014001 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014002 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014003 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014004 case SSTATE_NOT_INTERNED:
14005 /* XXX Shouldn't happen */
14006 break;
14007 case SSTATE_INTERNED_IMMORTAL:
14008 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014009 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014010 break;
14011 case SSTATE_INTERNED_MORTAL:
14012 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014013 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014014 break;
14015 default:
14016 Py_FatalError("Inconsistent interned string state.");
14017 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014018 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014019 }
14020 fprintf(stderr, "total size of all interned strings: "
14021 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14022 "mortal/immortal\n", mortal_size, immortal_size);
14023 Py_DECREF(keys);
14024 PyDict_Clear(interned);
14025 Py_DECREF(interned);
14026 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014027}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014028
14029
14030/********************* Unicode Iterator **************************/
14031
14032typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014033 PyObject_HEAD
14034 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014035 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014036} unicodeiterobject;
14037
14038static void
14039unicodeiter_dealloc(unicodeiterobject *it)
14040{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014041 _PyObject_GC_UNTRACK(it);
14042 Py_XDECREF(it->it_seq);
14043 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014044}
14045
14046static int
14047unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14048{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014049 Py_VISIT(it->it_seq);
14050 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014051}
14052
14053static PyObject *
14054unicodeiter_next(unicodeiterobject *it)
14055{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014056 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014057
Benjamin Peterson14339b62009-01-31 16:36:08 +000014058 assert(it != NULL);
14059 seq = it->it_seq;
14060 if (seq == NULL)
14061 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014062 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014063
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014064 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14065 int kind = PyUnicode_KIND(seq);
14066 void *data = PyUnicode_DATA(seq);
14067 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14068 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014069 if (item != NULL)
14070 ++it->it_index;
14071 return item;
14072 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014073
Benjamin Peterson14339b62009-01-31 16:36:08 +000014074 Py_DECREF(seq);
14075 it->it_seq = NULL;
14076 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014077}
14078
14079static PyObject *
14080unicodeiter_len(unicodeiterobject *it)
14081{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014082 Py_ssize_t len = 0;
14083 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014084 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014085 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014086}
14087
14088PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14089
14090static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014091 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014092 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014093 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014094};
14095
14096PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014097 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14098 "str_iterator", /* tp_name */
14099 sizeof(unicodeiterobject), /* tp_basicsize */
14100 0, /* tp_itemsize */
14101 /* methods */
14102 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14103 0, /* tp_print */
14104 0, /* tp_getattr */
14105 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014106 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014107 0, /* tp_repr */
14108 0, /* tp_as_number */
14109 0, /* tp_as_sequence */
14110 0, /* tp_as_mapping */
14111 0, /* tp_hash */
14112 0, /* tp_call */
14113 0, /* tp_str */
14114 PyObject_GenericGetAttr, /* tp_getattro */
14115 0, /* tp_setattro */
14116 0, /* tp_as_buffer */
14117 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14118 0, /* tp_doc */
14119 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14120 0, /* tp_clear */
14121 0, /* tp_richcompare */
14122 0, /* tp_weaklistoffset */
14123 PyObject_SelfIter, /* tp_iter */
14124 (iternextfunc)unicodeiter_next, /* tp_iternext */
14125 unicodeiter_methods, /* tp_methods */
14126 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014127};
14128
14129static PyObject *
14130unicode_iter(PyObject *seq)
14131{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014132 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014133
Benjamin Peterson14339b62009-01-31 16:36:08 +000014134 if (!PyUnicode_Check(seq)) {
14135 PyErr_BadInternalCall();
14136 return NULL;
14137 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014138 if (PyUnicode_READY(seq) == -1)
14139 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014140 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14141 if (it == NULL)
14142 return NULL;
14143 it->it_index = 0;
14144 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014145 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014146 _PyObject_GC_TRACK(it);
14147 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014148}
14149
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014150
14151size_t
14152Py_UNICODE_strlen(const Py_UNICODE *u)
14153{
14154 int res = 0;
14155 while(*u++)
14156 res++;
14157 return res;
14158}
14159
14160Py_UNICODE*
14161Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14162{
14163 Py_UNICODE *u = s1;
14164 while ((*u++ = *s2++));
14165 return s1;
14166}
14167
14168Py_UNICODE*
14169Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14170{
14171 Py_UNICODE *u = s1;
14172 while ((*u++ = *s2++))
14173 if (n-- == 0)
14174 break;
14175 return s1;
14176}
14177
14178Py_UNICODE*
14179Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14180{
14181 Py_UNICODE *u1 = s1;
14182 u1 += Py_UNICODE_strlen(u1);
14183 Py_UNICODE_strcpy(u1, s2);
14184 return s1;
14185}
14186
14187int
14188Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14189{
14190 while (*s1 && *s2 && *s1 == *s2)
14191 s1++, s2++;
14192 if (*s1 && *s2)
14193 return (*s1 < *s2) ? -1 : +1;
14194 if (*s1)
14195 return 1;
14196 if (*s2)
14197 return -1;
14198 return 0;
14199}
14200
14201int
14202Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14203{
14204 register Py_UNICODE u1, u2;
14205 for (; n != 0; n--) {
14206 u1 = *s1;
14207 u2 = *s2;
14208 if (u1 != u2)
14209 return (u1 < u2) ? -1 : +1;
14210 if (u1 == '\0')
14211 return 0;
14212 s1++;
14213 s2++;
14214 }
14215 return 0;
14216}
14217
14218Py_UNICODE*
14219Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14220{
14221 const Py_UNICODE *p;
14222 for (p = s; *p; p++)
14223 if (*p == c)
14224 return (Py_UNICODE*)p;
14225 return NULL;
14226}
14227
14228Py_UNICODE*
14229Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14230{
14231 const Py_UNICODE *p;
14232 p = s + Py_UNICODE_strlen(s);
14233 while (p != s) {
14234 p--;
14235 if (*p == c)
14236 return (Py_UNICODE*)p;
14237 }
14238 return NULL;
14239}
Victor Stinner331ea922010-08-10 16:37:20 +000014240
Victor Stinner71133ff2010-09-01 23:43:53 +000014241Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014242PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014243{
Victor Stinner577db2c2011-10-11 22:12:48 +020014244 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014245 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014246
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014247 if (!PyUnicode_Check(unicode)) {
14248 PyErr_BadArgument();
14249 return NULL;
14250 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014251 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014252 if (u == NULL)
14253 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014254 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014255 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014256 PyErr_NoMemory();
14257 return NULL;
14258 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014259 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014260 size *= sizeof(Py_UNICODE);
14261 copy = PyMem_Malloc(size);
14262 if (copy == NULL) {
14263 PyErr_NoMemory();
14264 return NULL;
14265 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014266 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014267 return copy;
14268}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014269
Georg Brandl66c221e2010-10-14 07:04:07 +000014270/* A _string module, to export formatter_parser and formatter_field_name_split
14271 to the string.Formatter class implemented in Python. */
14272
14273static PyMethodDef _string_methods[] = {
14274 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14275 METH_O, PyDoc_STR("split the argument as a field name")},
14276 {"formatter_parser", (PyCFunction) formatter_parser,
14277 METH_O, PyDoc_STR("parse the argument as a format string")},
14278 {NULL, NULL}
14279};
14280
14281static struct PyModuleDef _string_module = {
14282 PyModuleDef_HEAD_INIT,
14283 "_string",
14284 PyDoc_STR("string helper module"),
14285 0,
14286 _string_methods,
14287 NULL,
14288 NULL,
14289 NULL,
14290 NULL
14291};
14292
14293PyMODINIT_FUNC
14294PyInit__string(void)
14295{
14296 return PyModule_Create(&_string_module);
14297}
14298
14299
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014300#ifdef __cplusplus
14301}
14302#endif