blob: b02adeed91ac187bf6846cc25baee679a5208a61 [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{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002058 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002059 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 Stinnerac931b12011-11-20 18:27:03 +01003054 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003055#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003056 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003057#else
Victor Stinner793b5312011-04-27 00:24:21 +02003058 PyInterpreterState *interp = PyThreadState_GET()->interp;
3059 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3060 cannot use it to encode and decode filenames before it is loaded. Load
3061 the Python codec requires to encode at least its own filename. Use the C
3062 version of the locale codec until the codec registry is initialized and
3063 the Python codec is loaded.
3064
3065 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3066 cannot only rely on it: check also interp->fscodec_initialized for
3067 subinterpreters. */
3068 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003069 return PyUnicode_AsEncodedString(unicode,
3070 Py_FileSystemDefaultEncoding,
3071 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003072 }
3073 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003074 /* locale encoding with surrogateescape */
3075 wchar_t *wchar;
3076 char *bytes;
3077 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003078 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003079
3080 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3081 if (wchar == NULL)
3082 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003083 bytes = _Py_wchar2char(wchar, &error_pos);
3084 if (bytes == NULL) {
3085 if (error_pos != (size_t)-1) {
3086 char *errmsg = strerror(errno);
3087 PyObject *exc = NULL;
3088 if (errmsg == NULL)
3089 errmsg = "Py_wchar2char() failed";
3090 raise_encode_exception(&exc,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01003091 "filesystemencoding", unicode,
Victor Stinner2f02a512010-11-08 22:43:46 +00003092 error_pos, error_pos+1,
3093 errmsg);
3094 Py_XDECREF(exc);
3095 }
3096 else
3097 PyErr_NoMemory();
3098 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003099 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003100 }
3101 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003102
3103 bytes_obj = PyBytes_FromString(bytes);
3104 PyMem_Free(bytes);
3105 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003106 }
Victor Stinnerad158722010-10-27 00:25:46 +00003107#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003108}
3109
Alexander Belopolsky40018472011-02-26 01:02:56 +00003110PyObject *
3111PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003112 const char *encoding,
3113 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003114{
3115 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003116 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003117
Guido van Rossumd57fd912000-03-10 22:53:23 +00003118 if (!PyUnicode_Check(unicode)) {
3119 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003120 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003121 }
Fred Drakee4315f52000-05-09 19:53:39 +00003122
Fred Drakee4315f52000-05-09 19:53:39 +00003123 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003124 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003125 if ((strcmp(lower, "utf-8") == 0) ||
3126 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003127 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003128 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003129 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003130 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003131 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003132 }
Victor Stinner37296e82010-06-10 13:36:23 +00003133 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003134 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003135 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003136 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003137#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003138 else if (strcmp(lower, "mbcs") == 0)
3139 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003140#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003141 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003142 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003143 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003144
3145 /* Encode via the codec registry */
3146 v = PyCodec_Encode(unicode, encoding, errors);
3147 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003148 return NULL;
3149
3150 /* The normal path */
3151 if (PyBytes_Check(v))
3152 return v;
3153
3154 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003155 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003156 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003157 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003158
3159 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3160 "encoder %s returned bytearray instead of bytes",
3161 encoding);
3162 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003163 Py_DECREF(v);
3164 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003165 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003166
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003167 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3168 Py_DECREF(v);
3169 return b;
3170 }
3171
3172 PyErr_Format(PyExc_TypeError,
3173 "encoder did not return a bytes object (type=%.400s)",
3174 Py_TYPE(v)->tp_name);
3175 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003176 return NULL;
3177}
3178
Alexander Belopolsky40018472011-02-26 01:02:56 +00003179PyObject *
3180PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003181 const char *encoding,
3182 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003183{
3184 PyObject *v;
3185
3186 if (!PyUnicode_Check(unicode)) {
3187 PyErr_BadArgument();
3188 goto onError;
3189 }
3190
3191 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003192 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003193
3194 /* Encode via the codec registry */
3195 v = PyCodec_Encode(unicode, encoding, errors);
3196 if (v == NULL)
3197 goto onError;
3198 if (!PyUnicode_Check(v)) {
3199 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003200 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003201 Py_TYPE(v)->tp_name);
3202 Py_DECREF(v);
3203 goto onError;
3204 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003205 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003206
Benjamin Peterson29060642009-01-31 22:14:21 +00003207 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003208 return NULL;
3209}
3210
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003211PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003212PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003213 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003214 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3215}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003216
Christian Heimes5894ba72007-11-04 11:43:14 +00003217PyObject*
3218PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3219{
Victor Stinner99b95382011-07-04 14:23:54 +02003220#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003221 return PyUnicode_DecodeMBCS(s, size, NULL);
3222#elif defined(__APPLE__)
3223 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3224#else
Victor Stinner793b5312011-04-27 00:24:21 +02003225 PyInterpreterState *interp = PyThreadState_GET()->interp;
3226 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3227 cannot use it to encode and decode filenames before it is loaded. Load
3228 the Python codec requires to encode at least its own filename. Use the C
3229 version of the locale codec until the codec registry is initialized and
3230 the Python codec is loaded.
3231
3232 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3233 cannot only rely on it: check also interp->fscodec_initialized for
3234 subinterpreters. */
3235 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003236 return PyUnicode_Decode(s, size,
3237 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003238 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003239 }
3240 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003241 /* locale encoding with surrogateescape */
3242 wchar_t *wchar;
3243 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003244 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003245
3246 if (s[size] != '\0' || size != strlen(s)) {
3247 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3248 return NULL;
3249 }
3250
Victor Stinner168e1172010-10-16 23:16:16 +00003251 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003252 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003253 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003254
Victor Stinner168e1172010-10-16 23:16:16 +00003255 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003256 PyMem_Free(wchar);
3257 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003258 }
Victor Stinnerad158722010-10-27 00:25:46 +00003259#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003260}
3261
Martin v. Löwis011e8422009-05-05 04:43:17 +00003262
3263int
3264PyUnicode_FSConverter(PyObject* arg, void* addr)
3265{
3266 PyObject *output = NULL;
3267 Py_ssize_t size;
3268 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003269 if (arg == NULL) {
3270 Py_DECREF(*(PyObject**)addr);
3271 return 1;
3272 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003273 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003274 output = arg;
3275 Py_INCREF(output);
3276 }
3277 else {
3278 arg = PyUnicode_FromObject(arg);
3279 if (!arg)
3280 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003281 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003282 Py_DECREF(arg);
3283 if (!output)
3284 return 0;
3285 if (!PyBytes_Check(output)) {
3286 Py_DECREF(output);
3287 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3288 return 0;
3289 }
3290 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003291 size = PyBytes_GET_SIZE(output);
3292 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003293 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003294 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003295 Py_DECREF(output);
3296 return 0;
3297 }
3298 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003299 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003300}
3301
3302
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003303int
3304PyUnicode_FSDecoder(PyObject* arg, void* addr)
3305{
3306 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003307 if (arg == NULL) {
3308 Py_DECREF(*(PyObject**)addr);
3309 return 1;
3310 }
3311 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003312 if (PyUnicode_READY(arg))
3313 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003314 output = arg;
3315 Py_INCREF(output);
3316 }
3317 else {
3318 arg = PyBytes_FromObject(arg);
3319 if (!arg)
3320 return 0;
3321 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3322 PyBytes_GET_SIZE(arg));
3323 Py_DECREF(arg);
3324 if (!output)
3325 return 0;
3326 if (!PyUnicode_Check(output)) {
3327 Py_DECREF(output);
3328 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3329 return 0;
3330 }
3331 }
Victor Stinner065836e2011-10-27 01:56:33 +02003332 if (PyUnicode_READY(output) < 0) {
3333 Py_DECREF(output);
3334 return 0;
3335 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003336 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003337 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003338 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3339 Py_DECREF(output);
3340 return 0;
3341 }
3342 *(PyObject**)addr = output;
3343 return Py_CLEANUP_SUPPORTED;
3344}
3345
3346
Martin v. Löwis5b222132007-06-10 09:51:05 +00003347char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003348PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003349{
Christian Heimesf3863112007-11-22 07:46:41 +00003350 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003351
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003352 if (!PyUnicode_Check(unicode)) {
3353 PyErr_BadArgument();
3354 return NULL;
3355 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003356 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003357 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003358
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003359 if (PyUnicode_UTF8(unicode) == NULL) {
3360 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003361 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3362 if (bytes == NULL)
3363 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003364 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3365 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003366 Py_DECREF(bytes);
3367 return NULL;
3368 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003369 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3370 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3371 PyBytes_AS_STRING(bytes),
3372 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003373 Py_DECREF(bytes);
3374 }
3375
3376 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003377 *psize = PyUnicode_UTF8_LENGTH(unicode);
3378 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003379}
3380
3381char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003382PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003383{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003384 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3385}
3386
3387#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003388static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003389#endif
3390
3391
3392Py_UNICODE *
3393PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3394{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003395 const unsigned char *one_byte;
3396#if SIZEOF_WCHAR_T == 4
3397 const Py_UCS2 *two_bytes;
3398#else
3399 const Py_UCS4 *four_bytes;
3400 const Py_UCS4 *ucs4_end;
3401 Py_ssize_t num_surrogates;
3402#endif
3403 wchar_t *w;
3404 wchar_t *wchar_end;
3405
3406 if (!PyUnicode_Check(unicode)) {
3407 PyErr_BadArgument();
3408 return NULL;
3409 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003410 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003411 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003412 assert(_PyUnicode_KIND(unicode) != 0);
3413 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003414
3415#ifdef Py_DEBUG
3416 ++unicode_as_unicode_calls;
3417#endif
3418
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003419 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003420#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003421 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3422 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003423 num_surrogates = 0;
3424
3425 for (; four_bytes < ucs4_end; ++four_bytes) {
3426 if (*four_bytes > 0xFFFF)
3427 ++num_surrogates;
3428 }
3429
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003430 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3431 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3432 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003433 PyErr_NoMemory();
3434 return NULL;
3435 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003436 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003437
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003438 w = _PyUnicode_WSTR(unicode);
3439 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3440 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003441 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3442 if (*four_bytes > 0xFFFF) {
3443 /* encode surrogate pair in this case */
3444 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3445 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3446 }
3447 else
3448 *w = *four_bytes;
3449
3450 if (w > wchar_end) {
3451 assert(0 && "Miscalculated string end");
3452 }
3453 }
3454 *w = 0;
3455#else
3456 /* sizeof(wchar_t) == 4 */
3457 Py_FatalError("Impossible unicode object state, wstr and str "
3458 "should share memory already.");
3459 return NULL;
3460#endif
3461 }
3462 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003463 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3464 (_PyUnicode_LENGTH(unicode) + 1));
3465 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003466 PyErr_NoMemory();
3467 return NULL;
3468 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003469 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3470 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3471 w = _PyUnicode_WSTR(unicode);
3472 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003473
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003474 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3475 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003476 for (; w < wchar_end; ++one_byte, ++w)
3477 *w = *one_byte;
3478 /* null-terminate the wstr */
3479 *w = 0;
3480 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003481 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003482#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003483 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003484 for (; w < wchar_end; ++two_bytes, ++w)
3485 *w = *two_bytes;
3486 /* null-terminate the wstr */
3487 *w = 0;
3488#else
3489 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003490 PyObject_FREE(_PyUnicode_WSTR(unicode));
3491 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003492 Py_FatalError("Impossible unicode object state, wstr "
3493 "and str should share memory already.");
3494 return NULL;
3495#endif
3496 }
3497 else {
3498 assert(0 && "This should never happen.");
3499 }
3500 }
3501 }
3502 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003503 *size = PyUnicode_WSTR_LENGTH(unicode);
3504 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003505}
3506
Alexander Belopolsky40018472011-02-26 01:02:56 +00003507Py_UNICODE *
3508PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003509{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003510 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003511}
3512
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003513
Alexander Belopolsky40018472011-02-26 01:02:56 +00003514Py_ssize_t
3515PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003516{
3517 if (!PyUnicode_Check(unicode)) {
3518 PyErr_BadArgument();
3519 goto onError;
3520 }
3521 return PyUnicode_GET_SIZE(unicode);
3522
Benjamin Peterson29060642009-01-31 22:14:21 +00003523 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003524 return -1;
3525}
3526
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003527Py_ssize_t
3528PyUnicode_GetLength(PyObject *unicode)
3529{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003530 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003531 PyErr_BadArgument();
3532 return -1;
3533 }
3534
3535 return PyUnicode_GET_LENGTH(unicode);
3536}
3537
3538Py_UCS4
3539PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3540{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003541 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3542 PyErr_BadArgument();
3543 return (Py_UCS4)-1;
3544 }
3545 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3546 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003547 return (Py_UCS4)-1;
3548 }
3549 return PyUnicode_READ_CHAR(unicode, index);
3550}
3551
3552int
3553PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3554{
3555 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003556 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003557 return -1;
3558 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003559 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3560 PyErr_SetString(PyExc_IndexError, "string index out of range");
3561 return -1;
3562 }
3563 if (_PyUnicode_Dirty(unicode))
3564 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003565 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3566 index, ch);
3567 return 0;
3568}
3569
Alexander Belopolsky40018472011-02-26 01:02:56 +00003570const char *
3571PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003572{
Victor Stinner42cb4622010-09-01 19:39:01 +00003573 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003574}
3575
Victor Stinner554f3f02010-06-16 23:33:54 +00003576/* create or adjust a UnicodeDecodeError */
3577static void
3578make_decode_exception(PyObject **exceptionObject,
3579 const char *encoding,
3580 const char *input, Py_ssize_t length,
3581 Py_ssize_t startpos, Py_ssize_t endpos,
3582 const char *reason)
3583{
3584 if (*exceptionObject == NULL) {
3585 *exceptionObject = PyUnicodeDecodeError_Create(
3586 encoding, input, length, startpos, endpos, reason);
3587 }
3588 else {
3589 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3590 goto onError;
3591 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3592 goto onError;
3593 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3594 goto onError;
3595 }
3596 return;
3597
3598onError:
3599 Py_DECREF(*exceptionObject);
3600 *exceptionObject = NULL;
3601}
3602
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003603/* error handling callback helper:
3604 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003605 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003606 and adjust various state variables.
3607 return 0 on success, -1 on error
3608*/
3609
Alexander Belopolsky40018472011-02-26 01:02:56 +00003610static int
3611unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003612 const char *encoding, const char *reason,
3613 const char **input, const char **inend, Py_ssize_t *startinpos,
3614 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003615 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003616{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003617 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003618
3619 PyObject *restuple = NULL;
3620 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003621 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003622 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003623 Py_ssize_t requiredsize;
3624 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003625 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003626 int res = -1;
3627
Victor Stinner596a6c42011-11-09 00:02:18 +01003628 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
3629 outsize = PyUnicode_GET_LENGTH(*output);
3630 else
3631 outsize = _PyUnicode_WSTR_LENGTH(*output);
3632
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003633 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003634 *errorHandler = PyCodec_LookupError(errors);
3635 if (*errorHandler == NULL)
3636 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003637 }
3638
Victor Stinner554f3f02010-06-16 23:33:54 +00003639 make_decode_exception(exceptionObject,
3640 encoding,
3641 *input, *inend - *input,
3642 *startinpos, *endinpos,
3643 reason);
3644 if (*exceptionObject == NULL)
3645 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003646
3647 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3648 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003649 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003650 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003651 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003652 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003653 }
3654 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003655 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003656 if (PyUnicode_READY(repunicode) < 0)
3657 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003658
3659 /* Copy back the bytes variables, which might have been modified by the
3660 callback */
3661 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3662 if (!inputobj)
3663 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003664 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003665 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003666 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003667 *input = PyBytes_AS_STRING(inputobj);
3668 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003669 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003670 /* we can DECREF safely, as the exception has another reference,
3671 so the object won't go away. */
3672 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003673
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003674 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003675 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003676 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003677 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3678 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003679 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003680
Victor Stinner596a6c42011-11-09 00:02:18 +01003681 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
3682 /* need more space? (at least enough for what we
3683 have+the replacement+the rest of the string (starting
3684 at the new input position), so we won't have to check space
3685 when there are no errors in the rest of the string) */
3686 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
3687 requiredsize = *outpos + replen + insize-newpos;
3688 if (requiredsize > outsize) {
3689 if (requiredsize<2*outsize)
3690 requiredsize = 2*outsize;
3691 if (unicode_resize(output, requiredsize) < 0)
3692 goto onError;
3693 }
3694 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003695 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01003696 copy_characters(*output, *outpos, repunicode, 0, replen);
3697 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003698 }
Victor Stinner596a6c42011-11-09 00:02:18 +01003699 else {
3700 wchar_t *repwstr;
3701 Py_ssize_t repwlen;
3702 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
3703 if (repwstr == NULL)
3704 goto onError;
3705 /* need more space? (at least enough for what we
3706 have+the replacement+the rest of the string (starting
3707 at the new input position), so we won't have to check space
3708 when there are no errors in the rest of the string) */
3709 requiredsize = *outpos + repwlen + insize-newpos;
3710 if (requiredsize > outsize) {
3711 if (requiredsize < 2*outsize)
3712 requiredsize = 2*outsize;
3713 if (unicode_resize(output, requiredsize) < 0)
3714 goto onError;
3715 }
3716 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
3717 *outpos += repwlen;
3718 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003719 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003720 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003721
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003722 /* we made it! */
3723 res = 0;
3724
Benjamin Peterson29060642009-01-31 22:14:21 +00003725 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003726 Py_XDECREF(restuple);
3727 return res;
3728}
3729
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003730/* --- UTF-7 Codec -------------------------------------------------------- */
3731
Antoine Pitrou244651a2009-05-04 18:56:13 +00003732/* See RFC2152 for details. We encode conservatively and decode liberally. */
3733
3734/* Three simple macros defining base-64. */
3735
3736/* Is c a base-64 character? */
3737
3738#define IS_BASE64(c) \
3739 (((c) >= 'A' && (c) <= 'Z') || \
3740 ((c) >= 'a' && (c) <= 'z') || \
3741 ((c) >= '0' && (c) <= '9') || \
3742 (c) == '+' || (c) == '/')
3743
3744/* given that c is a base-64 character, what is its base-64 value? */
3745
3746#define FROM_BASE64(c) \
3747 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3748 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3749 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3750 (c) == '+' ? 62 : 63)
3751
3752/* What is the base-64 character of the bottom 6 bits of n? */
3753
3754#define TO_BASE64(n) \
3755 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3756
3757/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3758 * decoded as itself. We are permissive on decoding; the only ASCII
3759 * byte not decoding to itself is the + which begins a base64
3760 * string. */
3761
3762#define DECODE_DIRECT(c) \
3763 ((c) <= 127 && (c) != '+')
3764
3765/* The UTF-7 encoder treats ASCII characters differently according to
3766 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3767 * the above). See RFC2152. This array identifies these different
3768 * sets:
3769 * 0 : "Set D"
3770 * alphanumeric and '(),-./:?
3771 * 1 : "Set O"
3772 * !"#$%&*;<=>@[]^_`{|}
3773 * 2 : "whitespace"
3774 * ht nl cr sp
3775 * 3 : special (must be base64 encoded)
3776 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3777 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003778
Tim Petersced69f82003-09-16 20:30:58 +00003779static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003780char utf7_category[128] = {
3781/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3782 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3783/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3784 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3785/* sp ! " # $ % & ' ( ) * + , - . / */
3786 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3787/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3788 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3789/* @ A B C D E F G H I J K L M N O */
3790 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3791/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3792 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
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 { | } ~ del */
3796 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003797};
3798
Antoine Pitrou244651a2009-05-04 18:56:13 +00003799/* ENCODE_DIRECT: this character should be encoded as itself. The
3800 * answer depends on whether we are encoding set O as itself, and also
3801 * on whether we are encoding whitespace as itself. RFC2152 makes it
3802 * clear that the answers to these questions vary between
3803 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003804
Antoine Pitrou244651a2009-05-04 18:56:13 +00003805#define ENCODE_DIRECT(c, directO, directWS) \
3806 ((c) < 128 && (c) > 0 && \
3807 ((utf7_category[(c)] == 0) || \
3808 (directWS && (utf7_category[(c)] == 2)) || \
3809 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003810
Alexander Belopolsky40018472011-02-26 01:02:56 +00003811PyObject *
3812PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003813 Py_ssize_t size,
3814 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003815{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003816 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3817}
3818
Antoine Pitrou244651a2009-05-04 18:56:13 +00003819/* The decoder. The only state we preserve is our read position,
3820 * i.e. how many characters we have consumed. So if we end in the
3821 * middle of a shift sequence we have to back off the read position
3822 * and the output to the beginning of the sequence, otherwise we lose
3823 * all the shift state (seen bits, number of bits seen, high
3824 * surrogate). */
3825
Alexander Belopolsky40018472011-02-26 01:02:56 +00003826PyObject *
3827PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003828 Py_ssize_t size,
3829 const char *errors,
3830 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003831{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003832 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003833 Py_ssize_t startinpos;
3834 Py_ssize_t endinpos;
3835 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003836 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003837 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003838 const char *errmsg = "";
3839 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003840 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003841 unsigned int base64bits = 0;
3842 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01003843 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003844 PyObject *errorHandler = NULL;
3845 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003846
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003847 /* Start off assuming it's all ASCII. Widen later as necessary. */
3848 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003849 if (!unicode)
3850 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003851 if (size == 0) {
3852 if (consumed)
3853 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003854 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003855 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003856
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003857 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003858 e = s + size;
3859
3860 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003861 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003862 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003863 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003864
Antoine Pitrou244651a2009-05-04 18:56:13 +00003865 if (inShift) { /* in a base-64 section */
3866 if (IS_BASE64(ch)) { /* consume a base-64 character */
3867 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3868 base64bits += 6;
3869 s++;
3870 if (base64bits >= 16) {
3871 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01003872 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00003873 base64bits -= 16;
3874 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3875 if (surrogate) {
3876 /* expecting a second surrogate */
3877 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003878 Py_UCS4 ch2 = (((surrogate & 0x3FF)<<10)
3879 | (outCh & 0x3FF)) + 0x10000;
3880 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
3881 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003882 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003883 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003884 }
3885 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01003886 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
3887 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003888 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003889 }
3890 }
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003891 if (outCh >= 0xD800 && outCh <= 0xDBFF) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003892 /* first surrogate */
3893 surrogate = outCh;
3894 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003895 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003896 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
3897 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003898 }
3899 }
3900 }
3901 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003902 inShift = 0;
3903 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003904 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01003905 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
3906 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003907 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003908 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003909 if (base64bits > 0) { /* left-over bits */
3910 if (base64bits >= 6) {
3911 /* We've seen at least one base-64 character */
3912 errmsg = "partial character in shift sequence";
3913 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003914 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003915 else {
3916 /* Some bits remain; they should be zero */
3917 if (base64buffer != 0) {
3918 errmsg = "non-zero padding bits in shift sequence";
3919 goto utf7Error;
3920 }
3921 }
3922 }
3923 if (ch != '-') {
3924 /* '-' is absorbed; other terminating
3925 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003926 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3927 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003928 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003929 }
3930 }
3931 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003932 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003933 s++; /* consume '+' */
3934 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003935 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003936 if (unicode_putchar(&unicode, &outpos, '+') < 0)
3937 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003938 }
3939 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003940 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003941 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003942 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003943 }
3944 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003945 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003946 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3947 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003948 s++;
3949 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003950 else {
3951 startinpos = s-starts;
3952 s++;
3953 errmsg = "unexpected special character";
3954 goto utf7Error;
3955 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003956 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003957utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003958 endinpos = s-starts;
3959 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003960 errors, &errorHandler,
3961 "utf7", errmsg,
3962 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003963 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003964 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003965 }
3966
Antoine Pitrou244651a2009-05-04 18:56:13 +00003967 /* end of string */
3968
3969 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3970 /* if we're in an inconsistent state, that's an error */
3971 if (surrogate ||
3972 (base64bits >= 6) ||
3973 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003974 endinpos = size;
3975 if (unicode_decode_call_errorhandler(
3976 errors, &errorHandler,
3977 "utf7", "unterminated shift sequence",
3978 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003979 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00003980 goto onError;
3981 if (s < e)
3982 goto restart;
3983 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003984 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003985
3986 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003987 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003988 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003989 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003990 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003991 }
3992 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003993 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003994 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003995 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003996
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003997 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003998 goto onError;
3999
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004000 Py_XDECREF(errorHandler);
4001 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004002#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004003 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004004 Py_DECREF(unicode);
4005 return NULL;
4006 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004007#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004008 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004009 return unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004010
Benjamin Peterson29060642009-01-31 22:14:21 +00004011 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004012 Py_XDECREF(errorHandler);
4013 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004014 Py_DECREF(unicode);
4015 return NULL;
4016}
4017
4018
Alexander Belopolsky40018472011-02-26 01:02:56 +00004019PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004020_PyUnicode_EncodeUTF7(PyObject *str,
4021 int base64SetO,
4022 int base64WhiteSpace,
4023 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004024{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004025 int kind;
4026 void *data;
4027 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004028 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004029 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004030 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004031 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004032 unsigned int base64bits = 0;
4033 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004034 char * out;
4035 char * start;
4036
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004037 if (PyUnicode_READY(str) < 0)
4038 return NULL;
4039 kind = PyUnicode_KIND(str);
4040 data = PyUnicode_DATA(str);
4041 len = PyUnicode_GET_LENGTH(str);
4042
4043 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004044 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004045
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004046 /* It might be possible to tighten this worst case */
4047 allocated = 8 * len;
4048 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004049 return PyErr_NoMemory();
4050
Antoine Pitrou244651a2009-05-04 18:56:13 +00004051 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004052 if (v == NULL)
4053 return NULL;
4054
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004055 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004056 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004057 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004058
Antoine Pitrou244651a2009-05-04 18:56:13 +00004059 if (inShift) {
4060 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4061 /* shifting out */
4062 if (base64bits) { /* output remaining bits */
4063 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4064 base64buffer = 0;
4065 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004066 }
4067 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004068 /* Characters not in the BASE64 set implicitly unshift the sequence
4069 so no '-' is required, except if the character is itself a '-' */
4070 if (IS_BASE64(ch) || ch == '-') {
4071 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004072 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004073 *out++ = (char) ch;
4074 }
4075 else {
4076 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004077 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004078 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004079 else { /* not in a shift sequence */
4080 if (ch == '+') {
4081 *out++ = '+';
4082 *out++ = '-';
4083 }
4084 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4085 *out++ = (char) ch;
4086 }
4087 else {
4088 *out++ = '+';
4089 inShift = 1;
4090 goto encode_char;
4091 }
4092 }
4093 continue;
4094encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004095 if (ch >= 0x10000) {
4096 /* code first surrogate */
4097 base64bits += 16;
4098 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4099 while (base64bits >= 6) {
4100 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4101 base64bits -= 6;
4102 }
4103 /* prepare second surrogate */
4104 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4105 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004106 base64bits += 16;
4107 base64buffer = (base64buffer << 16) | ch;
4108 while (base64bits >= 6) {
4109 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4110 base64bits -= 6;
4111 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004112 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004113 if (base64bits)
4114 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4115 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004116 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004117 if (_PyBytes_Resize(&v, out - start) < 0)
4118 return NULL;
4119 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004120}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004121PyObject *
4122PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4123 Py_ssize_t size,
4124 int base64SetO,
4125 int base64WhiteSpace,
4126 const char *errors)
4127{
4128 PyObject *result;
4129 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4130 if (tmp == NULL)
4131 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004132 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004133 base64WhiteSpace, errors);
4134 Py_DECREF(tmp);
4135 return result;
4136}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004137
Antoine Pitrou244651a2009-05-04 18:56:13 +00004138#undef IS_BASE64
4139#undef FROM_BASE64
4140#undef TO_BASE64
4141#undef DECODE_DIRECT
4142#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004143
Guido van Rossumd57fd912000-03-10 22:53:23 +00004144/* --- UTF-8 Codec -------------------------------------------------------- */
4145
Tim Petersced69f82003-09-16 20:30:58 +00004146static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004147char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004148 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4149 illegal prefix. See RFC 3629 for details */
4150 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4151 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004152 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004153 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4154 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4155 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4156 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004157 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4158 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 +00004159 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4160 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004161 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4162 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4163 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4164 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4165 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 +00004166};
4167
Alexander Belopolsky40018472011-02-26 01:02:56 +00004168PyObject *
4169PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004170 Py_ssize_t size,
4171 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004172{
Walter Dörwald69652032004-09-07 20:24:22 +00004173 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4174}
4175
Antoine Pitrouab868312009-01-10 15:40:25 +00004176/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4177#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4178
4179/* Mask to quickly check whether a C 'long' contains a
4180 non-ASCII, UTF8-encoded char. */
4181#if (SIZEOF_LONG == 8)
4182# define ASCII_CHAR_MASK 0x8080808080808080L
4183#elif (SIZEOF_LONG == 4)
4184# define ASCII_CHAR_MASK 0x80808080L
4185#else
4186# error C 'long' size should be either 4 or 8!
4187#endif
4188
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004189/* Scans a UTF-8 string and returns the maximum character to be expected,
4190 the size of the decoded unicode string and if any major errors were
4191 encountered.
4192
4193 This function does check basic UTF-8 sanity, it does however NOT CHECK
4194 if the string contains surrogates, and if all continuation bytes are
4195 within the correct ranges, these checks are performed in
4196 PyUnicode_DecodeUTF8Stateful.
4197
4198 If it sets has_errors to 1, it means the value of unicode_size and max_char
4199 will be bogus and you should not rely on useful information in them.
4200 */
4201static Py_UCS4
4202utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4203 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4204 int *has_errors)
4205{
4206 Py_ssize_t n;
4207 Py_ssize_t char_count = 0;
4208 Py_UCS4 max_char = 127, new_max;
4209 Py_UCS4 upper_bound;
4210 const unsigned char *p = (const unsigned char *)s;
4211 const unsigned char *end = p + string_size;
4212 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4213 int err = 0;
4214
4215 for (; p < end && !err; ++p, ++char_count) {
4216 /* Only check value if it's not a ASCII char... */
4217 if (*p < 0x80) {
4218 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4219 an explanation. */
4220 if (!((size_t) p & LONG_PTR_MASK)) {
4221 /* Help register allocation */
4222 register const unsigned char *_p = p;
4223 while (_p < aligned_end) {
4224 unsigned long value = *(unsigned long *) _p;
4225 if (value & ASCII_CHAR_MASK)
4226 break;
4227 _p += SIZEOF_LONG;
4228 char_count += SIZEOF_LONG;
4229 }
4230 p = _p;
4231 if (p == end)
4232 break;
4233 }
4234 }
4235 if (*p >= 0x80) {
4236 n = utf8_code_length[*p];
4237 new_max = max_char;
4238 switch (n) {
4239 /* invalid start byte */
4240 case 0:
4241 err = 1;
4242 break;
4243 case 2:
4244 /* Code points between 0x00FF and 0x07FF inclusive.
4245 Approximate the upper bound of the code point,
4246 if this flips over 255 we can be sure it will be more
4247 than 255 and the string will need 2 bytes per code coint,
4248 if it stays under or equal to 255, we can be sure 1 byte
4249 is enough.
4250 ((*p & 0b00011111) << 6) | 0b00111111 */
4251 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4252 if (max_char < upper_bound)
4253 new_max = upper_bound;
4254 /* Ensure we track at least that we left ASCII space. */
4255 if (new_max < 128)
4256 new_max = 128;
4257 break;
4258 case 3:
4259 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4260 always > 255 and <= 65535 and will always need 2 bytes. */
4261 if (max_char < 65535)
4262 new_max = 65535;
4263 break;
4264 case 4:
4265 /* Code point will be above 0xFFFF for sure in this case. */
4266 new_max = 65537;
4267 break;
4268 /* Internal error, this should be caught by the first if */
4269 case 1:
4270 default:
4271 assert(0 && "Impossible case in utf8_max_char_and_size");
4272 err = 1;
4273 }
4274 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004275 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004276 --n;
4277 /* Check if the follow up chars are all valid continuation bytes */
4278 if (n >= 1) {
4279 const unsigned char *cont;
4280 if ((p + n) >= end) {
4281 if (consumed == 0)
4282 /* incomplete data, non-incremental decoding */
4283 err = 1;
4284 break;
4285 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004286 for (cont = p + 1; cont <= (p + n); ++cont) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004287 if ((*cont & 0xc0) != 0x80) {
4288 err = 1;
4289 break;
4290 }
4291 }
4292 p += n;
4293 }
4294 else
4295 err = 1;
4296 max_char = new_max;
4297 }
4298 }
4299
4300 if (unicode_size)
4301 *unicode_size = char_count;
4302 if (has_errors)
4303 *has_errors = err;
4304 return max_char;
4305}
4306
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004307/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
4308 in case of errors. Implicit parameters: unicode, kind, data, has_errors,
4309 onError. Potential resizing overallocates, so the result needs to shrink
4310 at the end.
4311*/
4312#define WRITE_MAYBE_FAIL(index, value) \
4313 do { \
4314 if (has_errors) { \
4315 Py_ssize_t pos = index; \
4316 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4317 unicode_resize(&unicode, pos + pos/8) < 0) \
4318 goto onError; \
4319 if (unicode_putchar(&unicode, &pos, value) < 0) \
4320 goto onError; \
4321 } \
4322 else \
4323 PyUnicode_WRITE(kind, data, index, value); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004324 } while (0)
4325
Alexander Belopolsky40018472011-02-26 01:02:56 +00004326PyObject *
4327PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004328 Py_ssize_t size,
4329 const char *errors,
4330 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004331{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004332 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004333 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004334 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004335 Py_ssize_t startinpos;
4336 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004337 const char *e, *aligned_end;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004338 PyObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004339 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004340 PyObject *errorHandler = NULL;
4341 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004342 Py_UCS4 maxchar = 0;
4343 Py_ssize_t unicode_size;
4344 Py_ssize_t i;
4345 int kind;
4346 void *data;
4347 int has_errors;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004348
Walter Dörwald69652032004-09-07 20:24:22 +00004349 if (size == 0) {
4350 if (consumed)
4351 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004352 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004353 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004354 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4355 consumed, &has_errors);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004356 if (has_errors)
Victor Stinner62aa4d02011-11-09 00:03:45 +01004357 /* maxchar and size computation might be incorrect;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004358 code below widens and resizes as necessary. */
4359 unicode = PyUnicode_New(size, 127);
4360 else
Victor Stinner7931d9a2011-11-04 00:22:48 +01004361 unicode = PyUnicode_New(unicode_size, maxchar);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004362 if (!unicode)
4363 return NULL;
4364 /* When the string is ASCII only, just use memcpy and return.
4365 unicode_size may be != size if there is an incomplete UTF-8
4366 sequence at the end of the ASCII block. */
4367 if (!has_errors && maxchar < 128 && size == unicode_size) {
4368 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4369 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004370 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004371 kind = PyUnicode_KIND(unicode);
4372 data = PyUnicode_DATA(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004373 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004374 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004375 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004376 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004377
4378 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004379 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004380
4381 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004382 /* Fast path for runs of ASCII characters. Given that common UTF-8
4383 input will consist of an overwhelming majority of ASCII
4384 characters, we try to optimize for this case by checking
4385 as many characters as a C 'long' can contain.
4386 First, check if we can do an aligned read, as most CPUs have
4387 a penalty for unaligned reads.
4388 */
4389 if (!((size_t) s & LONG_PTR_MASK)) {
4390 /* Help register allocation */
4391 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004392 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004393 while (_s < aligned_end) {
4394 /* Read a whole long at a time (either 4 or 8 bytes),
4395 and do a fast unrolled copy if it only contains ASCII
4396 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004397 unsigned long value = *(unsigned long *) _s;
4398 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004399 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004400 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4401 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4402 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4403 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004404#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004405 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4406 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4407 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4408 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004409#endif
4410 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004411 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004412 }
4413 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004414 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004415 if (s == e)
4416 break;
4417 ch = (unsigned char)*s;
4418 }
4419 }
4420
4421 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004422 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004423 s++;
4424 continue;
4425 }
4426
4427 n = utf8_code_length[ch];
4428
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004429 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004430 if (consumed)
4431 break;
4432 else {
4433 errmsg = "unexpected end of data";
4434 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004435 endinpos = startinpos+1;
4436 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4437 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004438 goto utf8Error;
4439 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004440 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004441
4442 switch (n) {
4443
4444 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004445 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004446 startinpos = s-starts;
4447 endinpos = startinpos+1;
4448 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004449
4450 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004451 errmsg = "internal error";
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 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004457 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004458 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004459 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004460 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004461 goto utf8Error;
4462 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004463 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004464 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004465 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004466 break;
4467
4468 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004469 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4470 will result in surrogates in range d800-dfff. Surrogates are
4471 not valid UTF-8 so they are rejected.
4472 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4473 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004474 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004475 (s[2] & 0xc0) != 0x80 ||
4476 ((unsigned char)s[0] == 0xE0 &&
4477 (unsigned char)s[1] < 0xA0) ||
4478 ((unsigned char)s[0] == 0xED &&
4479 (unsigned char)s[1] > 0x9F)) {
4480 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004481 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004482 endinpos = startinpos + 1;
4483
4484 /* if s[1] first two bits are 1 and 0, then the invalid
4485 continuation byte is s[2], so increment endinpos by 1,
4486 if not, s[1] is invalid and endinpos doesn't need to
4487 be incremented. */
4488 if ((s[1] & 0xC0) == 0x80)
4489 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004490 goto utf8Error;
4491 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004492 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004493 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004494 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004495 break;
4496
4497 case 4:
4498 if ((s[1] & 0xc0) != 0x80 ||
4499 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004500 (s[3] & 0xc0) != 0x80 ||
4501 ((unsigned char)s[0] == 0xF0 &&
4502 (unsigned char)s[1] < 0x90) ||
4503 ((unsigned char)s[0] == 0xF4 &&
4504 (unsigned char)s[1] > 0x8F)) {
4505 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004506 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004507 endinpos = startinpos + 1;
4508 if ((s[1] & 0xC0) == 0x80) {
4509 endinpos++;
4510 if ((s[2] & 0xC0) == 0x80)
4511 endinpos++;
4512 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004513 goto utf8Error;
4514 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004515 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004516 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4517 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4518
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004519 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004520 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004521 }
4522 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004523 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004524
Benjamin Peterson29060642009-01-31 22:14:21 +00004525 utf8Error:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004526 if (!has_errors) {
4527 PyObject *tmp;
4528 Py_ssize_t k;
4529 /* We encountered some error that wasn't detected in the original scan,
4530 e.g. an encoded surrogate character. The original maxchar computation may
4531 have been incorrect, so redo it now. */
4532 for (k = 0, maxchar = 0; k < i; k++)
4533 maxchar = Py_MAX(maxchar, PyUnicode_READ(kind, data, k));
4534 tmp = PyUnicode_New(PyUnicode_GET_LENGTH(unicode), maxchar);
4535 if (tmp == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004536 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004537 PyUnicode_CopyCharacters(tmp, 0, unicode, 0, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004538 Py_DECREF(unicode);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004539 unicode = tmp;
4540 has_errors = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004541 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004542 if (unicode_decode_call_errorhandler(
4543 errors, &errorHandler,
4544 "utf8", errmsg,
4545 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004546 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004547 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004548 /* Update data because unicode_decode_call_errorhandler might have
4549 re-created or resized the unicode object. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004550 data = PyUnicode_DATA(unicode);
4551 kind = PyUnicode_KIND(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004552 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004553 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004554 /* Ensure the unicode_size calculation above was correct: */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004555 assert(has_errors || i == unicode_size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004556
Walter Dörwald69652032004-09-07 20:24:22 +00004557 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004558 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004559
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004560 /* Adjust length and ready string when it contained errors and
4561 is of the old resizable kind. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004562 if (has_errors) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004563 if (PyUnicode_Resize(&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004564 goto onError;
4565 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004566
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004567 Py_XDECREF(errorHandler);
4568 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004569 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004570 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004571
Benjamin Peterson29060642009-01-31 22:14:21 +00004572 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004573 Py_XDECREF(errorHandler);
4574 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004575 Py_DECREF(unicode);
4576 return NULL;
4577}
4578
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004579#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004580
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004581#ifdef __APPLE__
4582
4583/* Simplified UTF-8 decoder using surrogateescape error handler,
4584 used to decode the command line arguments on Mac OS X. */
4585
4586wchar_t*
4587_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4588{
4589 int n;
4590 const char *e;
4591 wchar_t *unicode, *p;
4592
4593 /* Note: size will always be longer than the resulting Unicode
4594 character count */
4595 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4596 PyErr_NoMemory();
4597 return NULL;
4598 }
4599 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4600 if (!unicode)
4601 return NULL;
4602
4603 /* Unpack UTF-8 encoded data */
4604 p = unicode;
4605 e = s + size;
4606 while (s < e) {
4607 Py_UCS4 ch = (unsigned char)*s;
4608
4609 if (ch < 0x80) {
4610 *p++ = (wchar_t)ch;
4611 s++;
4612 continue;
4613 }
4614
4615 n = utf8_code_length[ch];
4616 if (s + n > e) {
4617 goto surrogateescape;
4618 }
4619
4620 switch (n) {
4621 case 0:
4622 case 1:
4623 goto surrogateescape;
4624
4625 case 2:
4626 if ((s[1] & 0xc0) != 0x80)
4627 goto surrogateescape;
4628 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4629 assert ((ch > 0x007F) && (ch <= 0x07FF));
4630 *p++ = (wchar_t)ch;
4631 break;
4632
4633 case 3:
4634 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4635 will result in surrogates in range d800-dfff. Surrogates are
4636 not valid UTF-8 so they are rejected.
4637 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4638 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4639 if ((s[1] & 0xc0) != 0x80 ||
4640 (s[2] & 0xc0) != 0x80 ||
4641 ((unsigned char)s[0] == 0xE0 &&
4642 (unsigned char)s[1] < 0xA0) ||
4643 ((unsigned char)s[0] == 0xED &&
4644 (unsigned char)s[1] > 0x9F)) {
4645
4646 goto surrogateescape;
4647 }
4648 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4649 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004650 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004651 break;
4652
4653 case 4:
4654 if ((s[1] & 0xc0) != 0x80 ||
4655 (s[2] & 0xc0) != 0x80 ||
4656 (s[3] & 0xc0) != 0x80 ||
4657 ((unsigned char)s[0] == 0xF0 &&
4658 (unsigned char)s[1] < 0x90) ||
4659 ((unsigned char)s[0] == 0xF4 &&
4660 (unsigned char)s[1] > 0x8F)) {
4661 goto surrogateescape;
4662 }
4663 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4664 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4665 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4666
4667#if SIZEOF_WCHAR_T == 4
4668 *p++ = (wchar_t)ch;
4669#else
4670 /* compute and append the two surrogates: */
4671
4672 /* translate from 10000..10FFFF to 0..FFFF */
4673 ch -= 0x10000;
4674
4675 /* high surrogate = top 10 bits added to D800 */
4676 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4677
4678 /* low surrogate = bottom 10 bits added to DC00 */
4679 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4680#endif
4681 break;
4682 }
4683 s += n;
4684 continue;
4685
4686 surrogateescape:
4687 *p++ = 0xDC00 + ch;
4688 s++;
4689 }
4690 *p = L'\0';
4691 return unicode;
4692}
4693
4694#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004695
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004696/* Primary internal function which creates utf8 encoded bytes objects.
4697
4698 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004699 and allocate exactly as much space needed at the end. Else allocate the
4700 maximum possible needed (4 result bytes per Unicode character), and return
4701 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004702*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004703PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004704_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004705{
Tim Peters602f7402002-04-27 18:03:26 +00004706#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004707
Guido van Rossum98297ee2007-11-06 21:34:58 +00004708 Py_ssize_t i; /* index into s of next input byte */
4709 PyObject *result; /* result string object */
4710 char *p; /* next free byte in output buffer */
4711 Py_ssize_t nallocated; /* number of result bytes allocated */
4712 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004713 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004714 PyObject *errorHandler = NULL;
4715 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004716 int kind;
4717 void *data;
4718 Py_ssize_t size;
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004719 PyObject *rep = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004720
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004721 if (!PyUnicode_Check(unicode)) {
4722 PyErr_BadArgument();
4723 return NULL;
4724 }
4725
4726 if (PyUnicode_READY(unicode) == -1)
4727 return NULL;
4728
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004729 if (PyUnicode_UTF8(unicode))
4730 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4731 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004732
4733 kind = PyUnicode_KIND(unicode);
4734 data = PyUnicode_DATA(unicode);
4735 size = PyUnicode_GET_LENGTH(unicode);
4736
Tim Peters602f7402002-04-27 18:03:26 +00004737 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004738
Tim Peters602f7402002-04-27 18:03:26 +00004739 if (size <= MAX_SHORT_UNICHARS) {
4740 /* Write into the stack buffer; nallocated can't overflow.
4741 * At the end, we'll allocate exactly as much heap space as it
4742 * turns out we need.
4743 */
4744 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004745 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004746 p = stackbuf;
4747 }
4748 else {
4749 /* Overallocate on the heap, and give the excess back at the end. */
4750 nallocated = size * 4;
4751 if (nallocated / 4 != size) /* overflow! */
4752 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004753 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004754 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004755 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004756 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004757 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004758
Tim Peters602f7402002-04-27 18:03:26 +00004759 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004760 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004761
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004762 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004763 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004764 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004765
Guido van Rossumd57fd912000-03-10 22:53:23 +00004766 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004767 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004768 *p++ = (char)(0xc0 | (ch >> 6));
4769 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004770 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004771 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004772 Py_ssize_t repsize, k, startpos;
4773 startpos = i-1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004774 rep = unicode_encode_call_errorhandler(
4775 errors, &errorHandler, "utf-8", "surrogates not allowed",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004776 unicode, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004777 if (!rep)
4778 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004779
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004780 if (PyBytes_Check(rep))
4781 repsize = PyBytes_GET_SIZE(rep);
4782 else
4783 repsize = PyUnicode_GET_SIZE(rep);
4784
4785 if (repsize > 4) {
4786 Py_ssize_t offset;
4787
4788 if (result == NULL)
4789 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004790 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004791 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004792
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004793 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4794 /* integer overflow */
4795 PyErr_NoMemory();
4796 goto error;
4797 }
4798 nallocated += repsize - 4;
4799 if (result != NULL) {
4800 if (_PyBytes_Resize(&result, nallocated) < 0)
4801 goto error;
4802 } else {
4803 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004804 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004805 goto error;
4806 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4807 }
4808 p = PyBytes_AS_STRING(result) + offset;
4809 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004811 if (PyBytes_Check(rep)) {
4812 char *prep = PyBytes_AS_STRING(rep);
4813 for(k = repsize; k > 0; k--)
4814 *p++ = *prep++;
4815 } else /* rep is unicode */ {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004816 enum PyUnicode_Kind repkind;
4817 void *repdata;
4818
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004819 if (PyUnicode_READY(rep) < 0)
Victor Stinnera98b28c2011-11-10 20:21:49 +01004820 goto error;
Victor Stinnera98b28c2011-11-10 20:21:49 +01004821 repkind = PyUnicode_KIND(rep);
4822 repdata = PyUnicode_DATA(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004823
4824 for(k=0; k<repsize; k++) {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004825 Py_UCS4 c = PyUnicode_READ(repkind, repdata, k);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004826 if (0x80 <= c) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01004827 raise_encode_exception(&exc, "utf-8",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004828 unicode,
Martin v. Löwis9e816682011-11-02 12:45:42 +01004829 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004830 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004831 goto error;
4832 }
Victor Stinnera98b28c2011-11-10 20:21:49 +01004833 *p++ = (char)c;
Victor Stinner31be90b2010-04-22 19:38:16 +00004834 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004835 }
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004836 Py_CLEAR(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004837 } else if (ch < 0x10000) {
4838 *p++ = (char)(0xe0 | (ch >> 12));
4839 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4840 *p++ = (char)(0x80 | (ch & 0x3f));
4841 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004842 /* Encode UCS4 Unicode ordinals */
4843 *p++ = (char)(0xf0 | (ch >> 18));
4844 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4845 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4846 *p++ = (char)(0x80 | (ch & 0x3f));
4847 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004848 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004849
Guido van Rossum98297ee2007-11-06 21:34:58 +00004850 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004851 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004852 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004853 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004854 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004855 }
4856 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004857 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004858 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004859 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004860 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004861 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004862
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004863 Py_XDECREF(errorHandler);
4864 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004865 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004866 error:
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004867 Py_XDECREF(rep);
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004868 Py_XDECREF(errorHandler);
4869 Py_XDECREF(exc);
4870 Py_XDECREF(result);
4871 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004872
Tim Peters602f7402002-04-27 18:03:26 +00004873#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004874}
4875
Alexander Belopolsky40018472011-02-26 01:02:56 +00004876PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004877PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4878 Py_ssize_t size,
4879 const char *errors)
4880{
4881 PyObject *v, *unicode;
4882
4883 unicode = PyUnicode_FromUnicode(s, size);
4884 if (unicode == NULL)
4885 return NULL;
4886 v = _PyUnicode_AsUTF8String(unicode, errors);
4887 Py_DECREF(unicode);
4888 return v;
4889}
4890
4891PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004892PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004893{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004894 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004895}
4896
Walter Dörwald41980ca2007-08-16 21:55:45 +00004897/* --- UTF-32 Codec ------------------------------------------------------- */
4898
4899PyObject *
4900PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004901 Py_ssize_t size,
4902 const char *errors,
4903 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004904{
4905 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4906}
4907
4908PyObject *
4909PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004910 Py_ssize_t size,
4911 const char *errors,
4912 int *byteorder,
4913 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004914{
4915 const char *starts = s;
4916 Py_ssize_t startinpos;
4917 Py_ssize_t endinpos;
4918 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004919 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004920 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004921 int bo = 0; /* assume native ordering by default */
4922 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004923 /* Offsets from q for retrieving bytes in the right order. */
4924#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4925 int iorder[] = {0, 1, 2, 3};
4926#else
4927 int iorder[] = {3, 2, 1, 0};
4928#endif
4929 PyObject *errorHandler = NULL;
4930 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004931
Walter Dörwald41980ca2007-08-16 21:55:45 +00004932 q = (unsigned char *)s;
4933 e = q + size;
4934
4935 if (byteorder)
4936 bo = *byteorder;
4937
4938 /* Check for BOM marks (U+FEFF) in the input and adjust current
4939 byte order setting accordingly. In native mode, the leading BOM
4940 mark is skipped, in all other modes, it is copied to the output
4941 stream as-is (giving a ZWNBSP character). */
4942 if (bo == 0) {
4943 if (size >= 4) {
4944 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004945 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004946#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004947 if (bom == 0x0000FEFF) {
4948 q += 4;
4949 bo = -1;
4950 }
4951 else if (bom == 0xFFFE0000) {
4952 q += 4;
4953 bo = 1;
4954 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004955#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004956 if (bom == 0x0000FEFF) {
4957 q += 4;
4958 bo = 1;
4959 }
4960 else if (bom == 0xFFFE0000) {
4961 q += 4;
4962 bo = -1;
4963 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004964#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004965 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004966 }
4967
4968 if (bo == -1) {
4969 /* force LE */
4970 iorder[0] = 0;
4971 iorder[1] = 1;
4972 iorder[2] = 2;
4973 iorder[3] = 3;
4974 }
4975 else if (bo == 1) {
4976 /* force BE */
4977 iorder[0] = 3;
4978 iorder[1] = 2;
4979 iorder[2] = 1;
4980 iorder[3] = 0;
4981 }
4982
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004983 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004984 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004985 if (!unicode)
4986 return NULL;
4987 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01004988 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004989 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004990
Walter Dörwald41980ca2007-08-16 21:55:45 +00004991 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004992 Py_UCS4 ch;
4993 /* remaining bytes at the end? (size should be divisible by 4) */
4994 if (e-q<4) {
4995 if (consumed)
4996 break;
4997 errmsg = "truncated data";
4998 startinpos = ((const char *)q)-starts;
4999 endinpos = ((const char *)e)-starts;
5000 goto utf32Error;
5001 /* The remaining input chars are ignored if the callback
5002 chooses to skip the input */
5003 }
5004 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5005 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005006
Benjamin Peterson29060642009-01-31 22:14:21 +00005007 if (ch >= 0x110000)
5008 {
5009 errmsg = "codepoint not in range(0x110000)";
5010 startinpos = ((const char *)q)-starts;
5011 endinpos = startinpos+4;
5012 goto utf32Error;
5013 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005014 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5015 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005016 q += 4;
5017 continue;
5018 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005019 if (unicode_decode_call_errorhandler(
5020 errors, &errorHandler,
5021 "utf32", errmsg,
5022 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005023 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005024 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005025 }
5026
5027 if (byteorder)
5028 *byteorder = bo;
5029
5030 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005031 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005032
5033 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005034 if (PyUnicode_Resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005035 goto onError;
5036
5037 Py_XDECREF(errorHandler);
5038 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005039#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005040 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005041 Py_DECREF(unicode);
5042 return NULL;
5043 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005044#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005045 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005046 return unicode;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005047
Benjamin Peterson29060642009-01-31 22:14:21 +00005048 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005049 Py_DECREF(unicode);
5050 Py_XDECREF(errorHandler);
5051 Py_XDECREF(exc);
5052 return NULL;
5053}
5054
5055PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005056_PyUnicode_EncodeUTF32(PyObject *str,
5057 const char *errors,
5058 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005059{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005060 int kind;
5061 void *data;
5062 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005063 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005064 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005065 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005066 /* Offsets from p for storing byte pairs in the right order. */
5067#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5068 int iorder[] = {0, 1, 2, 3};
5069#else
5070 int iorder[] = {3, 2, 1, 0};
5071#endif
5072
Benjamin Peterson29060642009-01-31 22:14:21 +00005073#define STORECHAR(CH) \
5074 do { \
5075 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5076 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5077 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5078 p[iorder[0]] = (CH) & 0xff; \
5079 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005080 } while(0)
5081
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005082 if (!PyUnicode_Check(str)) {
5083 PyErr_BadArgument();
5084 return NULL;
5085 }
5086 if (PyUnicode_READY(str) < 0)
5087 return NULL;
5088 kind = PyUnicode_KIND(str);
5089 data = PyUnicode_DATA(str);
5090 len = PyUnicode_GET_LENGTH(str);
5091
5092 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005093 bytesize = nsize * 4;
5094 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005095 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005096 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005097 if (v == NULL)
5098 return NULL;
5099
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005100 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005101 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005102 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005103 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005104 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005105
5106 if (byteorder == -1) {
5107 /* force LE */
5108 iorder[0] = 0;
5109 iorder[1] = 1;
5110 iorder[2] = 2;
5111 iorder[3] = 3;
5112 }
5113 else if (byteorder == 1) {
5114 /* force BE */
5115 iorder[0] = 3;
5116 iorder[1] = 2;
5117 iorder[2] = 1;
5118 iorder[3] = 0;
5119 }
5120
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005121 for (i = 0; i < len; i++)
5122 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005123
5124 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005125 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005126#undef STORECHAR
5127}
5128
Alexander Belopolsky40018472011-02-26 01:02:56 +00005129PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005130PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5131 Py_ssize_t size,
5132 const char *errors,
5133 int byteorder)
5134{
5135 PyObject *result;
5136 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5137 if (tmp == NULL)
5138 return NULL;
5139 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5140 Py_DECREF(tmp);
5141 return result;
5142}
5143
5144PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005145PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005146{
Victor Stinner1f795172011-11-17 00:45:54 +01005147 const Py_UNICODE *wstr;
5148 Py_ssize_t wlen;
5149 wstr = PyUnicode_AsUnicodeAndSize(unicode, &wlen);
5150 if (wstr == NULL)
5151 return NULL;
5152 return PyUnicode_EncodeUTF32(wstr, wlen, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005153}
5154
Guido van Rossumd57fd912000-03-10 22:53:23 +00005155/* --- UTF-16 Codec ------------------------------------------------------- */
5156
Tim Peters772747b2001-08-09 22:21:55 +00005157PyObject *
5158PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005159 Py_ssize_t size,
5160 const char *errors,
5161 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005162{
Walter Dörwald69652032004-09-07 20:24:22 +00005163 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5164}
5165
Antoine Pitrouab868312009-01-10 15:40:25 +00005166/* Two masks for fast checking of whether a C 'long' may contain
5167 UTF16-encoded surrogate characters. This is an efficient heuristic,
5168 assuming that non-surrogate characters with a code point >= 0x8000 are
5169 rare in most input.
5170 FAST_CHAR_MASK is used when the input is in native byte ordering,
5171 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005172*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005173#if (SIZEOF_LONG == 8)
5174# define FAST_CHAR_MASK 0x8000800080008000L
5175# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5176#elif (SIZEOF_LONG == 4)
5177# define FAST_CHAR_MASK 0x80008000L
5178# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5179#else
5180# error C 'long' size should be either 4 or 8!
5181#endif
5182
Walter Dörwald69652032004-09-07 20:24:22 +00005183PyObject *
5184PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005185 Py_ssize_t size,
5186 const char *errors,
5187 int *byteorder,
5188 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005189{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005190 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005191 Py_ssize_t startinpos;
5192 Py_ssize_t endinpos;
5193 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005194 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005195 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005196 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005197 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005198 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005199 /* Offsets from q for retrieving byte pairs in the right order. */
5200#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5201 int ihi = 1, ilo = 0;
5202#else
5203 int ihi = 0, ilo = 1;
5204#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005205 PyObject *errorHandler = NULL;
5206 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005207
5208 /* Note: size will always be longer than the resulting Unicode
5209 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005210 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005211 if (!unicode)
5212 return NULL;
5213 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005214 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005215 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005216
Tim Peters772747b2001-08-09 22:21:55 +00005217 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005218 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005219
5220 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005221 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005222
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005223 /* Check for BOM marks (U+FEFF) in the input and adjust current
5224 byte order setting accordingly. In native mode, the leading BOM
5225 mark is skipped, in all other modes, it is copied to the output
5226 stream as-is (giving a ZWNBSP character). */
5227 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005228 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005229 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005230#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005231 if (bom == 0xFEFF) {
5232 q += 2;
5233 bo = -1;
5234 }
5235 else if (bom == 0xFFFE) {
5236 q += 2;
5237 bo = 1;
5238 }
Tim Petersced69f82003-09-16 20:30:58 +00005239#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005240 if (bom == 0xFEFF) {
5241 q += 2;
5242 bo = 1;
5243 }
5244 else if (bom == 0xFFFE) {
5245 q += 2;
5246 bo = -1;
5247 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005248#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005249 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005250 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005251
Tim Peters772747b2001-08-09 22:21:55 +00005252 if (bo == -1) {
5253 /* force LE */
5254 ihi = 1;
5255 ilo = 0;
5256 }
5257 else if (bo == 1) {
5258 /* force BE */
5259 ihi = 0;
5260 ilo = 1;
5261 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005262#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5263 native_ordering = ilo < ihi;
5264#else
5265 native_ordering = ilo > ihi;
5266#endif
Tim Peters772747b2001-08-09 22:21:55 +00005267
Antoine Pitrouab868312009-01-10 15:40:25 +00005268 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005269 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005270 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005271 /* First check for possible aligned read of a C 'long'. Unaligned
5272 reads are more expensive, better to defer to another iteration. */
5273 if (!((size_t) q & LONG_PTR_MASK)) {
5274 /* Fast path for runs of non-surrogate chars. */
5275 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005276 int kind = PyUnicode_KIND(unicode);
5277 void *data = PyUnicode_DATA(unicode);
5278 while (_q < aligned_end) {
5279 unsigned long block = * (unsigned long *) _q;
5280 unsigned short *pblock = (unsigned short*)&block;
5281 Py_UCS4 maxch;
5282 if (native_ordering) {
5283 /* Can use buffer directly */
5284 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005285 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005286 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005287 else {
5288 /* Need to byte-swap */
5289 unsigned char *_p = (unsigned char*)pblock;
5290 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005291 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005292 _p[0] = _q[1];
5293 _p[1] = _q[0];
5294 _p[2] = _q[3];
5295 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005296#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005297 _p[4] = _q[5];
5298 _p[5] = _q[4];
5299 _p[6] = _q[7];
5300 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005301#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005302 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005303 maxch = Py_MAX(pblock[0], pblock[1]);
5304#if SIZEOF_LONG == 8
5305 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5306#endif
5307 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5308 if (unicode_widen(&unicode, maxch) < 0)
5309 goto onError;
5310 kind = PyUnicode_KIND(unicode);
5311 data = PyUnicode_DATA(unicode);
5312 }
5313 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5314 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5315#if SIZEOF_LONG == 8
5316 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5317 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5318#endif
5319 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005320 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005321 q = _q;
5322 if (q >= e)
5323 break;
5324 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005325 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005326
Benjamin Peterson14339b62009-01-31 16:36:08 +00005327 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005328
5329 if (ch < 0xD800 || ch > 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005330 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5331 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005332 continue;
5333 }
5334
5335 /* UTF-16 code pair: */
5336 if (q > e) {
5337 errmsg = "unexpected end of data";
5338 startinpos = (((const char *)q) - 2) - starts;
5339 endinpos = ((const char *)e) + 1 - starts;
5340 goto utf16Error;
5341 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005342 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5343 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005344 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005345 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005346 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005347 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005348 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005349 continue;
5350 }
5351 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005352 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005353 startinpos = (((const char *)q)-4)-starts;
5354 endinpos = startinpos+2;
5355 goto utf16Error;
5356 }
5357
Benjamin Peterson14339b62009-01-31 16:36:08 +00005358 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005359 errmsg = "illegal encoding";
5360 startinpos = (((const char *)q)-2)-starts;
5361 endinpos = startinpos+2;
5362 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005363
Benjamin Peterson29060642009-01-31 22:14:21 +00005364 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005365 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005366 errors,
5367 &errorHandler,
5368 "utf16", errmsg,
5369 &starts,
5370 (const char **)&e,
5371 &startinpos,
5372 &endinpos,
5373 &exc,
5374 (const char **)&q,
5375 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005376 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005377 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005378 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005379 /* remaining byte at the end? (size should be even) */
5380 if (e == q) {
5381 if (!consumed) {
5382 errmsg = "truncated data";
5383 startinpos = ((const char *)q) - starts;
5384 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005385 if (unicode_decode_call_errorhandler(
5386 errors,
5387 &errorHandler,
5388 "utf16", errmsg,
5389 &starts,
5390 (const char **)&e,
5391 &startinpos,
5392 &endinpos,
5393 &exc,
5394 (const char **)&q,
5395 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005396 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005397 goto onError;
5398 /* The remaining input chars are ignored if the callback
5399 chooses to skip the input */
5400 }
5401 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005402
5403 if (byteorder)
5404 *byteorder = bo;
5405
Walter Dörwald69652032004-09-07 20:24:22 +00005406 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005407 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005408
Guido van Rossumd57fd912000-03-10 22:53:23 +00005409 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005410 if (PyUnicode_Resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005411 goto onError;
5412
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005413 Py_XDECREF(errorHandler);
5414 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005415 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005416 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005417
Benjamin Peterson29060642009-01-31 22:14:21 +00005418 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005419 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005420 Py_XDECREF(errorHandler);
5421 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005422 return NULL;
5423}
5424
Antoine Pitrouab868312009-01-10 15:40:25 +00005425#undef FAST_CHAR_MASK
5426#undef SWAPPED_FAST_CHAR_MASK
5427
Tim Peters772747b2001-08-09 22:21:55 +00005428PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005429_PyUnicode_EncodeUTF16(PyObject *str,
5430 const char *errors,
5431 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005432{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005433 int kind;
5434 void *data;
5435 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005436 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005437 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005438 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005439 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005440 /* Offsets from p for storing byte pairs in the right order. */
5441#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5442 int ihi = 1, ilo = 0;
5443#else
5444 int ihi = 0, ilo = 1;
5445#endif
5446
Benjamin Peterson29060642009-01-31 22:14:21 +00005447#define STORECHAR(CH) \
5448 do { \
5449 p[ihi] = ((CH) >> 8) & 0xff; \
5450 p[ilo] = (CH) & 0xff; \
5451 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005452 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005453
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005454 if (!PyUnicode_Check(str)) {
5455 PyErr_BadArgument();
5456 return NULL;
5457 }
5458 if (PyUnicode_READY(str) < 0)
5459 return NULL;
5460 kind = PyUnicode_KIND(str);
5461 data = PyUnicode_DATA(str);
5462 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005463
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005464 pairs = 0;
5465 if (kind == PyUnicode_4BYTE_KIND)
5466 for (i = 0; i < len; i++)
5467 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5468 pairs++;
5469 /* 2 * (len + pairs + (byteorder == 0)) */
5470 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005471 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005472 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005473 bytesize = nsize * 2;
5474 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005475 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005476 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005477 if (v == NULL)
5478 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005479
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005480 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005481 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005482 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005483 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005484 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005485
5486 if (byteorder == -1) {
5487 /* force LE */
5488 ihi = 1;
5489 ilo = 0;
5490 }
5491 else if (byteorder == 1) {
5492 /* force BE */
5493 ihi = 0;
5494 ilo = 1;
5495 }
5496
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005497 for (i = 0; i < len; i++) {
5498 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5499 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005500 if (ch >= 0x10000) {
5501 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5502 ch = 0xD800 | ((ch-0x10000) >> 10);
5503 }
Tim Peters772747b2001-08-09 22:21:55 +00005504 STORECHAR(ch);
5505 if (ch2)
5506 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005507 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005508
5509 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005510 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005511#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005512}
5513
Alexander Belopolsky40018472011-02-26 01:02:56 +00005514PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005515PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5516 Py_ssize_t size,
5517 const char *errors,
5518 int byteorder)
5519{
5520 PyObject *result;
5521 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5522 if (tmp == NULL)
5523 return NULL;
5524 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5525 Py_DECREF(tmp);
5526 return result;
5527}
5528
5529PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005530PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005531{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005532 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005533}
5534
5535/* --- Unicode Escape Codec ----------------------------------------------- */
5536
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005537/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5538 if all the escapes in the string make it still a valid ASCII string.
5539 Returns -1 if any escapes were found which cause the string to
5540 pop out of ASCII range. Otherwise returns the length of the
5541 required buffer to hold the string.
5542 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005543static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005544length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5545{
5546 const unsigned char *p = (const unsigned char *)s;
5547 const unsigned char *end = p + size;
5548 Py_ssize_t length = 0;
5549
5550 if (size < 0)
5551 return -1;
5552
5553 for (; p < end; ++p) {
5554 if (*p > 127) {
5555 /* Non-ASCII */
5556 return -1;
5557 }
5558 else if (*p != '\\') {
5559 /* Normal character */
5560 ++length;
5561 }
5562 else {
5563 /* Backslash-escape, check next char */
5564 ++p;
5565 /* Escape sequence reaches till end of string or
5566 non-ASCII follow-up. */
5567 if (p >= end || *p > 127)
5568 return -1;
5569 switch (*p) {
5570 case '\n':
5571 /* backslash + \n result in zero characters */
5572 break;
5573 case '\\': case '\'': case '\"':
5574 case 'b': case 'f': case 't':
5575 case 'n': case 'r': case 'v': case 'a':
5576 ++length;
5577 break;
5578 case '0': case '1': case '2': case '3':
5579 case '4': case '5': case '6': case '7':
5580 case 'x': case 'u': case 'U': case 'N':
5581 /* these do not guarantee ASCII characters */
5582 return -1;
5583 default:
5584 /* count the backslash + the other character */
5585 length += 2;
5586 }
5587 }
5588 }
5589 return length;
5590}
5591
5592/* Similar to PyUnicode_WRITE but either write into wstr field
5593 or treat string as ASCII. */
5594#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5595 do { \
5596 if ((kind) != PyUnicode_WCHAR_KIND) \
5597 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5598 else \
5599 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5600 } while (0)
5601
5602#define WRITE_WSTR(buf, index, value) \
5603 assert(kind == PyUnicode_WCHAR_KIND), \
5604 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5605
5606
Fredrik Lundh06d12682001-01-24 07:59:11 +00005607static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005608
Alexander Belopolsky40018472011-02-26 01:02:56 +00005609PyObject *
5610PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005611 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005612 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005613{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005614 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005615 Py_ssize_t startinpos;
5616 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005617 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005618 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005619 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005620 char* message;
5621 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005622 PyObject *errorHandler = NULL;
5623 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005624 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005625 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005626
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005627 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005628
5629 /* After length_of_escaped_ascii_string() there are two alternatives,
5630 either the string is pure ASCII with named escapes like \n, etc.
5631 and we determined it's exact size (common case)
5632 or it contains \x, \u, ... escape sequences. then we create a
5633 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005634 if (len >= 0) {
5635 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005636 if (!v)
5637 goto onError;
5638 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005639 }
5640 else {
5641 /* Escaped strings will always be longer than the resulting
5642 Unicode string, so we start with size here and then reduce the
5643 length after conversion to the true value.
5644 (but if the error callback returns a long replacement string
5645 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005646 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005647 if (!v)
5648 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005649 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005650 }
5651
Guido van Rossumd57fd912000-03-10 22:53:23 +00005652 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005653 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005654 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005655 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005656
Guido van Rossumd57fd912000-03-10 22:53:23 +00005657 while (s < end) {
5658 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005659 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005660 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005661
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005662 /* The only case in which i == ascii_length is a backslash
5663 followed by a newline. */
5664 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005665
Guido van Rossumd57fd912000-03-10 22:53:23 +00005666 /* Non-escape characters are interpreted as Unicode ordinals */
5667 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005668 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5669 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005670 continue;
5671 }
5672
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005673 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005674 /* \ - Escapes */
5675 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005676 c = *s++;
5677 if (s > end)
5678 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005679
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005680 /* The only case in which i == ascii_length is a backslash
5681 followed by a newline. */
5682 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005683
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005684 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005685
Benjamin Peterson29060642009-01-31 22:14:21 +00005686 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005687#define WRITECHAR(ch) \
5688 do { \
5689 if (unicode_putchar(&v, &i, ch) < 0) \
5690 goto onError; \
5691 }while(0)
5692
Guido van Rossumd57fd912000-03-10 22:53:23 +00005693 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005694 case '\\': WRITECHAR('\\'); break;
5695 case '\'': WRITECHAR('\''); break;
5696 case '\"': WRITECHAR('\"'); break;
5697 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005698 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005699 case 'f': WRITECHAR('\014'); break;
5700 case 't': WRITECHAR('\t'); break;
5701 case 'n': WRITECHAR('\n'); break;
5702 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005703 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005704 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005705 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005706 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005707
Benjamin Peterson29060642009-01-31 22:14:21 +00005708 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005709 case '0': case '1': case '2': case '3':
5710 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005711 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005712 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005713 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005714 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005715 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005716 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005717 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005718 break;
5719
Benjamin Peterson29060642009-01-31 22:14:21 +00005720 /* hex escapes */
5721 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005722 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005723 digits = 2;
5724 message = "truncated \\xXX escape";
5725 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005726
Benjamin Peterson29060642009-01-31 22:14:21 +00005727 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005728 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005729 digits = 4;
5730 message = "truncated \\uXXXX escape";
5731 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732
Benjamin Peterson29060642009-01-31 22:14:21 +00005733 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005734 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005735 digits = 8;
5736 message = "truncated \\UXXXXXXXX escape";
5737 hexescape:
5738 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005739 if (s+digits>end) {
5740 endinpos = size;
5741 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005742 errors, &errorHandler,
5743 "unicodeescape", "end of string in escape sequence",
5744 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005745 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005746 goto onError;
5747 goto nextByte;
5748 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005749 for (j = 0; j < digits; ++j) {
5750 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005751 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005752 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005753 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005754 errors, &errorHandler,
5755 "unicodeescape", message,
5756 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005757 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005758 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005759 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005760 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005761 }
5762 chr = (chr<<4) & ~0xF;
5763 if (c >= '0' && c <= '9')
5764 chr += c - '0';
5765 else if (c >= 'a' && c <= 'f')
5766 chr += 10 + c - 'a';
5767 else
5768 chr += 10 + c - 'A';
5769 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005770 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005771 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005772 /* _decoding_error will have already written into the
5773 target buffer. */
5774 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005775 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005776 /* when we get here, chr is a 32-bit unicode character */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005777 if (chr <= 0x10ffff) {
5778 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005779 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005780 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005781 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005782 errors, &errorHandler,
5783 "unicodeescape", "illegal Unicode character",
5784 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005785 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005786 goto onError;
5787 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005788 break;
5789
Benjamin Peterson29060642009-01-31 22:14:21 +00005790 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005791 case 'N':
5792 message = "malformed \\N character escape";
5793 if (ucnhash_CAPI == NULL) {
5794 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005795 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5796 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005797 if (ucnhash_CAPI == NULL)
5798 goto ucnhashError;
5799 }
5800 if (*s == '{') {
5801 const char *start = s+1;
5802 /* look for the closing brace */
5803 while (*s != '}' && s < end)
5804 s++;
5805 if (s > start && s < end && *s == '}') {
5806 /* found a name. look it up in the unicode database */
5807 message = "unknown Unicode character name";
5808 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005809 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005810 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005811 goto store;
5812 }
5813 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005814 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005815 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005816 errors, &errorHandler,
5817 "unicodeescape", message,
5818 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005819 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005820 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005821 break;
5822
5823 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005824 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005825 message = "\\ at end of string";
5826 s--;
5827 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005828 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005829 errors, &errorHandler,
5830 "unicodeescape", message,
5831 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005832 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005833 goto onError;
5834 }
5835 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005836 WRITECHAR('\\');
5837 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005838 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005839 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005840 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005841 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005842 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005843 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005844#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005845
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005846 if (PyUnicode_Resize(&v, i) < 0)
5847 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005848 Py_XDECREF(errorHandler);
5849 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005850#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005851 if (_PyUnicode_READY_REPLACE(&v)) {
5852 Py_DECREF(v);
5853 return NULL;
5854 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005855#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005856 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005857 return v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005858
Benjamin Peterson29060642009-01-31 22:14:21 +00005859 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005860 PyErr_SetString(
5861 PyExc_UnicodeError,
5862 "\\N escapes not supported (can't load unicodedata module)"
5863 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005864 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005865 Py_XDECREF(errorHandler);
5866 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005867 return NULL;
5868
Benjamin Peterson29060642009-01-31 22:14:21 +00005869 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005870 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005871 Py_XDECREF(errorHandler);
5872 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005873 return NULL;
5874}
5875
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005876#undef WRITE_ASCII_OR_WSTR
5877#undef WRITE_WSTR
5878
Guido van Rossumd57fd912000-03-10 22:53:23 +00005879/* Return a Unicode-Escape string version of the Unicode object.
5880
5881 If quotes is true, the string is enclosed in u"" or u'' quotes as
5882 appropriate.
5883
5884*/
5885
Alexander Belopolsky40018472011-02-26 01:02:56 +00005886PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005887PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005888{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005889 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005890 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005891 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005892 int kind;
5893 void *data;
5894 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005895
Thomas Wouters89f507f2006-12-13 04:49:30 +00005896 /* Initial allocation is based on the longest-possible unichr
5897 escape.
5898
5899 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5900 unichr, so in this case it's the longest unichr escape. In
5901 narrow (UTF-16) builds this is five chars per source unichr
5902 since there are two unichrs in the surrogate pair, so in narrow
5903 (UTF-16) builds it's not the longest unichr escape.
5904
5905 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5906 so in the narrow (UTF-16) build case it's the longest unichr
5907 escape.
5908 */
5909
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005910 if (!PyUnicode_Check(unicode)) {
5911 PyErr_BadArgument();
5912 return NULL;
5913 }
5914 if (PyUnicode_READY(unicode) < 0)
5915 return NULL;
5916 len = PyUnicode_GET_LENGTH(unicode);
5917 kind = PyUnicode_KIND(unicode);
5918 data = PyUnicode_DATA(unicode);
5919 switch(kind) {
5920 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5921 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5922 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5923 }
5924
5925 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005926 return PyBytes_FromStringAndSize(NULL, 0);
5927
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005928 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005929 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005930
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005931 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005932 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005933 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005934 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935 if (repr == NULL)
5936 return NULL;
5937
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005938 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005939
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005940 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005941 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005942
Walter Dörwald79e913e2007-05-12 11:08:06 +00005943 /* Escape backslashes */
5944 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005945 *p++ = '\\';
5946 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005947 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005948 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005949
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005950 /* Map 21-bit characters to '\U00xxxxxx' */
5951 else if (ch >= 0x10000) {
5952 *p++ = '\\';
5953 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005954 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5955 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5956 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5957 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5958 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5959 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5960 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5961 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005962 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005963 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005964
Guido van Rossumd57fd912000-03-10 22:53:23 +00005965 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005966 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005967 *p++ = '\\';
5968 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005969 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5970 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5971 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5972 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005973 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005974
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005975 /* Map special whitespace to '\t', \n', '\r' */
5976 else if (ch == '\t') {
5977 *p++ = '\\';
5978 *p++ = 't';
5979 }
5980 else if (ch == '\n') {
5981 *p++ = '\\';
5982 *p++ = 'n';
5983 }
5984 else if (ch == '\r') {
5985 *p++ = '\\';
5986 *p++ = 'r';
5987 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005988
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005989 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005990 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005991 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005992 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005993 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5994 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005995 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005996
Guido van Rossumd57fd912000-03-10 22:53:23 +00005997 /* Copy everything else as-is */
5998 else
5999 *p++ = (char) ch;
6000 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006001
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006002 assert(p - PyBytes_AS_STRING(repr) > 0);
6003 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6004 return NULL;
6005 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006006}
6007
Alexander Belopolsky40018472011-02-26 01:02:56 +00006008PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006009PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6010 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006011{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006012 PyObject *result;
6013 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6014 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006015 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006016 result = PyUnicode_AsUnicodeEscapeString(tmp);
6017 Py_DECREF(tmp);
6018 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006019}
6020
6021/* --- Raw Unicode Escape Codec ------------------------------------------- */
6022
Alexander Belopolsky40018472011-02-26 01:02:56 +00006023PyObject *
6024PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006025 Py_ssize_t size,
6026 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006027{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006028 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006029 Py_ssize_t startinpos;
6030 Py_ssize_t endinpos;
6031 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006032 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006033 const char *end;
6034 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006035 PyObject *errorHandler = NULL;
6036 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006037
Guido van Rossumd57fd912000-03-10 22:53:23 +00006038 /* Escaped strings will always be longer than the resulting
6039 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006040 length after conversion to the true value. (But decoding error
6041 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006042 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006044 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006045 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006046 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006047 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006048 end = s + size;
6049 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006050 unsigned char c;
6051 Py_UCS4 x;
6052 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006053 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006054
Benjamin Peterson29060642009-01-31 22:14:21 +00006055 /* Non-escape characters are interpreted as Unicode ordinals */
6056 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006057 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6058 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006059 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006060 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006061 startinpos = s-starts;
6062
6063 /* \u-escapes are only interpreted iff the number of leading
6064 backslashes if odd */
6065 bs = s;
6066 for (;s < end;) {
6067 if (*s != '\\')
6068 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006069 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6070 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006071 }
6072 if (((s - bs) & 1) == 0 ||
6073 s >= end ||
6074 (*s != 'u' && *s != 'U')) {
6075 continue;
6076 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006077 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006078 count = *s=='u' ? 4 : 8;
6079 s++;
6080
6081 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006082 for (x = 0, i = 0; i < count; ++i, ++s) {
6083 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006084 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006085 endinpos = s-starts;
6086 if (unicode_decode_call_errorhandler(
6087 errors, &errorHandler,
6088 "rawunicodeescape", "truncated \\uXXXX",
6089 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006090 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006091 goto onError;
6092 goto nextByte;
6093 }
6094 x = (x<<4) & ~0xF;
6095 if (c >= '0' && c <= '9')
6096 x += c - '0';
6097 else if (c >= 'a' && c <= 'f')
6098 x += 10 + c - 'a';
6099 else
6100 x += 10 + c - 'A';
6101 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006102 if (x <= 0x10ffff) {
6103 if (unicode_putchar(&v, &outpos, x) < 0)
6104 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006105 } else {
6106 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006107 if (unicode_decode_call_errorhandler(
6108 errors, &errorHandler,
6109 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006110 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006111 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006112 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006113 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006114 nextByte:
6115 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006116 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006117 if (PyUnicode_Resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006118 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006119 Py_XDECREF(errorHandler);
6120 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006121 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006122 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006123
Benjamin Peterson29060642009-01-31 22:14:21 +00006124 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006125 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006126 Py_XDECREF(errorHandler);
6127 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006128 return NULL;
6129}
6130
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006131
Alexander Belopolsky40018472011-02-26 01:02:56 +00006132PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006133PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006134{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006135 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006136 char *p;
6137 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006138 Py_ssize_t expandsize, pos;
6139 int kind;
6140 void *data;
6141 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006142
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006143 if (!PyUnicode_Check(unicode)) {
6144 PyErr_BadArgument();
6145 return NULL;
6146 }
6147 if (PyUnicode_READY(unicode) < 0)
6148 return NULL;
6149 kind = PyUnicode_KIND(unicode);
6150 data = PyUnicode_DATA(unicode);
6151 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006152
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006153 switch(kind) {
6154 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6155 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6156 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6157 }
Victor Stinner0e368262011-11-10 20:12:49 +01006158
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006159 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006160 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006161
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006162 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006163 if (repr == NULL)
6164 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006165 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006166 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006167
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006168 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006169 for (pos = 0; pos < len; pos++) {
6170 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006171 /* Map 32-bit characters to '\Uxxxxxxxx' */
6172 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006173 *p++ = '\\';
6174 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006175 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6176 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6177 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6178 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6179 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6180 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6181 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6182 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006183 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006184 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006185 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006186 *p++ = '\\';
6187 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006188 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6189 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6190 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6191 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006192 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006193 /* Copy everything else as-is */
6194 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006195 *p++ = (char) ch;
6196 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006197
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006198 assert(p > q);
6199 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006200 return NULL;
6201 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006202}
6203
Alexander Belopolsky40018472011-02-26 01:02:56 +00006204PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006205PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6206 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006207{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006208 PyObject *result;
6209 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6210 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006211 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006212 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6213 Py_DECREF(tmp);
6214 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006215}
6216
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006217/* --- Unicode Internal Codec ------------------------------------------- */
6218
Alexander Belopolsky40018472011-02-26 01:02:56 +00006219PyObject *
6220_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006221 Py_ssize_t size,
6222 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006223{
6224 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006225 Py_ssize_t startinpos;
6226 Py_ssize_t endinpos;
6227 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006228 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006229 const char *end;
6230 const char *reason;
6231 PyObject *errorHandler = NULL;
6232 PyObject *exc = NULL;
6233
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006234 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006235 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006236 1))
6237 return NULL;
6238
Thomas Wouters89f507f2006-12-13 04:49:30 +00006239 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006240 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006241 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006242 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006243 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006244 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006245 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006246 end = s + size;
6247
6248 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006249 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006250 Py_UCS4 ch;
6251 /* We copy the raw representation one byte at a time because the
6252 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006253 ((char *) &uch)[0] = s[0];
6254 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006255#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006256 ((char *) &uch)[2] = s[2];
6257 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006258#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006259 ch = uch;
6260
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006261 /* We have to sanity check the raw data, otherwise doom looms for
6262 some malformed UCS-4 data. */
6263 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006264#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006265 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006266#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006267 end-s < Py_UNICODE_SIZE
6268 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006269 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006270 startinpos = s - starts;
6271 if (end-s < Py_UNICODE_SIZE) {
6272 endinpos = end-starts;
6273 reason = "truncated input";
6274 }
6275 else {
6276 endinpos = s - starts + Py_UNICODE_SIZE;
6277 reason = "illegal code point (> 0x10FFFF)";
6278 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006279 if (unicode_decode_call_errorhandler(
6280 errors, &errorHandler,
6281 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006282 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006283 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006284 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006285 continue;
6286 }
6287
6288 s += Py_UNICODE_SIZE;
6289#ifndef Py_UNICODE_WIDE
6290 if (ch >= 0xD800 && ch <= 0xDBFF && s < end)
6291 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006292 Py_UNICODE uch2;
6293 ((char *) &uch2)[0] = s[0];
6294 ((char *) &uch2)[1] = s[1];
6295 if (uch2 >= 0xDC00 && uch2 <= 0xDFFF)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006296 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006297 ch = (((uch & 0x3FF)<<10) | (uch2 & 0x3FF)) + 0x10000;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006298 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006299 }
6300 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006301#endif
6302
6303 if (unicode_putchar(&v, &outpos, ch) < 0)
6304 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006305 }
6306
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006307 if (PyUnicode_Resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006308 goto onError;
6309 Py_XDECREF(errorHandler);
6310 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006311 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006312 return v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006313
Benjamin Peterson29060642009-01-31 22:14:21 +00006314 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006315 Py_XDECREF(v);
6316 Py_XDECREF(errorHandler);
6317 Py_XDECREF(exc);
6318 return NULL;
6319}
6320
Guido van Rossumd57fd912000-03-10 22:53:23 +00006321/* --- Latin-1 Codec ------------------------------------------------------ */
6322
Alexander Belopolsky40018472011-02-26 01:02:56 +00006323PyObject *
6324PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006325 Py_ssize_t size,
6326 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006327{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006328 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006329 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006330}
6331
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006332/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006333static void
6334make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006335 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006336 PyObject *unicode,
6337 Py_ssize_t startpos, Py_ssize_t endpos,
6338 const char *reason)
6339{
6340 if (*exceptionObject == NULL) {
6341 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006342 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006343 encoding, unicode, startpos, endpos, reason);
6344 }
6345 else {
6346 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6347 goto onError;
6348 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6349 goto onError;
6350 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6351 goto onError;
6352 return;
6353 onError:
6354 Py_DECREF(*exceptionObject);
6355 *exceptionObject = NULL;
6356 }
6357}
6358
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006359/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006360static void
6361raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006362 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006363 PyObject *unicode,
6364 Py_ssize_t startpos, Py_ssize_t endpos,
6365 const char *reason)
6366{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006367 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006368 encoding, unicode, startpos, endpos, reason);
6369 if (*exceptionObject != NULL)
6370 PyCodec_StrictErrors(*exceptionObject);
6371}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006372
6373/* error handling callback helper:
6374 build arguments, call the callback and check the arguments,
6375 put the result into newpos and return the replacement string, which
6376 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006377static PyObject *
6378unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006379 PyObject **errorHandler,
6380 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006381 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006382 Py_ssize_t startpos, Py_ssize_t endpos,
6383 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006384{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006385 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006386 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006387 PyObject *restuple;
6388 PyObject *resunicode;
6389
6390 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006391 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006392 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006393 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006394 }
6395
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006396 if (PyUnicode_READY(unicode) < 0)
6397 return NULL;
6398 len = PyUnicode_GET_LENGTH(unicode);
6399
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006400 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006401 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006402 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006403 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006404
6405 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006406 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006407 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006408 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006409 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006410 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006411 Py_DECREF(restuple);
6412 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006413 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006414 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006415 &resunicode, newpos)) {
6416 Py_DECREF(restuple);
6417 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006418 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006419 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6420 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6421 Py_DECREF(restuple);
6422 return NULL;
6423 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006424 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006425 *newpos = len + *newpos;
6426 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006427 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6428 Py_DECREF(restuple);
6429 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006430 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006431 Py_INCREF(resunicode);
6432 Py_DECREF(restuple);
6433 return resunicode;
6434}
6435
Alexander Belopolsky40018472011-02-26 01:02:56 +00006436static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006437unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006438 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006439 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006440{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006441 /* input state */
6442 Py_ssize_t pos=0, size;
6443 int kind;
6444 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006445 /* output object */
6446 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006447 /* pointer into the output */
6448 char *str;
6449 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006450 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006451 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6452 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006453 PyObject *errorHandler = NULL;
6454 PyObject *exc = NULL;
6455 /* the following variable is used for caching string comparisons
6456 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6457 int known_errorHandler = -1;
6458
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006459 if (PyUnicode_READY(unicode) < 0)
6460 return NULL;
6461 size = PyUnicode_GET_LENGTH(unicode);
6462 kind = PyUnicode_KIND(unicode);
6463 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006464 /* allocate enough for a simple encoding without
6465 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006466 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006467 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006468 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006469 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006470 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006471 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006472 ressize = size;
6473
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006474 while (pos < size) {
6475 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006476
Benjamin Peterson29060642009-01-31 22:14:21 +00006477 /* can we encode this? */
6478 if (c<limit) {
6479 /* no overflow check, because we know that the space is enough */
6480 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006481 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006482 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006483 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006484 Py_ssize_t requiredsize;
6485 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006486 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006487 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006488 Py_ssize_t collstart = pos;
6489 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006490 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006491 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006492 ++collend;
6493 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6494 if (known_errorHandler==-1) {
6495 if ((errors==NULL) || (!strcmp(errors, "strict")))
6496 known_errorHandler = 1;
6497 else if (!strcmp(errors, "replace"))
6498 known_errorHandler = 2;
6499 else if (!strcmp(errors, "ignore"))
6500 known_errorHandler = 3;
6501 else if (!strcmp(errors, "xmlcharrefreplace"))
6502 known_errorHandler = 4;
6503 else
6504 known_errorHandler = 0;
6505 }
6506 switch (known_errorHandler) {
6507 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006508 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006509 goto onError;
6510 case 2: /* replace */
6511 while (collstart++<collend)
6512 *str++ = '?'; /* fall through */
6513 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006514 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006515 break;
6516 case 4: /* xmlcharrefreplace */
6517 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006518 /* determine replacement size */
6519 for (i = collstart, repsize = 0; i < collend; ++i) {
6520 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6521 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006522 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006523 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006524 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006525 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006526 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006527 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006528 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006529#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006530 else
6531 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006532#else
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006533 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006534 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006535 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006536 repsize += 2+6+1;
6537 else
6538 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006539#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006540 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006541 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006542 if (requiredsize > ressize) {
6543 if (requiredsize<2*ressize)
6544 requiredsize = 2*ressize;
6545 if (_PyBytes_Resize(&res, requiredsize))
6546 goto onError;
6547 str = PyBytes_AS_STRING(res) + respos;
6548 ressize = requiredsize;
6549 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006550 /* generate replacement */
6551 for (i = collstart; i < collend; ++i) {
6552 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006553 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006554 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006555 break;
6556 default:
6557 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006558 encoding, reason, unicode, &exc,
6559 collstart, collend, &newpos);
6560 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6561 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006562 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006563 if (PyBytes_Check(repunicode)) {
6564 /* Directly copy bytes result to output. */
6565 repsize = PyBytes_Size(repunicode);
6566 if (repsize > 1) {
6567 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006568 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006569 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6570 Py_DECREF(repunicode);
6571 goto onError;
6572 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006573 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006574 ressize += repsize-1;
6575 }
6576 memcpy(str, PyBytes_AsString(repunicode), repsize);
6577 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006578 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006579 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006580 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006581 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006582 /* need more space? (at least enough for what we
6583 have+the replacement+the rest of the string, so
6584 we won't have to check space for encodable characters) */
6585 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006586 repsize = PyUnicode_GET_LENGTH(repunicode);
6587 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006588 if (requiredsize > ressize) {
6589 if (requiredsize<2*ressize)
6590 requiredsize = 2*ressize;
6591 if (_PyBytes_Resize(&res, requiredsize)) {
6592 Py_DECREF(repunicode);
6593 goto onError;
6594 }
6595 str = PyBytes_AS_STRING(res) + respos;
6596 ressize = requiredsize;
6597 }
6598 /* check if there is anything unencodable in the replacement
6599 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006600 for (i = 0; repsize-->0; ++i, ++str) {
6601 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006602 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006603 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006604 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006605 Py_DECREF(repunicode);
6606 goto onError;
6607 }
6608 *str = (char)c;
6609 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006610 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006611 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006612 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006613 }
6614 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006615 /* Resize if we allocated to much */
6616 size = str - PyBytes_AS_STRING(res);
6617 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006618 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006619 if (_PyBytes_Resize(&res, size) < 0)
6620 goto onError;
6621 }
6622
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006623 Py_XDECREF(errorHandler);
6624 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006625 return res;
6626
6627 onError:
6628 Py_XDECREF(res);
6629 Py_XDECREF(errorHandler);
6630 Py_XDECREF(exc);
6631 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006632}
6633
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006634/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006635PyObject *
6636PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006637 Py_ssize_t size,
6638 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006639{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006640 PyObject *result;
6641 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6642 if (unicode == NULL)
6643 return NULL;
6644 result = unicode_encode_ucs1(unicode, errors, 256);
6645 Py_DECREF(unicode);
6646 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006647}
6648
Alexander Belopolsky40018472011-02-26 01:02:56 +00006649PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006650_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006651{
6652 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006653 PyErr_BadArgument();
6654 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006655 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006656 if (PyUnicode_READY(unicode) == -1)
6657 return NULL;
6658 /* Fast path: if it is a one-byte string, construct
6659 bytes object directly. */
6660 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6661 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6662 PyUnicode_GET_LENGTH(unicode));
6663 /* Non-Latin-1 characters present. Defer to above function to
6664 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006665 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006666}
6667
6668PyObject*
6669PyUnicode_AsLatin1String(PyObject *unicode)
6670{
6671 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006672}
6673
6674/* --- 7-bit ASCII Codec -------------------------------------------------- */
6675
Alexander Belopolsky40018472011-02-26 01:02:56 +00006676PyObject *
6677PyUnicode_DecodeASCII(const char *s,
6678 Py_ssize_t size,
6679 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006680{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006681 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006682 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006683 int kind;
6684 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006685 Py_ssize_t startinpos;
6686 Py_ssize_t endinpos;
6687 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006688 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006689 int has_error;
6690 const unsigned char *p = (const unsigned char *)s;
6691 const unsigned char *end = p + size;
6692 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006693 PyObject *errorHandler = NULL;
6694 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006695
Guido van Rossumd57fd912000-03-10 22:53:23 +00006696 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006697 if (size == 1 && (unsigned char)s[0] < 128)
6698 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006699
Victor Stinner702c7342011-10-05 13:50:52 +02006700 has_error = 0;
6701 while (p < end && !has_error) {
6702 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6703 an explanation. */
6704 if (!((size_t) p & LONG_PTR_MASK)) {
6705 /* Help register allocation */
6706 register const unsigned char *_p = p;
6707 while (_p < aligned_end) {
6708 unsigned long value = *(unsigned long *) _p;
6709 if (value & ASCII_CHAR_MASK) {
6710 has_error = 1;
6711 break;
6712 }
6713 _p += SIZEOF_LONG;
6714 }
6715 if (_p == end)
6716 break;
6717 if (has_error)
6718 break;
6719 p = _p;
6720 }
6721 if (*p & 0x80) {
6722 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006723 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006724 }
6725 else {
6726 ++p;
6727 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006728 }
Victor Stinner702c7342011-10-05 13:50:52 +02006729 if (!has_error)
6730 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006731
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006732 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006733 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006734 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006735 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006736 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006737 kind = PyUnicode_KIND(v);
6738 data = PyUnicode_DATA(v);
6739 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006740 e = s + size;
6741 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006742 register unsigned char c = (unsigned char)*s;
6743 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006744 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006745 ++s;
6746 }
6747 else {
6748 startinpos = s-starts;
6749 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006750 if (unicode_decode_call_errorhandler(
6751 errors, &errorHandler,
6752 "ascii", "ordinal not in range(128)",
6753 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006754 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006755 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006756 kind = PyUnicode_KIND(v);
6757 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006758 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006759 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006760 if (PyUnicode_Resize(&v, outpos) < 0)
6761 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006762 Py_XDECREF(errorHandler);
6763 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006764 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006765 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006766
Benjamin Peterson29060642009-01-31 22:14:21 +00006767 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006768 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006769 Py_XDECREF(errorHandler);
6770 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006771 return NULL;
6772}
6773
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006774/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006775PyObject *
6776PyUnicode_EncodeASCII(const Py_UNICODE *p,
6777 Py_ssize_t size,
6778 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006779{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006780 PyObject *result;
6781 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6782 if (unicode == NULL)
6783 return NULL;
6784 result = unicode_encode_ucs1(unicode, errors, 128);
6785 Py_DECREF(unicode);
6786 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006787}
6788
Alexander Belopolsky40018472011-02-26 01:02:56 +00006789PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006790_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006791{
6792 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006793 PyErr_BadArgument();
6794 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006795 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006796 if (PyUnicode_READY(unicode) == -1)
6797 return NULL;
6798 /* Fast path: if it is an ASCII-only string, construct bytes object
6799 directly. Else defer to above function to raise the exception. */
6800 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6801 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6802 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006803 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006804}
6805
6806PyObject *
6807PyUnicode_AsASCIIString(PyObject *unicode)
6808{
6809 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006810}
6811
Victor Stinner99b95382011-07-04 14:23:54 +02006812#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006813
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006814/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006815
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006816#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006817#define NEED_RETRY
6818#endif
6819
Victor Stinner3a50e702011-10-18 21:21:00 +02006820#ifndef WC_ERR_INVALID_CHARS
6821# define WC_ERR_INVALID_CHARS 0x0080
6822#endif
6823
6824static char*
6825code_page_name(UINT code_page, PyObject **obj)
6826{
6827 *obj = NULL;
6828 if (code_page == CP_ACP)
6829 return "mbcs";
6830 if (code_page == CP_UTF7)
6831 return "CP_UTF7";
6832 if (code_page == CP_UTF8)
6833 return "CP_UTF8";
6834
6835 *obj = PyBytes_FromFormat("cp%u", code_page);
6836 if (*obj == NULL)
6837 return NULL;
6838 return PyBytes_AS_STRING(*obj);
6839}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006840
Alexander Belopolsky40018472011-02-26 01:02:56 +00006841static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006842is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006843{
6844 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006845 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006846
Victor Stinner3a50e702011-10-18 21:21:00 +02006847 if (!IsDBCSLeadByteEx(code_page, *curr))
6848 return 0;
6849
6850 prev = CharPrevExA(code_page, s, curr, 0);
6851 if (prev == curr)
6852 return 1;
6853 /* FIXME: This code is limited to "true" double-byte encodings,
6854 as it assumes an incomplete character consists of a single
6855 byte. */
6856 if (curr - prev == 2)
6857 return 1;
6858 if (!IsDBCSLeadByteEx(code_page, *prev))
6859 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006860 return 0;
6861}
6862
Victor Stinner3a50e702011-10-18 21:21:00 +02006863static DWORD
6864decode_code_page_flags(UINT code_page)
6865{
6866 if (code_page == CP_UTF7) {
6867 /* The CP_UTF7 decoder only supports flags=0 */
6868 return 0;
6869 }
6870 else
6871 return MB_ERR_INVALID_CHARS;
6872}
6873
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006874/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006875 * Decode a byte string from a Windows code page into unicode object in strict
6876 * mode.
6877 *
6878 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6879 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006880 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006881static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006882decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006883 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006884 const char *in,
6885 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006886{
Victor Stinner3a50e702011-10-18 21:21:00 +02006887 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006888 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006889 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006890
6891 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006892 assert(insize > 0);
6893 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6894 if (outsize <= 0)
6895 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006896
6897 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006898 /* Create unicode object */
Victor Stinner76a31a62011-11-04 00:05:13 +01006899 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006900 if (*v == NULL)
6901 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006902 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006903 }
6904 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006905 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006906 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner76a31a62011-11-04 00:05:13 +01006907 if (PyUnicode_Resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006908 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006909 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006910 }
6911
6912 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006913 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6914 if (outsize <= 0)
6915 goto error;
6916 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006917
Victor Stinner3a50e702011-10-18 21:21:00 +02006918error:
6919 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6920 return -2;
6921 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006922 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006923}
6924
Victor Stinner3a50e702011-10-18 21:21:00 +02006925/*
6926 * Decode a byte string from a code page into unicode object with an error
6927 * handler.
6928 *
6929 * Returns consumed size if succeed, or raise a WindowsError or
6930 * UnicodeDecodeError exception and returns -1 on error.
6931 */
6932static int
6933decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006934 PyObject **v,
6935 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006936 const char *errors)
6937{
6938 const char *startin = in;
6939 const char *endin = in + size;
6940 const DWORD flags = decode_code_page_flags(code_page);
6941 /* Ideally, we should get reason from FormatMessage. This is the Windows
6942 2000 English version of the message. */
6943 const char *reason = "No mapping for the Unicode character exists "
6944 "in the target code page.";
6945 /* each step cannot decode more than 1 character, but a character can be
6946 represented as a surrogate pair */
6947 wchar_t buffer[2], *startout, *out;
6948 int insize, outsize;
6949 PyObject *errorHandler = NULL;
6950 PyObject *exc = NULL;
6951 PyObject *encoding_obj = NULL;
6952 char *encoding;
6953 DWORD err;
6954 int ret = -1;
6955
6956 assert(size > 0);
6957
6958 encoding = code_page_name(code_page, &encoding_obj);
6959 if (encoding == NULL)
6960 return -1;
6961
6962 if (errors == NULL || strcmp(errors, "strict") == 0) {
6963 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6964 UnicodeDecodeError. */
6965 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6966 if (exc != NULL) {
6967 PyCodec_StrictErrors(exc);
6968 Py_CLEAR(exc);
6969 }
6970 goto error;
6971 }
6972
6973 if (*v == NULL) {
6974 /* Create unicode object */
6975 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6976 PyErr_NoMemory();
6977 goto error;
6978 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006979 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006980 if (*v == NULL)
6981 goto error;
6982 startout = PyUnicode_AS_UNICODE(*v);
6983 }
6984 else {
6985 /* Extend unicode object */
6986 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6987 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6988 PyErr_NoMemory();
6989 goto error;
6990 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006991 if (PyUnicode_Resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006992 goto error;
6993 startout = PyUnicode_AS_UNICODE(*v) + n;
6994 }
6995
6996 /* Decode the byte string character per character */
6997 out = startout;
6998 while (in < endin)
6999 {
7000 /* Decode a character */
7001 insize = 1;
7002 do
7003 {
7004 outsize = MultiByteToWideChar(code_page, flags,
7005 in, insize,
7006 buffer, Py_ARRAY_LENGTH(buffer));
7007 if (outsize > 0)
7008 break;
7009 err = GetLastError();
7010 if (err != ERROR_NO_UNICODE_TRANSLATION
7011 && err != ERROR_INSUFFICIENT_BUFFER)
7012 {
7013 PyErr_SetFromWindowsErr(0);
7014 goto error;
7015 }
7016 insize++;
7017 }
7018 /* 4=maximum length of a UTF-8 sequence */
7019 while (insize <= 4 && (in + insize) <= endin);
7020
7021 if (outsize <= 0) {
7022 Py_ssize_t startinpos, endinpos, outpos;
7023
7024 startinpos = in - startin;
7025 endinpos = startinpos + 1;
7026 outpos = out - PyUnicode_AS_UNICODE(*v);
7027 if (unicode_decode_call_errorhandler(
7028 errors, &errorHandler,
7029 encoding, reason,
7030 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007031 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007032 {
7033 goto error;
7034 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007035 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007036 }
7037 else {
7038 in += insize;
7039 memcpy(out, buffer, outsize * sizeof(wchar_t));
7040 out += outsize;
7041 }
7042 }
7043
7044 /* write a NUL character at the end */
7045 *out = 0;
7046
7047 /* Extend unicode object */
7048 outsize = out - startout;
7049 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner76a31a62011-11-04 00:05:13 +01007050 if (PyUnicode_Resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007051 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007052 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007053
7054error:
7055 Py_XDECREF(encoding_obj);
7056 Py_XDECREF(errorHandler);
7057 Py_XDECREF(exc);
7058 return ret;
7059}
7060
Victor Stinner3a50e702011-10-18 21:21:00 +02007061static PyObject *
7062decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007063 const char *s, Py_ssize_t size,
7064 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007065{
Victor Stinner76a31a62011-11-04 00:05:13 +01007066 PyObject *v = NULL;
7067 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007068
Victor Stinner3a50e702011-10-18 21:21:00 +02007069 if (code_page < 0) {
7070 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7071 return NULL;
7072 }
7073
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007074 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007075 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007076
Victor Stinner76a31a62011-11-04 00:05:13 +01007077 do
7078 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007079#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007080 if (size > INT_MAX) {
7081 chunk_size = INT_MAX;
7082 final = 0;
7083 done = 0;
7084 }
7085 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007086#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007087 {
7088 chunk_size = (int)size;
7089 final = (consumed == NULL);
7090 done = 1;
7091 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007092
Victor Stinner76a31a62011-11-04 00:05:13 +01007093 /* Skip trailing lead-byte unless 'final' is set */
7094 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7095 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007096
Victor Stinner76a31a62011-11-04 00:05:13 +01007097 if (chunk_size == 0 && done) {
7098 if (v != NULL)
7099 break;
7100 Py_INCREF(unicode_empty);
7101 return unicode_empty;
7102 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007103
Victor Stinner76a31a62011-11-04 00:05:13 +01007104
7105 converted = decode_code_page_strict(code_page, &v,
7106 s, chunk_size);
7107 if (converted == -2)
7108 converted = decode_code_page_errors(code_page, &v,
7109 s, chunk_size,
7110 errors);
7111 assert(converted != 0);
7112
7113 if (converted < 0) {
7114 Py_XDECREF(v);
7115 return NULL;
7116 }
7117
7118 if (consumed)
7119 *consumed += converted;
7120
7121 s += converted;
7122 size -= converted;
7123 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007124
Victor Stinner17efeed2011-10-04 20:05:46 +02007125#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007126 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007127 Py_DECREF(v);
7128 return NULL;
7129 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007130#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007131 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner76a31a62011-11-04 00:05:13 +01007132 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007133}
7134
Alexander Belopolsky40018472011-02-26 01:02:56 +00007135PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007136PyUnicode_DecodeCodePageStateful(int code_page,
7137 const char *s,
7138 Py_ssize_t size,
7139 const char *errors,
7140 Py_ssize_t *consumed)
7141{
7142 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7143}
7144
7145PyObject *
7146PyUnicode_DecodeMBCSStateful(const char *s,
7147 Py_ssize_t size,
7148 const char *errors,
7149 Py_ssize_t *consumed)
7150{
7151 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7152}
7153
7154PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007155PyUnicode_DecodeMBCS(const char *s,
7156 Py_ssize_t size,
7157 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007158{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007159 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7160}
7161
Victor Stinner3a50e702011-10-18 21:21:00 +02007162static DWORD
7163encode_code_page_flags(UINT code_page, const char *errors)
7164{
7165 if (code_page == CP_UTF8) {
7166 if (winver.dwMajorVersion >= 6)
7167 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7168 and later */
7169 return WC_ERR_INVALID_CHARS;
7170 else
7171 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7172 return 0;
7173 }
7174 else if (code_page == CP_UTF7) {
7175 /* CP_UTF7 only supports flags=0 */
7176 return 0;
7177 }
7178 else {
7179 if (errors != NULL && strcmp(errors, "replace") == 0)
7180 return 0;
7181 else
7182 return WC_NO_BEST_FIT_CHARS;
7183 }
7184}
7185
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007186/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007187 * Encode a Unicode string to a Windows code page into a byte string in strict
7188 * mode.
7189 *
7190 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7191 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007192 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007193static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007194encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007195 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007196 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007197{
Victor Stinner554f3f02010-06-16 23:33:54 +00007198 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007199 BOOL *pusedDefaultChar = &usedDefaultChar;
7200 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007201 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007202 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007203 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007204 const DWORD flags = encode_code_page_flags(code_page, NULL);
7205 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007206 /* Create a substring so that we can get the UTF-16 representation
7207 of just the slice under consideration. */
7208 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007209
Martin v. Löwis3d325192011-11-04 18:23:06 +01007210 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007211
Victor Stinner3a50e702011-10-18 21:21:00 +02007212 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007213 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007214 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007215 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007216
Victor Stinner2fc507f2011-11-04 20:06:39 +01007217 substring = PyUnicode_Substring(unicode, offset, offset+len);
7218 if (substring == NULL)
7219 return -1;
7220 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7221 if (p == NULL) {
7222 Py_DECREF(substring);
7223 return -1;
7224 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007225
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007226 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007227 outsize = WideCharToMultiByte(code_page, flags,
7228 p, size,
7229 NULL, 0,
7230 NULL, pusedDefaultChar);
7231 if (outsize <= 0)
7232 goto error;
7233 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007234 if (pusedDefaultChar && *pusedDefaultChar) {
7235 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007236 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007237 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007238
Victor Stinner3a50e702011-10-18 21:21:00 +02007239 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007240 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007241 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007242 if (*outbytes == NULL) {
7243 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007244 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007245 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007246 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007247 }
7248 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007249 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007250 const Py_ssize_t n = PyBytes_Size(*outbytes);
7251 if (outsize > PY_SSIZE_T_MAX - n) {
7252 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007253 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007254 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007255 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007256 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7257 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007258 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007259 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007260 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007261 }
7262
7263 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007264 outsize = WideCharToMultiByte(code_page, flags,
7265 p, size,
7266 out, outsize,
7267 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007268 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007269 if (outsize <= 0)
7270 goto error;
7271 if (pusedDefaultChar && *pusedDefaultChar)
7272 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007273 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007274
Victor Stinner3a50e702011-10-18 21:21:00 +02007275error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007276 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007277 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7278 return -2;
7279 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007280 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007281}
7282
Victor Stinner3a50e702011-10-18 21:21:00 +02007283/*
7284 * Encode a Unicode string to a Windows code page into a byte string using a
7285 * error handler.
7286 *
7287 * Returns consumed characters if succeed, or raise a WindowsError and returns
7288 * -1 on other error.
7289 */
7290static int
7291encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007292 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007293 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007294{
Victor Stinner3a50e702011-10-18 21:21:00 +02007295 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007296 Py_ssize_t pos = unicode_offset;
7297 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007298 /* Ideally, we should get reason from FormatMessage. This is the Windows
7299 2000 English version of the message. */
7300 const char *reason = "invalid character";
7301 /* 4=maximum length of a UTF-8 sequence */
7302 char buffer[4];
7303 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7304 Py_ssize_t outsize;
7305 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007306 PyObject *errorHandler = NULL;
7307 PyObject *exc = NULL;
7308 PyObject *encoding_obj = NULL;
7309 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007310 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007311 PyObject *rep;
7312 int ret = -1;
7313
7314 assert(insize > 0);
7315
7316 encoding = code_page_name(code_page, &encoding_obj);
7317 if (encoding == NULL)
7318 return -1;
7319
7320 if (errors == NULL || strcmp(errors, "strict") == 0) {
7321 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7322 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007323 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007324 if (exc != NULL) {
7325 PyCodec_StrictErrors(exc);
7326 Py_DECREF(exc);
7327 }
7328 Py_XDECREF(encoding_obj);
7329 return -1;
7330 }
7331
7332 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7333 pusedDefaultChar = &usedDefaultChar;
7334 else
7335 pusedDefaultChar = NULL;
7336
7337 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7338 PyErr_NoMemory();
7339 goto error;
7340 }
7341 outsize = insize * Py_ARRAY_LENGTH(buffer);
7342
7343 if (*outbytes == NULL) {
7344 /* Create string object */
7345 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7346 if (*outbytes == NULL)
7347 goto error;
7348 out = PyBytes_AS_STRING(*outbytes);
7349 }
7350 else {
7351 /* Extend string object */
7352 Py_ssize_t n = PyBytes_Size(*outbytes);
7353 if (n > PY_SSIZE_T_MAX - outsize) {
7354 PyErr_NoMemory();
7355 goto error;
7356 }
7357 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7358 goto error;
7359 out = PyBytes_AS_STRING(*outbytes) + n;
7360 }
7361
7362 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007363 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007364 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007365 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7366 wchar_t chars[2];
7367 int charsize;
7368 if (ch < 0x10000) {
7369 chars[0] = (wchar_t)ch;
7370 charsize = 1;
7371 }
7372 else {
7373 ch -= 0x10000;
7374 chars[0] = 0xd800 + (ch >> 10);
7375 chars[1] = 0xdc00 + (ch & 0x3ff);
7376 charsize = 2;
7377 }
7378
Victor Stinner3a50e702011-10-18 21:21:00 +02007379 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007380 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007381 buffer, Py_ARRAY_LENGTH(buffer),
7382 NULL, pusedDefaultChar);
7383 if (outsize > 0) {
7384 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7385 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007386 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007387 memcpy(out, buffer, outsize);
7388 out += outsize;
7389 continue;
7390 }
7391 }
7392 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7393 PyErr_SetFromWindowsErr(0);
7394 goto error;
7395 }
7396
Victor Stinner3a50e702011-10-18 21:21:00 +02007397 rep = unicode_encode_call_errorhandler(
7398 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007399 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007400 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007401 if (rep == NULL)
7402 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007403 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007404
7405 if (PyBytes_Check(rep)) {
7406 outsize = PyBytes_GET_SIZE(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 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7417 out += outsize;
7418 }
7419 else {
7420 Py_ssize_t i;
7421 enum PyUnicode_Kind kind;
7422 void *data;
7423
7424 if (PyUnicode_READY(rep) < 0) {
7425 Py_DECREF(rep);
7426 goto error;
7427 }
7428
7429 outsize = PyUnicode_GET_LENGTH(rep);
7430 if (outsize != 1) {
7431 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7432 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7433 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7434 Py_DECREF(rep);
7435 goto error;
7436 }
7437 out = PyBytes_AS_STRING(*outbytes) + offset;
7438 }
7439 kind = PyUnicode_KIND(rep);
7440 data = PyUnicode_DATA(rep);
7441 for (i=0; i < outsize; i++) {
7442 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7443 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007444 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007445 encoding, unicode,
7446 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007447 "unable to encode error handler result to ASCII");
7448 Py_DECREF(rep);
7449 goto error;
7450 }
7451 *out = (unsigned char)ch;
7452 out++;
7453 }
7454 }
7455 Py_DECREF(rep);
7456 }
7457 /* write a NUL byte */
7458 *out = 0;
7459 outsize = out - PyBytes_AS_STRING(*outbytes);
7460 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7461 if (_PyBytes_Resize(outbytes, outsize) < 0)
7462 goto error;
7463 ret = 0;
7464
7465error:
7466 Py_XDECREF(encoding_obj);
7467 Py_XDECREF(errorHandler);
7468 Py_XDECREF(exc);
7469 return ret;
7470}
7471
Victor Stinner3a50e702011-10-18 21:21:00 +02007472static PyObject *
7473encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007474 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007475 const char *errors)
7476{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007477 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007478 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007479 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007480 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007481
Victor Stinner2fc507f2011-11-04 20:06:39 +01007482 if (PyUnicode_READY(unicode) < 0)
7483 return NULL;
7484 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007485
Victor Stinner3a50e702011-10-18 21:21:00 +02007486 if (code_page < 0) {
7487 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7488 return NULL;
7489 }
7490
Martin v. Löwis3d325192011-11-04 18:23:06 +01007491 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007492 return PyBytes_FromStringAndSize(NULL, 0);
7493
Victor Stinner7581cef2011-11-03 22:32:33 +01007494 offset = 0;
7495 do
7496 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007497#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007498 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007499 chunks. */
7500 if (len > INT_MAX/2) {
7501 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007502 done = 0;
7503 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007504 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007505#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007506 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007507 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007508 done = 1;
7509 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007510
Victor Stinner76a31a62011-11-04 00:05:13 +01007511 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007512 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007513 errors);
7514 if (ret == -2)
7515 ret = encode_code_page_errors(code_page, &outbytes,
7516 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007517 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007518 if (ret < 0) {
7519 Py_XDECREF(outbytes);
7520 return NULL;
7521 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007522
Victor Stinner7581cef2011-11-03 22:32:33 +01007523 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007524 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007525 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007526
Victor Stinner3a50e702011-10-18 21:21:00 +02007527 return outbytes;
7528}
7529
7530PyObject *
7531PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7532 Py_ssize_t size,
7533 const char *errors)
7534{
Victor Stinner7581cef2011-11-03 22:32:33 +01007535 PyObject *unicode, *res;
7536 unicode = PyUnicode_FromUnicode(p, size);
7537 if (unicode == NULL)
7538 return NULL;
7539 res = encode_code_page(CP_ACP, unicode, errors);
7540 Py_DECREF(unicode);
7541 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007542}
7543
7544PyObject *
7545PyUnicode_EncodeCodePage(int code_page,
7546 PyObject *unicode,
7547 const char *errors)
7548{
Victor Stinner7581cef2011-11-03 22:32:33 +01007549 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007550}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007551
Alexander Belopolsky40018472011-02-26 01:02:56 +00007552PyObject *
7553PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007554{
7555 if (!PyUnicode_Check(unicode)) {
7556 PyErr_BadArgument();
7557 return NULL;
7558 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007559 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007560}
7561
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007562#undef NEED_RETRY
7563
Victor Stinner99b95382011-07-04 14:23:54 +02007564#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007565
Guido van Rossumd57fd912000-03-10 22:53:23 +00007566/* --- Character Mapping Codec -------------------------------------------- */
7567
Alexander Belopolsky40018472011-02-26 01:02:56 +00007568PyObject *
7569PyUnicode_DecodeCharmap(const char *s,
7570 Py_ssize_t size,
7571 PyObject *mapping,
7572 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007573{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007574 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007575 Py_ssize_t startinpos;
7576 Py_ssize_t endinpos;
7577 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007578 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007579 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007580 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007581 PyObject *errorHandler = NULL;
7582 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007583
Guido van Rossumd57fd912000-03-10 22:53:23 +00007584 /* Default to Latin-1 */
7585 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007586 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007587
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007588 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007589 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007590 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007591 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007592 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007593 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007594 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007595 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007596 Py_ssize_t maplen;
7597 enum PyUnicode_Kind kind;
7598 void *data;
7599 Py_UCS4 x;
7600
7601 if (PyUnicode_READY(mapping) < 0)
7602 return NULL;
7603
7604 maplen = PyUnicode_GET_LENGTH(mapping);
7605 data = PyUnicode_DATA(mapping);
7606 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007607 while (s < e) {
7608 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007609
Benjamin Peterson29060642009-01-31 22:14:21 +00007610 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007611 x = PyUnicode_READ(kind, data, ch);
7612 else
7613 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007614
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007615 if (x == 0xfffe)
7616 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007617 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007618 startinpos = s-starts;
7619 endinpos = startinpos+1;
7620 if (unicode_decode_call_errorhandler(
7621 errors, &errorHandler,
7622 "charmap", "character maps to <undefined>",
7623 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007624 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007625 goto onError;
7626 }
7627 continue;
7628 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007629
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007630 if (unicode_putchar(&v, &outpos, x) < 0)
7631 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007632 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007633 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007634 }
7635 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007636 while (s < e) {
7637 unsigned char ch = *s;
7638 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007639
Benjamin Peterson29060642009-01-31 22:14:21 +00007640 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7641 w = PyLong_FromLong((long)ch);
7642 if (w == NULL)
7643 goto onError;
7644 x = PyObject_GetItem(mapping, w);
7645 Py_DECREF(w);
7646 if (x == NULL) {
7647 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7648 /* No mapping found means: mapping is undefined. */
7649 PyErr_Clear();
7650 x = Py_None;
7651 Py_INCREF(x);
7652 } else
7653 goto onError;
7654 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007655
Benjamin Peterson29060642009-01-31 22:14:21 +00007656 /* Apply mapping */
7657 if (PyLong_Check(x)) {
7658 long value = PyLong_AS_LONG(x);
7659 if (value < 0 || value > 65535) {
7660 PyErr_SetString(PyExc_TypeError,
7661 "character mapping must be in range(65536)");
7662 Py_DECREF(x);
7663 goto onError;
7664 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007665 if (unicode_putchar(&v, &outpos, value) < 0)
7666 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007667 }
7668 else if (x == Py_None) {
7669 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007670 startinpos = s-starts;
7671 endinpos = startinpos+1;
7672 if (unicode_decode_call_errorhandler(
7673 errors, &errorHandler,
7674 "charmap", "character maps to <undefined>",
7675 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007676 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007677 Py_DECREF(x);
7678 goto onError;
7679 }
7680 Py_DECREF(x);
7681 continue;
7682 }
7683 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007684 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007685
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007686 if (PyUnicode_READY(x) < 0)
7687 goto onError;
7688 targetsize = PyUnicode_GET_LENGTH(x);
7689
7690 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007691 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007692 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007693 PyUnicode_READ_CHAR(x, 0)) < 0)
7694 goto onError;
7695 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007696 else if (targetsize > 1) {
7697 /* 1-n mapping */
7698 if (targetsize > extrachars) {
7699 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007700 Py_ssize_t needed = (targetsize - extrachars) + \
7701 (targetsize << 2);
7702 extrachars += needed;
7703 /* XXX overflow detection missing */
Victor Stinner7931d9a2011-11-04 00:22:48 +01007704 if (PyUnicode_Resize(&v,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007705 PyUnicode_GET_LENGTH(v) + needed) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007706 Py_DECREF(x);
7707 goto onError;
7708 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007709 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007710 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7711 goto onError;
7712 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7713 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007714 extrachars -= targetsize;
7715 }
7716 /* 1-0 mapping: skip the character */
7717 }
7718 else {
7719 /* wrong return value */
7720 PyErr_SetString(PyExc_TypeError,
7721 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007722 Py_DECREF(x);
7723 goto onError;
7724 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007725 Py_DECREF(x);
7726 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007727 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007728 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007729 if (PyUnicode_Resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007730 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007731 Py_XDECREF(errorHandler);
7732 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007733 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01007734 return v;
Tim Petersced69f82003-09-16 20:30:58 +00007735
Benjamin Peterson29060642009-01-31 22:14:21 +00007736 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007737 Py_XDECREF(errorHandler);
7738 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007739 Py_XDECREF(v);
7740 return NULL;
7741}
7742
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007743/* Charmap encoding: the lookup table */
7744
Alexander Belopolsky40018472011-02-26 01:02:56 +00007745struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007746 PyObject_HEAD
7747 unsigned char level1[32];
7748 int count2, count3;
7749 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007750};
7751
7752static PyObject*
7753encoding_map_size(PyObject *obj, PyObject* args)
7754{
7755 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007756 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007757 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007758}
7759
7760static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007761 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007762 PyDoc_STR("Return the size (in bytes) of this object") },
7763 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007764};
7765
7766static void
7767encoding_map_dealloc(PyObject* o)
7768{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007769 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007770}
7771
7772static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007773 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007774 "EncodingMap", /*tp_name*/
7775 sizeof(struct encoding_map), /*tp_basicsize*/
7776 0, /*tp_itemsize*/
7777 /* methods */
7778 encoding_map_dealloc, /*tp_dealloc*/
7779 0, /*tp_print*/
7780 0, /*tp_getattr*/
7781 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007782 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007783 0, /*tp_repr*/
7784 0, /*tp_as_number*/
7785 0, /*tp_as_sequence*/
7786 0, /*tp_as_mapping*/
7787 0, /*tp_hash*/
7788 0, /*tp_call*/
7789 0, /*tp_str*/
7790 0, /*tp_getattro*/
7791 0, /*tp_setattro*/
7792 0, /*tp_as_buffer*/
7793 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7794 0, /*tp_doc*/
7795 0, /*tp_traverse*/
7796 0, /*tp_clear*/
7797 0, /*tp_richcompare*/
7798 0, /*tp_weaklistoffset*/
7799 0, /*tp_iter*/
7800 0, /*tp_iternext*/
7801 encoding_map_methods, /*tp_methods*/
7802 0, /*tp_members*/
7803 0, /*tp_getset*/
7804 0, /*tp_base*/
7805 0, /*tp_dict*/
7806 0, /*tp_descr_get*/
7807 0, /*tp_descr_set*/
7808 0, /*tp_dictoffset*/
7809 0, /*tp_init*/
7810 0, /*tp_alloc*/
7811 0, /*tp_new*/
7812 0, /*tp_free*/
7813 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007814};
7815
7816PyObject*
7817PyUnicode_BuildEncodingMap(PyObject* string)
7818{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007819 PyObject *result;
7820 struct encoding_map *mresult;
7821 int i;
7822 int need_dict = 0;
7823 unsigned char level1[32];
7824 unsigned char level2[512];
7825 unsigned char *mlevel1, *mlevel2, *mlevel3;
7826 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007827 int kind;
7828 void *data;
7829 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007830
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007831 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007832 PyErr_BadArgument();
7833 return NULL;
7834 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007835 kind = PyUnicode_KIND(string);
7836 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007837 memset(level1, 0xFF, sizeof level1);
7838 memset(level2, 0xFF, sizeof level2);
7839
7840 /* If there isn't a one-to-one mapping of NULL to \0,
7841 or if there are non-BMP characters, we need to use
7842 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007843 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007844 need_dict = 1;
7845 for (i = 1; i < 256; i++) {
7846 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007847 ch = PyUnicode_READ(kind, data, i);
7848 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007849 need_dict = 1;
7850 break;
7851 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007852 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007853 /* unmapped character */
7854 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007855 l1 = ch >> 11;
7856 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007857 if (level1[l1] == 0xFF)
7858 level1[l1] = count2++;
7859 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007860 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007861 }
7862
7863 if (count2 >= 0xFF || count3 >= 0xFF)
7864 need_dict = 1;
7865
7866 if (need_dict) {
7867 PyObject *result = PyDict_New();
7868 PyObject *key, *value;
7869 if (!result)
7870 return NULL;
7871 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007872 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007873 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007874 if (!key || !value)
7875 goto failed1;
7876 if (PyDict_SetItem(result, key, value) == -1)
7877 goto failed1;
7878 Py_DECREF(key);
7879 Py_DECREF(value);
7880 }
7881 return result;
7882 failed1:
7883 Py_XDECREF(key);
7884 Py_XDECREF(value);
7885 Py_DECREF(result);
7886 return NULL;
7887 }
7888
7889 /* Create a three-level trie */
7890 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7891 16*count2 + 128*count3 - 1);
7892 if (!result)
7893 return PyErr_NoMemory();
7894 PyObject_Init(result, &EncodingMapType);
7895 mresult = (struct encoding_map*)result;
7896 mresult->count2 = count2;
7897 mresult->count3 = count3;
7898 mlevel1 = mresult->level1;
7899 mlevel2 = mresult->level23;
7900 mlevel3 = mresult->level23 + 16*count2;
7901 memcpy(mlevel1, level1, 32);
7902 memset(mlevel2, 0xFF, 16*count2);
7903 memset(mlevel3, 0, 128*count3);
7904 count3 = 0;
7905 for (i = 1; i < 256; i++) {
7906 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007907 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007908 /* unmapped character */
7909 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007910 o1 = PyUnicode_READ(kind, data, i)>>11;
7911 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007912 i2 = 16*mlevel1[o1] + o2;
7913 if (mlevel2[i2] == 0xFF)
7914 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007915 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007916 i3 = 128*mlevel2[i2] + o3;
7917 mlevel3[i3] = i;
7918 }
7919 return result;
7920}
7921
7922static int
Victor Stinner22168992011-11-20 17:09:18 +01007923encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007924{
7925 struct encoding_map *map = (struct encoding_map*)mapping;
7926 int l1 = c>>11;
7927 int l2 = (c>>7) & 0xF;
7928 int l3 = c & 0x7F;
7929 int i;
7930
Victor Stinner22168992011-11-20 17:09:18 +01007931 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007932 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007933 if (c == 0)
7934 return 0;
7935 /* level 1*/
7936 i = map->level1[l1];
7937 if (i == 0xFF) {
7938 return -1;
7939 }
7940 /* level 2*/
7941 i = map->level23[16*i+l2];
7942 if (i == 0xFF) {
7943 return -1;
7944 }
7945 /* level 3 */
7946 i = map->level23[16*map->count2 + 128*i + l3];
7947 if (i == 0) {
7948 return -1;
7949 }
7950 return i;
7951}
7952
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007953/* Lookup the character ch in the mapping. If the character
7954 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007955 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007956static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007957charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007958{
Christian Heimes217cfd12007-12-02 14:31:20 +00007959 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007960 PyObject *x;
7961
7962 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007963 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007964 x = PyObject_GetItem(mapping, w);
7965 Py_DECREF(w);
7966 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007967 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7968 /* No mapping found means: mapping is undefined. */
7969 PyErr_Clear();
7970 x = Py_None;
7971 Py_INCREF(x);
7972 return x;
7973 } else
7974 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007975 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007976 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007977 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007978 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007979 long value = PyLong_AS_LONG(x);
7980 if (value < 0 || value > 255) {
7981 PyErr_SetString(PyExc_TypeError,
7982 "character mapping must be in range(256)");
7983 Py_DECREF(x);
7984 return NULL;
7985 }
7986 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007987 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007988 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007989 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007990 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007991 /* wrong return value */
7992 PyErr_Format(PyExc_TypeError,
7993 "character mapping must return integer, bytes or None, not %.400s",
7994 x->ob_type->tp_name);
7995 Py_DECREF(x);
7996 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007997 }
7998}
7999
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008000static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008001charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008002{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008003 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8004 /* exponentially overallocate to minimize reallocations */
8005 if (requiredsize < 2*outsize)
8006 requiredsize = 2*outsize;
8007 if (_PyBytes_Resize(outobj, requiredsize))
8008 return -1;
8009 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008010}
8011
Benjamin Peterson14339b62009-01-31 16:36:08 +00008012typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008013 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008014} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008015/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008016 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008017 space is available. Return a new reference to the object that
8018 was put in the output buffer, or Py_None, if the mapping was undefined
8019 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008020 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008021static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008022charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008023 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008024{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008025 PyObject *rep;
8026 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008027 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008028
Christian Heimes90aa7642007-12-19 02:45:37 +00008029 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008030 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008031 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008032 if (res == -1)
8033 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008034 if (outsize<requiredsize)
8035 if (charmapencode_resize(outobj, outpos, requiredsize))
8036 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008037 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008038 outstart[(*outpos)++] = (char)res;
8039 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008040 }
8041
8042 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008043 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008044 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008045 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008046 Py_DECREF(rep);
8047 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008048 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008049 if (PyLong_Check(rep)) {
8050 Py_ssize_t requiredsize = *outpos+1;
8051 if (outsize<requiredsize)
8052 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8053 Py_DECREF(rep);
8054 return enc_EXCEPTION;
8055 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008056 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008057 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008058 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008059 else {
8060 const char *repchars = PyBytes_AS_STRING(rep);
8061 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8062 Py_ssize_t requiredsize = *outpos+repsize;
8063 if (outsize<requiredsize)
8064 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8065 Py_DECREF(rep);
8066 return enc_EXCEPTION;
8067 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008068 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008069 memcpy(outstart + *outpos, repchars, repsize);
8070 *outpos += repsize;
8071 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008072 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008073 Py_DECREF(rep);
8074 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008075}
8076
8077/* handle an error in PyUnicode_EncodeCharmap
8078 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008079static int
8080charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008081 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008082 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008083 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008084 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008085{
8086 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008087 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008088 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008089 enum PyUnicode_Kind kind;
8090 void *data;
8091 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008092 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008093 Py_ssize_t collstartpos = *inpos;
8094 Py_ssize_t collendpos = *inpos+1;
8095 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008096 char *encoding = "charmap";
8097 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008098 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008099 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008100 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008101
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008102 if (PyUnicode_READY(unicode) < 0)
8103 return -1;
8104 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008105 /* find all unencodable characters */
8106 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008107 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008108 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008109 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008110 val = encoding_map_lookup(ch, mapping);
8111 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008112 break;
8113 ++collendpos;
8114 continue;
8115 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008116
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008117 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8118 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008119 if (rep==NULL)
8120 return -1;
8121 else if (rep!=Py_None) {
8122 Py_DECREF(rep);
8123 break;
8124 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008125 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008126 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008127 }
8128 /* cache callback name lookup
8129 * (if not done yet, i.e. it's the first error) */
8130 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008131 if ((errors==NULL) || (!strcmp(errors, "strict")))
8132 *known_errorHandler = 1;
8133 else if (!strcmp(errors, "replace"))
8134 *known_errorHandler = 2;
8135 else if (!strcmp(errors, "ignore"))
8136 *known_errorHandler = 3;
8137 else if (!strcmp(errors, "xmlcharrefreplace"))
8138 *known_errorHandler = 4;
8139 else
8140 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008141 }
8142 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008143 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008144 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008145 return -1;
8146 case 2: /* replace */
8147 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008148 x = charmapencode_output('?', mapping, res, respos);
8149 if (x==enc_EXCEPTION) {
8150 return -1;
8151 }
8152 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008153 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008154 return -1;
8155 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008156 }
8157 /* fall through */
8158 case 3: /* ignore */
8159 *inpos = collendpos;
8160 break;
8161 case 4: /* xmlcharrefreplace */
8162 /* generate replacement (temporarily (mis)uses p) */
8163 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008164 char buffer[2+29+1+1];
8165 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008166 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008167 for (cp = buffer; *cp; ++cp) {
8168 x = charmapencode_output(*cp, mapping, res, respos);
8169 if (x==enc_EXCEPTION)
8170 return -1;
8171 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008172 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008173 return -1;
8174 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008175 }
8176 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008177 *inpos = collendpos;
8178 break;
8179 default:
8180 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008181 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008182 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008183 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008184 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008185 if (PyBytes_Check(repunicode)) {
8186 /* Directly copy bytes result to output. */
8187 Py_ssize_t outsize = PyBytes_Size(*res);
8188 Py_ssize_t requiredsize;
8189 repsize = PyBytes_Size(repunicode);
8190 requiredsize = *respos + repsize;
8191 if (requiredsize > outsize)
8192 /* Make room for all additional bytes. */
8193 if (charmapencode_resize(res, respos, requiredsize)) {
8194 Py_DECREF(repunicode);
8195 return -1;
8196 }
8197 memcpy(PyBytes_AsString(*res) + *respos,
8198 PyBytes_AsString(repunicode), repsize);
8199 *respos += repsize;
8200 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008201 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008202 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008203 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008204 /* generate replacement */
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008205 if (PyUnicode_READY(repunicode) < 0) {
8206 Py_DECREF(repunicode);
8207 return -1;
8208 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008209 repsize = PyUnicode_GET_SIZE(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008210 data = PyUnicode_DATA(repunicode);
8211 kind = PyUnicode_KIND(repunicode);
8212 for (index = 0; index < repsize; index++) {
8213 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8214 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008215 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008216 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008217 return -1;
8218 }
8219 else if (x==enc_FAILED) {
8220 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008221 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008222 return -1;
8223 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008224 }
8225 *inpos = newpos;
8226 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008227 }
8228 return 0;
8229}
8230
Alexander Belopolsky40018472011-02-26 01:02:56 +00008231PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008232_PyUnicode_EncodeCharmap(PyObject *unicode,
8233 PyObject *mapping,
8234 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008235{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008236 /* output object */
8237 PyObject *res = NULL;
8238 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008239 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008240 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008241 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008242 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008243 PyObject *errorHandler = NULL;
8244 PyObject *exc = NULL;
8245 /* the following variable is used for caching string comparisons
8246 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8247 * 3=ignore, 4=xmlcharrefreplace */
8248 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008249
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008250 if (PyUnicode_READY(unicode) < 0)
8251 return NULL;
8252 size = PyUnicode_GET_LENGTH(unicode);
8253
Guido van Rossumd57fd912000-03-10 22:53:23 +00008254 /* Default to Latin-1 */
8255 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008256 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008257
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008258 /* allocate enough for a simple encoding without
8259 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008260 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008261 if (res == NULL)
8262 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008263 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008264 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008265
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008266 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008267 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008268 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008269 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008270 if (x==enc_EXCEPTION) /* error */
8271 goto onError;
8272 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008273 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008274 &exc,
8275 &known_errorHandler, &errorHandler, errors,
8276 &res, &respos)) {
8277 goto onError;
8278 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008279 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008280 else
8281 /* done with this character => adjust input position */
8282 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008283 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008284
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008285 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008286 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008287 if (_PyBytes_Resize(&res, respos) < 0)
8288 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008289
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008290 Py_XDECREF(exc);
8291 Py_XDECREF(errorHandler);
8292 return res;
8293
Benjamin Peterson29060642009-01-31 22:14:21 +00008294 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008295 Py_XDECREF(res);
8296 Py_XDECREF(exc);
8297 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008298 return NULL;
8299}
8300
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008301/* Deprecated */
8302PyObject *
8303PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8304 Py_ssize_t size,
8305 PyObject *mapping,
8306 const char *errors)
8307{
8308 PyObject *result;
8309 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8310 if (unicode == NULL)
8311 return NULL;
8312 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8313 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008314 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008315}
8316
Alexander Belopolsky40018472011-02-26 01:02:56 +00008317PyObject *
8318PyUnicode_AsCharmapString(PyObject *unicode,
8319 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008320{
8321 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008322 PyErr_BadArgument();
8323 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008324 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008325 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008326}
8327
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008328/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008329static void
8330make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008331 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008332 Py_ssize_t startpos, Py_ssize_t endpos,
8333 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008334{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008335 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008336 *exceptionObject = _PyUnicodeTranslateError_Create(
8337 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008338 }
8339 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008340 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8341 goto onError;
8342 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8343 goto onError;
8344 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8345 goto onError;
8346 return;
8347 onError:
8348 Py_DECREF(*exceptionObject);
8349 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008350 }
8351}
8352
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008353/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008354static void
8355raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008356 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008357 Py_ssize_t startpos, Py_ssize_t endpos,
8358 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008359{
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 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008364}
8365
8366/* error handling callback helper:
8367 build arguments, call the callback and check the arguments,
8368 put the result into newpos and return the replacement string, which
8369 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008370static PyObject *
8371unicode_translate_call_errorhandler(const char *errors,
8372 PyObject **errorHandler,
8373 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008374 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008375 Py_ssize_t startpos, Py_ssize_t endpos,
8376 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008377{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008378 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008379
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008380 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008381 PyObject *restuple;
8382 PyObject *resunicode;
8383
8384 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008385 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008386 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008387 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008388 }
8389
8390 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008391 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008392 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008393 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008394
8395 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008396 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008397 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008398 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008399 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008400 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008401 Py_DECREF(restuple);
8402 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008403 }
8404 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008405 &resunicode, &i_newpos)) {
8406 Py_DECREF(restuple);
8407 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008408 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008409 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008410 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008411 else
8412 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008413 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008414 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8415 Py_DECREF(restuple);
8416 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008417 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008418 Py_INCREF(resunicode);
8419 Py_DECREF(restuple);
8420 return resunicode;
8421}
8422
8423/* Lookup the character ch in the mapping and put the result in result,
8424 which must be decrefed by the caller.
8425 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008426static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008427charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008428{
Christian Heimes217cfd12007-12-02 14:31:20 +00008429 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008430 PyObject *x;
8431
8432 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008433 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008434 x = PyObject_GetItem(mapping, w);
8435 Py_DECREF(w);
8436 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8438 /* No mapping found means: use 1:1 mapping. */
8439 PyErr_Clear();
8440 *result = NULL;
8441 return 0;
8442 } else
8443 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008444 }
8445 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008446 *result = x;
8447 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008448 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008449 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008450 long value = PyLong_AS_LONG(x);
8451 long max = PyUnicode_GetMax();
8452 if (value < 0 || value > max) {
8453 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008454 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008455 Py_DECREF(x);
8456 return -1;
8457 }
8458 *result = x;
8459 return 0;
8460 }
8461 else if (PyUnicode_Check(x)) {
8462 *result = x;
8463 return 0;
8464 }
8465 else {
8466 /* wrong return value */
8467 PyErr_SetString(PyExc_TypeError,
8468 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008469 Py_DECREF(x);
8470 return -1;
8471 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008472}
8473/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008474 if not reallocate and adjust various state variables.
8475 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008476static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008477charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008478 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008479{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008480 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008481 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008482 /* exponentially overallocate to minimize reallocations */
8483 if (requiredsize < 2 * oldsize)
8484 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008485 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8486 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008488 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008489 }
8490 return 0;
8491}
8492/* lookup the character, put the result in the output string and adjust
8493 various state variables. Return a new reference to the object that
8494 was put in the output buffer in *result, or Py_None, if the mapping was
8495 undefined (in which case no character was written).
8496 The called must decref result.
8497 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008498static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008499charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8500 PyObject *mapping, Py_UCS4 **output,
8501 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008502 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008503{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008504 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8505 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008506 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008507 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008508 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008509 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008510 }
8511 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008512 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008513 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008514 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008515 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008516 }
8517 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008518 Py_ssize_t repsize;
8519 if (PyUnicode_READY(*res) == -1)
8520 return -1;
8521 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008522 if (repsize==1) {
8523 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008524 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008525 }
8526 else if (repsize!=0) {
8527 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008528 Py_ssize_t requiredsize = *opos +
8529 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008530 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008531 Py_ssize_t i;
8532 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008533 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008534 for(i = 0; i < repsize; i++)
8535 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008536 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008537 }
8538 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008539 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008540 return 0;
8541}
8542
Alexander Belopolsky40018472011-02-26 01:02:56 +00008543PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008544_PyUnicode_TranslateCharmap(PyObject *input,
8545 PyObject *mapping,
8546 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008547{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008548 /* input object */
8549 char *idata;
8550 Py_ssize_t size, i;
8551 int kind;
8552 /* output buffer */
8553 Py_UCS4 *output = NULL;
8554 Py_ssize_t osize;
8555 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008556 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008557 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008558 char *reason = "character maps to <undefined>";
8559 PyObject *errorHandler = NULL;
8560 PyObject *exc = NULL;
8561 /* the following variable is used for caching string comparisons
8562 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8563 * 3=ignore, 4=xmlcharrefreplace */
8564 int known_errorHandler = -1;
8565
Guido van Rossumd57fd912000-03-10 22:53:23 +00008566 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008567 PyErr_BadArgument();
8568 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008569 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008570
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008571 if (PyUnicode_READY(input) == -1)
8572 return NULL;
8573 idata = (char*)PyUnicode_DATA(input);
8574 kind = PyUnicode_KIND(input);
8575 size = PyUnicode_GET_LENGTH(input);
8576 i = 0;
8577
8578 if (size == 0) {
8579 Py_INCREF(input);
8580 return input;
8581 }
8582
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008583 /* allocate enough for a simple 1:1 translation without
8584 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008585 osize = size;
8586 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8587 opos = 0;
8588 if (output == NULL) {
8589 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008590 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008591 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008592
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008593 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008594 /* try to encode it */
8595 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008596 if (charmaptranslate_output(input, i, mapping,
8597 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008598 Py_XDECREF(x);
8599 goto onError;
8600 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008601 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008602 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008603 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008604 else { /* untranslatable character */
8605 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8606 Py_ssize_t repsize;
8607 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008608 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008609 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008610 Py_ssize_t collstart = i;
8611 Py_ssize_t collend = i+1;
8612 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008613
Benjamin Peterson29060642009-01-31 22:14:21 +00008614 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008615 while (collend < size) {
8616 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008617 goto onError;
8618 Py_XDECREF(x);
8619 if (x!=Py_None)
8620 break;
8621 ++collend;
8622 }
8623 /* cache callback name lookup
8624 * (if not done yet, i.e. it's the first error) */
8625 if (known_errorHandler==-1) {
8626 if ((errors==NULL) || (!strcmp(errors, "strict")))
8627 known_errorHandler = 1;
8628 else if (!strcmp(errors, "replace"))
8629 known_errorHandler = 2;
8630 else if (!strcmp(errors, "ignore"))
8631 known_errorHandler = 3;
8632 else if (!strcmp(errors, "xmlcharrefreplace"))
8633 known_errorHandler = 4;
8634 else
8635 known_errorHandler = 0;
8636 }
8637 switch (known_errorHandler) {
8638 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008639 raise_translate_exception(&exc, input, collstart,
8640 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008641 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008642 case 2: /* replace */
8643 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008644 for (coll = collstart; coll<collend; coll++)
8645 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008646 /* fall through */
8647 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008648 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008649 break;
8650 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008651 /* generate replacement (temporarily (mis)uses i) */
8652 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008653 char buffer[2+29+1+1];
8654 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008655 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8656 if (charmaptranslate_makespace(&output, &osize,
8657 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008658 goto onError;
8659 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008660 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008661 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008662 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008663 break;
8664 default:
8665 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008666 reason, input, &exc,
8667 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008668 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008669 goto onError;
8670 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008671 repsize = PyUnicode_GET_LENGTH(repunicode);
8672 if (charmaptranslate_makespace(&output, &osize,
8673 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008674 Py_DECREF(repunicode);
8675 goto onError;
8676 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008677 for (uni2 = 0; repsize-->0; ++uni2)
8678 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8679 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008680 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008681 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008682 }
8683 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008684 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8685 if (!res)
8686 goto onError;
8687 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008688 Py_XDECREF(exc);
8689 Py_XDECREF(errorHandler);
8690 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008691
Benjamin Peterson29060642009-01-31 22:14:21 +00008692 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008693 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008694 Py_XDECREF(exc);
8695 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008696 return NULL;
8697}
8698
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008699/* Deprecated. Use PyUnicode_Translate instead. */
8700PyObject *
8701PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8702 Py_ssize_t size,
8703 PyObject *mapping,
8704 const char *errors)
8705{
8706 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8707 if (!unicode)
8708 return NULL;
8709 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8710}
8711
Alexander Belopolsky40018472011-02-26 01:02:56 +00008712PyObject *
8713PyUnicode_Translate(PyObject *str,
8714 PyObject *mapping,
8715 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008716{
8717 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008718
Guido van Rossumd57fd912000-03-10 22:53:23 +00008719 str = PyUnicode_FromObject(str);
8720 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008721 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008722 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008723 Py_DECREF(str);
8724 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008725
Benjamin Peterson29060642009-01-31 22:14:21 +00008726 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008727 Py_XDECREF(str);
8728 return NULL;
8729}
Tim Petersced69f82003-09-16 20:30:58 +00008730
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008731static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008732fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008733{
8734 /* No need to call PyUnicode_READY(self) because this function is only
8735 called as a callback from fixup() which does it already. */
8736 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8737 const int kind = PyUnicode_KIND(self);
8738 void *data = PyUnicode_DATA(self);
8739 Py_UCS4 maxchar = 0, ch, fixed;
8740 Py_ssize_t i;
8741
8742 for (i = 0; i < len; ++i) {
8743 ch = PyUnicode_READ(kind, data, i);
8744 fixed = 0;
8745 if (ch > 127) {
8746 if (Py_UNICODE_ISSPACE(ch))
8747 fixed = ' ';
8748 else {
8749 const int decimal = Py_UNICODE_TODECIMAL(ch);
8750 if (decimal >= 0)
8751 fixed = '0' + decimal;
8752 }
8753 if (fixed != 0) {
8754 if (fixed > maxchar)
8755 maxchar = fixed;
8756 PyUnicode_WRITE(kind, data, i, fixed);
8757 }
8758 else if (ch > maxchar)
8759 maxchar = ch;
8760 }
8761 else if (ch > maxchar)
8762 maxchar = ch;
8763 }
8764
8765 return maxchar;
8766}
8767
8768PyObject *
8769_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8770{
8771 if (!PyUnicode_Check(unicode)) {
8772 PyErr_BadInternalCall();
8773 return NULL;
8774 }
8775 if (PyUnicode_READY(unicode) == -1)
8776 return NULL;
8777 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8778 /* If the string is already ASCII, just return the same string */
8779 Py_INCREF(unicode);
8780 return unicode;
8781 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008782 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008783}
8784
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008785PyObject *
8786PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8787 Py_ssize_t length)
8788{
8789 PyObject *result;
8790 Py_UNICODE *p; /* write pointer into result */
8791 Py_ssize_t i;
8792 /* Copy to a new string */
8793 result = (PyObject *)_PyUnicode_New(length);
8794 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8795 if (result == NULL)
8796 return result;
8797 p = PyUnicode_AS_UNICODE(result);
8798 /* Iterate over code points */
8799 for (i = 0; i < length; i++) {
8800 Py_UNICODE ch =s[i];
8801 if (ch > 127) {
8802 int decimal = Py_UNICODE_TODECIMAL(ch);
8803 if (decimal >= 0)
8804 p[i] = '0' + decimal;
8805 }
8806 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008807#ifndef DONT_MAKE_RESULT_READY
8808 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008809 Py_DECREF(result);
8810 return NULL;
8811 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008812#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008813 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008814 return result;
8815}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008816/* --- Decimal Encoder ---------------------------------------------------- */
8817
Alexander Belopolsky40018472011-02-26 01:02:56 +00008818int
8819PyUnicode_EncodeDecimal(Py_UNICODE *s,
8820 Py_ssize_t length,
8821 char *output,
8822 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008823{
8824 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008825 PyObject *errorHandler = NULL;
8826 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008827 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008828 const char *encoding = "decimal";
8829 const char *reason = "invalid decimal Unicode string";
8830 /* the following variable is used for caching string comparisons
8831 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8832 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008833
8834 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008835 PyErr_BadArgument();
8836 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008837 }
8838
8839 p = s;
8840 end = s + length;
8841 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008842 register Py_UNICODE ch = *p;
8843 int decimal;
8844 PyObject *repunicode;
8845 Py_ssize_t repsize;
8846 Py_ssize_t newpos;
8847 Py_UNICODE *uni2;
8848 Py_UNICODE *collstart;
8849 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008850
Benjamin Peterson29060642009-01-31 22:14:21 +00008851 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008852 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008853 ++p;
8854 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008855 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008856 decimal = Py_UNICODE_TODECIMAL(ch);
8857 if (decimal >= 0) {
8858 *output++ = '0' + decimal;
8859 ++p;
8860 continue;
8861 }
8862 if (0 < ch && ch < 256) {
8863 *output++ = (char)ch;
8864 ++p;
8865 continue;
8866 }
8867 /* All other characters are considered unencodable */
8868 collstart = p;
8869 collend = p+1;
8870 while (collend < end) {
8871 if ((0 < *collend && *collend < 256) ||
8872 !Py_UNICODE_ISSPACE(*collend) ||
8873 Py_UNICODE_TODECIMAL(*collend))
8874 break;
8875 }
8876 /* cache callback name lookup
8877 * (if not done yet, i.e. it's the first error) */
8878 if (known_errorHandler==-1) {
8879 if ((errors==NULL) || (!strcmp(errors, "strict")))
8880 known_errorHandler = 1;
8881 else if (!strcmp(errors, "replace"))
8882 known_errorHandler = 2;
8883 else if (!strcmp(errors, "ignore"))
8884 known_errorHandler = 3;
8885 else if (!strcmp(errors, "xmlcharrefreplace"))
8886 known_errorHandler = 4;
8887 else
8888 known_errorHandler = 0;
8889 }
8890 switch (known_errorHandler) {
8891 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008892 unicode = PyUnicode_FromUnicode(s, length);
8893 if (unicode == NULL)
8894 goto onError;
8895 raise_encode_exception(&exc, encoding, unicode, collstart-s, collend-s, reason);
8896 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008897 goto onError;
8898 case 2: /* replace */
8899 for (p = collstart; p < collend; ++p)
8900 *output++ = '?';
8901 /* fall through */
8902 case 3: /* ignore */
8903 p = collend;
8904 break;
8905 case 4: /* xmlcharrefreplace */
8906 /* generate replacement (temporarily (mis)uses p) */
8907 for (p = collstart; p < collend; ++p)
8908 output += sprintf(output, "&#%d;", (int)*p);
8909 p = collend;
8910 break;
8911 default:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008912 unicode = PyUnicode_FromUnicode(s, length);
8913 if (unicode == NULL)
8914 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008915 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008916 encoding, reason, unicode, &exc,
Benjamin Peterson29060642009-01-31 22:14:21 +00008917 collstart-s, collend-s, &newpos);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008918 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008919 if (repunicode == NULL)
8920 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008921 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008922 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008923 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8924 Py_DECREF(repunicode);
8925 goto onError;
8926 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008927 /* generate replacement */
8928 repsize = PyUnicode_GET_SIZE(repunicode);
8929 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8930 Py_UNICODE ch = *uni2;
8931 if (Py_UNICODE_ISSPACE(ch))
8932 *output++ = ' ';
8933 else {
8934 decimal = Py_UNICODE_TODECIMAL(ch);
8935 if (decimal >= 0)
8936 *output++ = '0' + decimal;
8937 else if (0 < ch && ch < 256)
8938 *output++ = (char)ch;
8939 else {
8940 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008941 unicode = PyUnicode_FromUnicode(s, length);
8942 if (unicode == NULL)
8943 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008944 raise_encode_exception(&exc, encoding,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008945 unicode, collstart-s, collend-s, reason);
8946 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008947 goto onError;
8948 }
8949 }
8950 }
8951 p = s + newpos;
8952 Py_DECREF(repunicode);
8953 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008954 }
8955 /* 0-terminate the output string */
8956 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008957 Py_XDECREF(exc);
8958 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008959 return 0;
8960
Benjamin Peterson29060642009-01-31 22:14:21 +00008961 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008962 Py_XDECREF(exc);
8963 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008964 return -1;
8965}
8966
Guido van Rossumd57fd912000-03-10 22:53:23 +00008967/* --- Helpers ------------------------------------------------------------ */
8968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008969static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008970any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008971 Py_ssize_t start,
8972 Py_ssize_t end)
8973{
8974 int kind1, kind2, kind;
8975 void *buf1, *buf2;
8976 Py_ssize_t len1, len2, result;
8977
8978 kind1 = PyUnicode_KIND(s1);
8979 kind2 = PyUnicode_KIND(s2);
8980 kind = kind1 > kind2 ? kind1 : kind2;
8981 buf1 = PyUnicode_DATA(s1);
8982 buf2 = PyUnicode_DATA(s2);
8983 if (kind1 != kind)
8984 buf1 = _PyUnicode_AsKind(s1, kind);
8985 if (!buf1)
8986 return -2;
8987 if (kind2 != kind)
8988 buf2 = _PyUnicode_AsKind(s2, kind);
8989 if (!buf2) {
8990 if (kind1 != kind) PyMem_Free(buf1);
8991 return -2;
8992 }
8993 len1 = PyUnicode_GET_LENGTH(s1);
8994 len2 = PyUnicode_GET_LENGTH(s2);
8995
Victor Stinner794d5672011-10-10 03:21:36 +02008996 if (direction > 0) {
8997 switch(kind) {
8998 case PyUnicode_1BYTE_KIND:
8999 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9000 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9001 else
9002 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9003 break;
9004 case PyUnicode_2BYTE_KIND:
9005 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9006 break;
9007 case PyUnicode_4BYTE_KIND:
9008 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9009 break;
9010 default:
9011 assert(0); result = -2;
9012 }
9013 }
9014 else {
9015 switch(kind) {
9016 case PyUnicode_1BYTE_KIND:
9017 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9018 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9019 else
9020 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9021 break;
9022 case PyUnicode_2BYTE_KIND:
9023 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9024 break;
9025 case PyUnicode_4BYTE_KIND:
9026 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9027 break;
9028 default:
9029 assert(0); result = -2;
9030 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009031 }
9032
9033 if (kind1 != kind)
9034 PyMem_Free(buf1);
9035 if (kind2 != kind)
9036 PyMem_Free(buf2);
9037
9038 return result;
9039}
9040
9041Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009042_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009043 Py_ssize_t n_buffer,
9044 void *digits, Py_ssize_t n_digits,
9045 Py_ssize_t min_width,
9046 const char *grouping,
9047 const char *thousands_sep)
9048{
9049 switch(kind) {
9050 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009051 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9052 return _PyUnicode_ascii_InsertThousandsGrouping(
9053 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9054 min_width, grouping, thousands_sep);
9055 else
9056 return _PyUnicode_ucs1_InsertThousandsGrouping(
9057 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9058 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009059 case PyUnicode_2BYTE_KIND:
9060 return _PyUnicode_ucs2_InsertThousandsGrouping(
9061 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9062 min_width, grouping, thousands_sep);
9063 case PyUnicode_4BYTE_KIND:
9064 return _PyUnicode_ucs4_InsertThousandsGrouping(
9065 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9066 min_width, grouping, thousands_sep);
9067 }
9068 assert(0);
9069 return -1;
9070}
9071
9072
Thomas Wouters477c8d52006-05-27 19:21:47 +00009073/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009074#define ADJUST_INDICES(start, end, len) \
9075 if (end > len) \
9076 end = len; \
9077 else if (end < 0) { \
9078 end += len; \
9079 if (end < 0) \
9080 end = 0; \
9081 } \
9082 if (start < 0) { \
9083 start += len; \
9084 if (start < 0) \
9085 start = 0; \
9086 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009087
Alexander Belopolsky40018472011-02-26 01:02:56 +00009088Py_ssize_t
9089PyUnicode_Count(PyObject *str,
9090 PyObject *substr,
9091 Py_ssize_t start,
9092 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009093{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009094 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009095 PyObject* str_obj;
9096 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009097 int kind1, kind2, kind;
9098 void *buf1 = NULL, *buf2 = NULL;
9099 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009100
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009101 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009102 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009103 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009104 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009105 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009106 Py_DECREF(str_obj);
9107 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009108 }
Tim Petersced69f82003-09-16 20:30:58 +00009109
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009110 kind1 = PyUnicode_KIND(str_obj);
9111 kind2 = PyUnicode_KIND(sub_obj);
9112 kind = kind1 > kind2 ? kind1 : kind2;
9113 buf1 = PyUnicode_DATA(str_obj);
9114 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009115 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009116 if (!buf1)
9117 goto onError;
9118 buf2 = PyUnicode_DATA(sub_obj);
9119 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009120 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009121 if (!buf2)
9122 goto onError;
9123 len1 = PyUnicode_GET_LENGTH(str_obj);
9124 len2 = PyUnicode_GET_LENGTH(sub_obj);
9125
9126 ADJUST_INDICES(start, end, len1);
9127 switch(kind) {
9128 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009129 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9130 result = asciilib_count(
9131 ((Py_UCS1*)buf1) + start, end - start,
9132 buf2, len2, PY_SSIZE_T_MAX
9133 );
9134 else
9135 result = ucs1lib_count(
9136 ((Py_UCS1*)buf1) + start, end - start,
9137 buf2, len2, PY_SSIZE_T_MAX
9138 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009139 break;
9140 case PyUnicode_2BYTE_KIND:
9141 result = ucs2lib_count(
9142 ((Py_UCS2*)buf1) + start, end - start,
9143 buf2, len2, PY_SSIZE_T_MAX
9144 );
9145 break;
9146 case PyUnicode_4BYTE_KIND:
9147 result = ucs4lib_count(
9148 ((Py_UCS4*)buf1) + start, end - start,
9149 buf2, len2, PY_SSIZE_T_MAX
9150 );
9151 break;
9152 default:
9153 assert(0); result = 0;
9154 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009155
9156 Py_DECREF(sub_obj);
9157 Py_DECREF(str_obj);
9158
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009159 if (kind1 != kind)
9160 PyMem_Free(buf1);
9161 if (kind2 != kind)
9162 PyMem_Free(buf2);
9163
Guido van Rossumd57fd912000-03-10 22:53:23 +00009164 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009165 onError:
9166 Py_DECREF(sub_obj);
9167 Py_DECREF(str_obj);
9168 if (kind1 != kind && buf1)
9169 PyMem_Free(buf1);
9170 if (kind2 != kind && buf2)
9171 PyMem_Free(buf2);
9172 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009173}
9174
Alexander Belopolsky40018472011-02-26 01:02:56 +00009175Py_ssize_t
9176PyUnicode_Find(PyObject *str,
9177 PyObject *sub,
9178 Py_ssize_t start,
9179 Py_ssize_t end,
9180 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009181{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009182 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009183
Guido van Rossumd57fd912000-03-10 22:53:23 +00009184 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009185 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009186 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009187 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009188 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009189 Py_DECREF(str);
9190 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009191 }
Tim Petersced69f82003-09-16 20:30:58 +00009192
Victor Stinner794d5672011-10-10 03:21:36 +02009193 result = any_find_slice(direction,
9194 str, sub, start, end
9195 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009196
Guido van Rossumd57fd912000-03-10 22:53:23 +00009197 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009198 Py_DECREF(sub);
9199
Guido van Rossumd57fd912000-03-10 22:53:23 +00009200 return result;
9201}
9202
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009203Py_ssize_t
9204PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9205 Py_ssize_t start, Py_ssize_t end,
9206 int direction)
9207{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009208 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009209 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009210 if (PyUnicode_READY(str) == -1)
9211 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009212 if (start < 0 || end < 0) {
9213 PyErr_SetString(PyExc_IndexError, "string index out of range");
9214 return -2;
9215 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009216 if (end > PyUnicode_GET_LENGTH(str))
9217 end = PyUnicode_GET_LENGTH(str);
9218 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009219 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9220 kind, end-start, ch, direction);
9221 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009222 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009223 else
9224 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009225}
9226
Alexander Belopolsky40018472011-02-26 01:02:56 +00009227static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009228tailmatch(PyObject *self,
9229 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009230 Py_ssize_t start,
9231 Py_ssize_t end,
9232 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009233{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009234 int kind_self;
9235 int kind_sub;
9236 void *data_self;
9237 void *data_sub;
9238 Py_ssize_t offset;
9239 Py_ssize_t i;
9240 Py_ssize_t end_sub;
9241
9242 if (PyUnicode_READY(self) == -1 ||
9243 PyUnicode_READY(substring) == -1)
9244 return 0;
9245
9246 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009247 return 1;
9248
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009249 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9250 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009251 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009252 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009253
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009254 kind_self = PyUnicode_KIND(self);
9255 data_self = PyUnicode_DATA(self);
9256 kind_sub = PyUnicode_KIND(substring);
9257 data_sub = PyUnicode_DATA(substring);
9258 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9259
9260 if (direction > 0)
9261 offset = end;
9262 else
9263 offset = start;
9264
9265 if (PyUnicode_READ(kind_self, data_self, offset) ==
9266 PyUnicode_READ(kind_sub, data_sub, 0) &&
9267 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9268 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9269 /* If both are of the same kind, memcmp is sufficient */
9270 if (kind_self == kind_sub) {
9271 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009272 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009273 data_sub,
9274 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009275 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009276 }
9277 /* otherwise we have to compare each character by first accesing it */
9278 else {
9279 /* We do not need to compare 0 and len(substring)-1 because
9280 the if statement above ensured already that they are equal
9281 when we end up here. */
9282 // TODO: honor direction and do a forward or backwards search
9283 for (i = 1; i < end_sub; ++i) {
9284 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9285 PyUnicode_READ(kind_sub, data_sub, i))
9286 return 0;
9287 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009288 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009289 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009290 }
9291
9292 return 0;
9293}
9294
Alexander Belopolsky40018472011-02-26 01:02:56 +00009295Py_ssize_t
9296PyUnicode_Tailmatch(PyObject *str,
9297 PyObject *substr,
9298 Py_ssize_t start,
9299 Py_ssize_t end,
9300 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009301{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009302 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009303
Guido van Rossumd57fd912000-03-10 22:53:23 +00009304 str = PyUnicode_FromObject(str);
9305 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009306 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009307 substr = PyUnicode_FromObject(substr);
9308 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009309 Py_DECREF(str);
9310 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009311 }
Tim Petersced69f82003-09-16 20:30:58 +00009312
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009313 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009314 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009315 Py_DECREF(str);
9316 Py_DECREF(substr);
9317 return result;
9318}
9319
Guido van Rossumd57fd912000-03-10 22:53:23 +00009320/* Apply fixfct filter to the Unicode object self and return a
9321 reference to the modified object */
9322
Alexander Belopolsky40018472011-02-26 01:02:56 +00009323static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009324fixup(PyObject *self,
9325 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009326{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009327 PyObject *u;
9328 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009329
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009330 if (PyUnicode_READY(self) == -1)
9331 return NULL;
9332 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
9333 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
9334 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009335 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009336 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009337
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009338 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009339 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009340
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009341 /* fix functions return the new maximum character in a string,
9342 if the kind of the resulting unicode object does not change,
9343 everything is fine. Otherwise we need to change the string kind
9344 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009345 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009346 if (maxchar_new == 0)
9347 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9348 else if (maxchar_new <= 127)
9349 maxchar_new = 127;
9350 else if (maxchar_new <= 255)
9351 maxchar_new = 255;
9352 else if (maxchar_new <= 65535)
9353 maxchar_new = 65535;
9354 else
9355 maxchar_new = 1114111; /* 0x10ffff */
9356
9357 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009358 /* fixfct should return TRUE if it modified the buffer. If
9359 FALSE, return a reference to the original buffer instead
9360 (to save space, not time) */
9361 Py_INCREF(self);
9362 Py_DECREF(u);
Victor Stinner7931d9a2011-11-04 00:22:48 +01009363 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009364 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009365 else if (maxchar_new == maxchar_old) {
9366 return u;
9367 }
9368 else {
9369 /* In case the maximum character changed, we need to
9370 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009371 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009372 if (v == NULL) {
9373 Py_DECREF(u);
9374 return NULL;
9375 }
9376 if (maxchar_new > maxchar_old) {
9377 /* If the maxchar increased so that the kind changed, not all
9378 characters are representable anymore and we need to fix the
9379 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009380 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009381 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009382 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9383 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009384 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009385 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009386 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009387
9388 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009389 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009390 return v;
9391 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009392}
9393
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009394static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009395fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009396{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009397 /* No need to call PyUnicode_READY(self) because this function is only
9398 called as a callback from fixup() which does it already. */
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 up = Py_UNICODE_TOUPPER(ch);
9409 if (up != ch) {
9410 if (up > maxchar)
9411 maxchar = up;
9412 PyUnicode_WRITE(kind, data, i, up);
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 +02009426fixlower(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 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9439 if (lo != ch) {
9440 if (lo > maxchar)
9441 maxchar = lo;
9442 PyUnicode_WRITE(kind, data, i, lo);
9443 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009444 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009445 else if (ch > maxchar)
9446 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009447 }
9448
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009449 if (touched)
9450 return maxchar;
9451 else
9452 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009453}
9454
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009455static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009456fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009457{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009458 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9459 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9460 const int kind = PyUnicode_KIND(self);
9461 void *data = PyUnicode_DATA(self);
9462 int touched = 0;
9463 Py_UCS4 maxchar = 0;
9464 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009465
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009466 for(i = 0; i < len; ++i) {
9467 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9468 Py_UCS4 nu = 0;
9469
9470 if (Py_UNICODE_ISUPPER(ch))
9471 nu = Py_UNICODE_TOLOWER(ch);
9472 else if (Py_UNICODE_ISLOWER(ch))
9473 nu = Py_UNICODE_TOUPPER(ch);
9474
9475 if (nu != 0) {
9476 if (nu > maxchar)
9477 maxchar = nu;
9478 PyUnicode_WRITE(kind, data, i, nu);
9479 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009480 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009481 else if (ch > maxchar)
9482 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009483 }
9484
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009485 if (touched)
9486 return maxchar;
9487 else
9488 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009489}
9490
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009491static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009492fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009493{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009494 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9495 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9496 const int kind = PyUnicode_KIND(self);
9497 void *data = PyUnicode_DATA(self);
9498 int touched = 0;
9499 Py_UCS4 maxchar = 0;
9500 Py_ssize_t i = 0;
9501 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009502
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009503 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009504 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009505
9506 ch = PyUnicode_READ(kind, data, i);
9507 if (!Py_UNICODE_ISUPPER(ch)) {
9508 maxchar = Py_UNICODE_TOUPPER(ch);
9509 PyUnicode_WRITE(kind, data, i, maxchar);
9510 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009511 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009512 ++i;
9513 for(; i < len; ++i) {
9514 ch = PyUnicode_READ(kind, data, i);
9515 if (!Py_UNICODE_ISLOWER(ch)) {
9516 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9517 if (lo > maxchar)
9518 maxchar = lo;
9519 PyUnicode_WRITE(kind, data, i, lo);
9520 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009521 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009522 else if (ch > maxchar)
9523 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009524 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009525
9526 if (touched)
9527 return maxchar;
9528 else
9529 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009530}
9531
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009532static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009533fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009534{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009535 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9536 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9537 const int kind = PyUnicode_KIND(self);
9538 void *data = PyUnicode_DATA(self);
9539 Py_UCS4 maxchar = 0;
9540 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009541 int previous_is_cased;
9542
9543 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009544 if (len == 1) {
9545 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9546 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9547 if (ti != ch) {
9548 PyUnicode_WRITE(kind, data, i, ti);
9549 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009550 }
9551 else
9552 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009553 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009554 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009555 for(; i < len; ++i) {
9556 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9557 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009558
Benjamin Peterson29060642009-01-31 22:14:21 +00009559 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009560 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009561 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009562 nu = Py_UNICODE_TOTITLE(ch);
9563
9564 if (nu > maxchar)
9565 maxchar = nu;
9566 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009567
Benjamin Peterson29060642009-01-31 22:14:21 +00009568 if (Py_UNICODE_ISLOWER(ch) ||
9569 Py_UNICODE_ISUPPER(ch) ||
9570 Py_UNICODE_ISTITLE(ch))
9571 previous_is_cased = 1;
9572 else
9573 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009574 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009575 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009576}
9577
Tim Peters8ce9f162004-08-27 01:49:32 +00009578PyObject *
9579PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009580{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009581 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009582 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009583 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009584 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009585 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9586 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009587 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009588 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009589 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009590 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009591 int use_memcpy;
9592 unsigned char *res_data = NULL, *sep_data = NULL;
9593 PyObject *last_obj;
9594 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009595
Tim Peters05eba1f2004-08-27 21:32:02 +00009596 fseq = PySequence_Fast(seq, "");
9597 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009598 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009599 }
9600
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009601 /* NOTE: the following code can't call back into Python code,
9602 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009603 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009604
Tim Peters05eba1f2004-08-27 21:32:02 +00009605 seqlen = PySequence_Fast_GET_SIZE(fseq);
9606 /* If empty sequence, return u"". */
9607 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009608 Py_DECREF(fseq);
9609 Py_INCREF(unicode_empty);
9610 res = unicode_empty;
9611 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009612 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009613
Tim Peters05eba1f2004-08-27 21:32:02 +00009614 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009615 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009616 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009617 if (seqlen == 1) {
9618 if (PyUnicode_CheckExact(items[0])) {
9619 res = items[0];
9620 Py_INCREF(res);
9621 Py_DECREF(fseq);
9622 return res;
9623 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009624 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009625 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009626 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009627 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009628 /* Set up sep and seplen */
9629 if (separator == NULL) {
9630 /* fall back to a blank space separator */
9631 sep = PyUnicode_FromOrdinal(' ');
9632 if (!sep)
9633 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009634 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009635 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009636 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009637 else {
9638 if (!PyUnicode_Check(separator)) {
9639 PyErr_Format(PyExc_TypeError,
9640 "separator: expected str instance,"
9641 " %.80s found",
9642 Py_TYPE(separator)->tp_name);
9643 goto onError;
9644 }
9645 if (PyUnicode_READY(separator))
9646 goto onError;
9647 sep = separator;
9648 seplen = PyUnicode_GET_LENGTH(separator);
9649 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9650 /* inc refcount to keep this code path symmetric with the
9651 above case of a blank separator */
9652 Py_INCREF(sep);
9653 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009654 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009655 }
9656
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009657 /* There are at least two things to join, or else we have a subclass
9658 * of str in the sequence.
9659 * Do a pre-pass to figure out the total amount of space we'll
9660 * need (sz), and see whether all argument are strings.
9661 */
9662 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009663#ifdef Py_DEBUG
9664 use_memcpy = 0;
9665#else
9666 use_memcpy = 1;
9667#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009668 for (i = 0; i < seqlen; i++) {
9669 const Py_ssize_t old_sz = sz;
9670 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009671 if (!PyUnicode_Check(item)) {
9672 PyErr_Format(PyExc_TypeError,
9673 "sequence item %zd: expected str instance,"
9674 " %.80s found",
9675 i, Py_TYPE(item)->tp_name);
9676 goto onError;
9677 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009678 if (PyUnicode_READY(item) == -1)
9679 goto onError;
9680 sz += PyUnicode_GET_LENGTH(item);
9681 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009682 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009683 if (i != 0)
9684 sz += seplen;
9685 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9686 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009687 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009688 goto onError;
9689 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009690 if (use_memcpy && last_obj != NULL) {
9691 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9692 use_memcpy = 0;
9693 }
9694 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009695 }
Tim Petersced69f82003-09-16 20:30:58 +00009696
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009697 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009698 if (res == NULL)
9699 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009700
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009701 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009702#ifdef Py_DEBUG
9703 use_memcpy = 0;
9704#else
9705 if (use_memcpy) {
9706 res_data = PyUnicode_1BYTE_DATA(res);
9707 kind = PyUnicode_KIND(res);
9708 if (seplen != 0)
9709 sep_data = PyUnicode_1BYTE_DATA(sep);
9710 }
9711#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009712 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009713 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009714 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009715 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009716 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009717 if (use_memcpy) {
9718 Py_MEMCPY(res_data,
9719 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009720 kind * seplen);
9721 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009722 }
9723 else {
9724 copy_characters(res, res_offset, sep, 0, seplen);
9725 res_offset += seplen;
9726 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009727 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009728 itemlen = PyUnicode_GET_LENGTH(item);
9729 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009730 if (use_memcpy) {
9731 Py_MEMCPY(res_data,
9732 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009733 kind * itemlen);
9734 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009735 }
9736 else {
9737 copy_characters(res, res_offset, item, 0, itemlen);
9738 res_offset += itemlen;
9739 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009740 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009741 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009742 if (use_memcpy)
9743 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009744 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009745 else
9746 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009747
Tim Peters05eba1f2004-08-27 21:32:02 +00009748 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009749 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009750 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009751 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009752
Benjamin Peterson29060642009-01-31 22:14:21 +00009753 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009754 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009755 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009756 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009757 return NULL;
9758}
9759
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009760#define FILL(kind, data, value, start, length) \
9761 do { \
9762 Py_ssize_t i_ = 0; \
9763 assert(kind != PyUnicode_WCHAR_KIND); \
9764 switch ((kind)) { \
9765 case PyUnicode_1BYTE_KIND: { \
9766 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9767 memset(to_, (unsigned char)value, length); \
9768 break; \
9769 } \
9770 case PyUnicode_2BYTE_KIND: { \
9771 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9772 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9773 break; \
9774 } \
9775 default: { \
9776 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9777 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9778 break; \
9779 } \
9780 } \
9781 } while (0)
9782
Victor Stinner9310abb2011-10-05 00:59:23 +02009783static PyObject *
9784pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009785 Py_ssize_t left,
9786 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009787 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009788{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009789 PyObject *u;
9790 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009791 int kind;
9792 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009793
9794 if (left < 0)
9795 left = 0;
9796 if (right < 0)
9797 right = 0;
9798
Tim Peters7a29bd52001-09-12 03:03:31 +00009799 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009800 Py_INCREF(self);
9801 return self;
9802 }
9803
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009804 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9805 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009806 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9807 return NULL;
9808 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009809 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9810 if (fill > maxchar)
9811 maxchar = fill;
9812 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009813 if (!u)
9814 return NULL;
9815
9816 kind = PyUnicode_KIND(u);
9817 data = PyUnicode_DATA(u);
9818 if (left)
9819 FILL(kind, data, fill, 0, left);
9820 if (right)
9821 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009822 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009823 assert(_PyUnicode_CheckConsistency(u, 1));
9824 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009825}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009826#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009827
Alexander Belopolsky40018472011-02-26 01:02:56 +00009828PyObject *
9829PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009830{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009831 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009832
9833 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009834 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009835 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009836
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009837 switch(PyUnicode_KIND(string)) {
9838 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009839 if (PyUnicode_IS_ASCII(string))
9840 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009841 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009842 PyUnicode_GET_LENGTH(string), keepends);
9843 else
9844 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009845 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009846 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009847 break;
9848 case PyUnicode_2BYTE_KIND:
9849 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009850 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009851 PyUnicode_GET_LENGTH(string), keepends);
9852 break;
9853 case PyUnicode_4BYTE_KIND:
9854 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009855 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009856 PyUnicode_GET_LENGTH(string), keepends);
9857 break;
9858 default:
9859 assert(0);
9860 list = 0;
9861 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009862 Py_DECREF(string);
9863 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009864}
9865
Alexander Belopolsky40018472011-02-26 01:02:56 +00009866static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009867split(PyObject *self,
9868 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009869 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009870{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009871 int kind1, kind2, kind;
9872 void *buf1, *buf2;
9873 Py_ssize_t len1, len2;
9874 PyObject* out;
9875
Guido van Rossumd57fd912000-03-10 22:53:23 +00009876 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009877 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009878
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009879 if (PyUnicode_READY(self) == -1)
9880 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009881
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009882 if (substring == NULL)
9883 switch(PyUnicode_KIND(self)) {
9884 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009885 if (PyUnicode_IS_ASCII(self))
9886 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009887 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009888 PyUnicode_GET_LENGTH(self), maxcount
9889 );
9890 else
9891 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009892 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009893 PyUnicode_GET_LENGTH(self), maxcount
9894 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009895 case PyUnicode_2BYTE_KIND:
9896 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009897 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009898 PyUnicode_GET_LENGTH(self), maxcount
9899 );
9900 case PyUnicode_4BYTE_KIND:
9901 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009902 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009903 PyUnicode_GET_LENGTH(self), maxcount
9904 );
9905 default:
9906 assert(0);
9907 return NULL;
9908 }
9909
9910 if (PyUnicode_READY(substring) == -1)
9911 return NULL;
9912
9913 kind1 = PyUnicode_KIND(self);
9914 kind2 = PyUnicode_KIND(substring);
9915 kind = kind1 > kind2 ? kind1 : kind2;
9916 buf1 = PyUnicode_DATA(self);
9917 buf2 = PyUnicode_DATA(substring);
9918 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009919 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009920 if (!buf1)
9921 return NULL;
9922 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009923 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009924 if (!buf2) {
9925 if (kind1 != kind) PyMem_Free(buf1);
9926 return NULL;
9927 }
9928 len1 = PyUnicode_GET_LENGTH(self);
9929 len2 = PyUnicode_GET_LENGTH(substring);
9930
9931 switch(kind) {
9932 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009933 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9934 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009935 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009936 else
9937 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009938 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009939 break;
9940 case PyUnicode_2BYTE_KIND:
9941 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009942 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009943 break;
9944 case PyUnicode_4BYTE_KIND:
9945 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009946 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009947 break;
9948 default:
9949 out = NULL;
9950 }
9951 if (kind1 != kind)
9952 PyMem_Free(buf1);
9953 if (kind2 != kind)
9954 PyMem_Free(buf2);
9955 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009956}
9957
Alexander Belopolsky40018472011-02-26 01:02:56 +00009958static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009959rsplit(PyObject *self,
9960 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009961 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009962{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009963 int kind1, kind2, kind;
9964 void *buf1, *buf2;
9965 Py_ssize_t len1, len2;
9966 PyObject* out;
9967
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009968 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009969 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009970
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009971 if (PyUnicode_READY(self) == -1)
9972 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009973
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009974 if (substring == NULL)
9975 switch(PyUnicode_KIND(self)) {
9976 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009977 if (PyUnicode_IS_ASCII(self))
9978 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009979 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009980 PyUnicode_GET_LENGTH(self), maxcount
9981 );
9982 else
9983 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009984 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009985 PyUnicode_GET_LENGTH(self), maxcount
9986 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009987 case PyUnicode_2BYTE_KIND:
9988 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009989 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009990 PyUnicode_GET_LENGTH(self), maxcount
9991 );
9992 case PyUnicode_4BYTE_KIND:
9993 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009994 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009995 PyUnicode_GET_LENGTH(self), maxcount
9996 );
9997 default:
9998 assert(0);
9999 return NULL;
10000 }
10001
10002 if (PyUnicode_READY(substring) == -1)
10003 return NULL;
10004
10005 kind1 = PyUnicode_KIND(self);
10006 kind2 = PyUnicode_KIND(substring);
10007 kind = kind1 > kind2 ? kind1 : kind2;
10008 buf1 = PyUnicode_DATA(self);
10009 buf2 = PyUnicode_DATA(substring);
10010 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010011 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010012 if (!buf1)
10013 return NULL;
10014 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010015 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010016 if (!buf2) {
10017 if (kind1 != kind) PyMem_Free(buf1);
10018 return NULL;
10019 }
10020 len1 = PyUnicode_GET_LENGTH(self);
10021 len2 = PyUnicode_GET_LENGTH(substring);
10022
10023 switch(kind) {
10024 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010025 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10026 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010027 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010028 else
10029 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010030 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010031 break;
10032 case PyUnicode_2BYTE_KIND:
10033 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010034 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010035 break;
10036 case PyUnicode_4BYTE_KIND:
10037 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010038 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010039 break;
10040 default:
10041 out = NULL;
10042 }
10043 if (kind1 != kind)
10044 PyMem_Free(buf1);
10045 if (kind2 != kind)
10046 PyMem_Free(buf2);
10047 return out;
10048}
10049
10050static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010051anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10052 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010053{
10054 switch(kind) {
10055 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010056 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10057 return asciilib_find(buf1, len1, buf2, len2, offset);
10058 else
10059 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010060 case PyUnicode_2BYTE_KIND:
10061 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10062 case PyUnicode_4BYTE_KIND:
10063 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10064 }
10065 assert(0);
10066 return -1;
10067}
10068
10069static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010070anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10071 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010072{
10073 switch(kind) {
10074 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010075 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10076 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10077 else
10078 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010079 case PyUnicode_2BYTE_KIND:
10080 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10081 case PyUnicode_4BYTE_KIND:
10082 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10083 }
10084 assert(0);
10085 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010086}
10087
Alexander Belopolsky40018472011-02-26 01:02:56 +000010088static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089replace(PyObject *self, PyObject *str1,
10090 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010091{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010092 PyObject *u;
10093 char *sbuf = PyUnicode_DATA(self);
10094 char *buf1 = PyUnicode_DATA(str1);
10095 char *buf2 = PyUnicode_DATA(str2);
10096 int srelease = 0, release1 = 0, release2 = 0;
10097 int skind = PyUnicode_KIND(self);
10098 int kind1 = PyUnicode_KIND(str1);
10099 int kind2 = PyUnicode_KIND(str2);
10100 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10101 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10102 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010103 int mayshrink;
10104 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010105
10106 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010107 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010109 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010110
Victor Stinner59de0ee2011-10-07 10:01:28 +020010111 if (str1 == str2)
10112 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010113 if (skind < kind1)
10114 /* substring too wide to be present */
10115 goto nothing;
10116
Victor Stinner49a0a212011-10-12 23:46:10 +020010117 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10118 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10119 /* Replacing str1 with str2 may cause a maxchar reduction in the
10120 result string. */
10121 mayshrink = (maxchar_str2 < maxchar);
10122 maxchar = Py_MAX(maxchar, maxchar_str2);
10123
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010124 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010125 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010126 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010127 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010128 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010129 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010130 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010131 Py_UCS4 u1, u2;
10132 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010133 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010134 if (findchar(sbuf, PyUnicode_KIND(self),
10135 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010136 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010137 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010139 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010141 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010142 rkind = PyUnicode_KIND(u);
10143 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10144 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010145 if (--maxcount < 0)
10146 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010148 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010149 }
10150 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 int rkind = skind;
10152 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010153
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 if (kind1 < rkind) {
10155 /* widen substring */
10156 buf1 = _PyUnicode_AsKind(str1, rkind);
10157 if (!buf1) goto error;
10158 release1 = 1;
10159 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010160 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010161 if (i < 0)
10162 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 if (rkind > kind2) {
10164 /* widen replacement */
10165 buf2 = _PyUnicode_AsKind(str2, rkind);
10166 if (!buf2) goto error;
10167 release2 = 1;
10168 }
10169 else if (rkind < kind2) {
10170 /* widen self and buf1 */
10171 rkind = kind2;
10172 if (release1) PyMem_Free(buf1);
10173 sbuf = _PyUnicode_AsKind(self, rkind);
10174 if (!sbuf) goto error;
10175 srelease = 1;
10176 buf1 = _PyUnicode_AsKind(str1, rkind);
10177 if (!buf1) goto error;
10178 release1 = 1;
10179 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010180 u = PyUnicode_New(slen, maxchar);
10181 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010182 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010183 assert(PyUnicode_KIND(u) == rkind);
10184 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010185
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010186 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010187 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010188 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010189 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010190 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010192
10193 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010194 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010195 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010196 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010197 if (i == -1)
10198 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010199 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010200 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010201 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010202 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010203 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010204 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010205 }
10206 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207 Py_ssize_t n, i, j, ires;
10208 Py_ssize_t product, new_size;
10209 int rkind = skind;
10210 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010211
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010212 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010213 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010214 buf1 = _PyUnicode_AsKind(str1, rkind);
10215 if (!buf1) goto error;
10216 release1 = 1;
10217 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010218 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010219 if (n == 0)
10220 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010221 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010222 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010223 buf2 = _PyUnicode_AsKind(str2, rkind);
10224 if (!buf2) goto error;
10225 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010226 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010227 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010228 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 rkind = kind2;
10230 sbuf = _PyUnicode_AsKind(self, rkind);
10231 if (!sbuf) goto error;
10232 srelease = 1;
10233 if (release1) PyMem_Free(buf1);
10234 buf1 = _PyUnicode_AsKind(str1, rkind);
10235 if (!buf1) goto error;
10236 release1 = 1;
10237 }
10238 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10239 PyUnicode_GET_LENGTH(str1))); */
10240 product = n * (len2-len1);
10241 if ((product / (len2-len1)) != n) {
10242 PyErr_SetString(PyExc_OverflowError,
10243 "replace string is too long");
10244 goto error;
10245 }
10246 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010247 if (new_size == 0) {
10248 Py_INCREF(unicode_empty);
10249 u = unicode_empty;
10250 goto done;
10251 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010252 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10253 PyErr_SetString(PyExc_OverflowError,
10254 "replace string is too long");
10255 goto error;
10256 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010257 u = PyUnicode_New(new_size, maxchar);
10258 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010259 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010260 assert(PyUnicode_KIND(u) == rkind);
10261 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010262 ires = i = 0;
10263 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010264 while (n-- > 0) {
10265 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010266 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010267 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010268 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010269 if (j == -1)
10270 break;
10271 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010272 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010273 memcpy(res + rkind * ires,
10274 sbuf + rkind * i,
10275 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010276 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010277 }
10278 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010279 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010280 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010282 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010283 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010284 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010286 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010288 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010289 memcpy(res + rkind * ires,
10290 sbuf + rkind * i,
10291 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010292 }
10293 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010294 /* interleave */
10295 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010296 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010297 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010298 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010300 if (--n <= 0)
10301 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010302 memcpy(res + rkind * ires,
10303 sbuf + rkind * i,
10304 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 ires++;
10306 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010307 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010308 memcpy(res + rkind * ires,
10309 sbuf + rkind * i,
10310 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010311 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010312 }
10313
10314 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010315 unicode_adjust_maxchar(&u);
10316 if (u == NULL)
10317 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010318 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010319
10320 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010321 if (srelease)
10322 PyMem_FREE(sbuf);
10323 if (release1)
10324 PyMem_FREE(buf1);
10325 if (release2)
10326 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010327 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010328 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010329
Benjamin Peterson29060642009-01-31 22:14:21 +000010330 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010331 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010332 if (srelease)
10333 PyMem_FREE(sbuf);
10334 if (release1)
10335 PyMem_FREE(buf1);
10336 if (release2)
10337 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010338 if (PyUnicode_CheckExact(self)) {
10339 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010340 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010341 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010342 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010343 error:
10344 if (srelease && sbuf)
10345 PyMem_FREE(sbuf);
10346 if (release1 && buf1)
10347 PyMem_FREE(buf1);
10348 if (release2 && buf2)
10349 PyMem_FREE(buf2);
10350 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010351}
10352
10353/* --- Unicode Object Methods --------------------------------------------- */
10354
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010355PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010356 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010357\n\
10358Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010359characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010360
10361static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010362unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010363{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010364 return fixup(self, fixtitle);
10365}
10366
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010367PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010368 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010369\n\
10370Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010371have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010372
10373static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010374unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010375{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010376 return fixup(self, fixcapitalize);
10377}
10378
10379#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010380PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010381 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010382\n\
10383Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010384normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010385
10386static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010387unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010388{
10389 PyObject *list;
10390 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010391 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010392
Guido van Rossumd57fd912000-03-10 22:53:23 +000010393 /* Split into words */
10394 list = split(self, NULL, -1);
10395 if (!list)
10396 return NULL;
10397
10398 /* Capitalize each word */
10399 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010400 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010401 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010402 if (item == NULL)
10403 goto onError;
10404 Py_DECREF(PyList_GET_ITEM(list, i));
10405 PyList_SET_ITEM(list, i, item);
10406 }
10407
10408 /* Join the words to form a new string */
10409 item = PyUnicode_Join(NULL, list);
10410
Benjamin Peterson29060642009-01-31 22:14:21 +000010411 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010412 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010413 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010414}
10415#endif
10416
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010417/* Argument converter. Coerces to a single unicode character */
10418
10419static int
10420convert_uc(PyObject *obj, void *addr)
10421{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010422 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010423 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010424
Benjamin Peterson14339b62009-01-31 16:36:08 +000010425 uniobj = PyUnicode_FromObject(obj);
10426 if (uniobj == NULL) {
10427 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010428 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010429 return 0;
10430 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010431 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010432 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010433 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010434 Py_DECREF(uniobj);
10435 return 0;
10436 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010437 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010438 Py_DECREF(uniobj);
10439 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010440}
10441
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010442PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010443 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010444\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010445Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010446done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010447
10448static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010449unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010450{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010451 Py_ssize_t marg, left;
10452 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010453 Py_UCS4 fillchar = ' ';
10454
Victor Stinnere9a29352011-10-01 02:14:59 +020010455 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010456 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010457
Victor Stinnere9a29352011-10-01 02:14:59 +020010458 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010459 return NULL;
10460
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010461 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010462 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010463 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010464 }
10465
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010466 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010467 left = marg / 2 + (marg & width & 1);
10468
Victor Stinner9310abb2011-10-05 00:59:23 +020010469 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010470}
10471
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010472/* This function assumes that str1 and str2 are readied by the caller. */
10473
Marc-André Lemburge5034372000-08-08 08:04:29 +000010474static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010475unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010476{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010477 int kind1, kind2;
10478 void *data1, *data2;
10479 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010480
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010481 kind1 = PyUnicode_KIND(str1);
10482 kind2 = PyUnicode_KIND(str2);
10483 data1 = PyUnicode_DATA(str1);
10484 data2 = PyUnicode_DATA(str2);
10485 len1 = PyUnicode_GET_LENGTH(str1);
10486 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010487
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010488 for (i = 0; i < len1 && i < len2; ++i) {
10489 Py_UCS4 c1, c2;
10490 c1 = PyUnicode_READ(kind1, data1, i);
10491 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010492
10493 if (c1 != c2)
10494 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010495 }
10496
10497 return (len1 < len2) ? -1 : (len1 != len2);
10498}
10499
Alexander Belopolsky40018472011-02-26 01:02:56 +000010500int
10501PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010502{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010503 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10504 if (PyUnicode_READY(left) == -1 ||
10505 PyUnicode_READY(right) == -1)
10506 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010507 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010508 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010509 PyErr_Format(PyExc_TypeError,
10510 "Can't compare %.100s and %.100s",
10511 left->ob_type->tp_name,
10512 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010513 return -1;
10514}
10515
Martin v. Löwis5b222132007-06-10 09:51:05 +000010516int
10517PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10518{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010519 Py_ssize_t i;
10520 int kind;
10521 void *data;
10522 Py_UCS4 chr;
10523
Victor Stinner910337b2011-10-03 03:20:16 +020010524 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010525 if (PyUnicode_READY(uni) == -1)
10526 return -1;
10527 kind = PyUnicode_KIND(uni);
10528 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010529 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010530 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10531 if (chr != str[i])
10532 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010533 /* This check keeps Python strings that end in '\0' from comparing equal
10534 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010535 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010536 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010537 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010538 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010539 return 0;
10540}
10541
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010542
Benjamin Peterson29060642009-01-31 22:14:21 +000010543#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010544 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010545
Alexander Belopolsky40018472011-02-26 01:02:56 +000010546PyObject *
10547PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010548{
10549 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010550
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010551 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10552 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010553 if (PyUnicode_READY(left) == -1 ||
10554 PyUnicode_READY(right) == -1)
10555 return NULL;
10556 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10557 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010558 if (op == Py_EQ) {
10559 Py_INCREF(Py_False);
10560 return Py_False;
10561 }
10562 if (op == Py_NE) {
10563 Py_INCREF(Py_True);
10564 return Py_True;
10565 }
10566 }
10567 if (left == right)
10568 result = 0;
10569 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010570 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010571
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010572 /* Convert the return value to a Boolean */
10573 switch (op) {
10574 case Py_EQ:
10575 v = TEST_COND(result == 0);
10576 break;
10577 case Py_NE:
10578 v = TEST_COND(result != 0);
10579 break;
10580 case Py_LE:
10581 v = TEST_COND(result <= 0);
10582 break;
10583 case Py_GE:
10584 v = TEST_COND(result >= 0);
10585 break;
10586 case Py_LT:
10587 v = TEST_COND(result == -1);
10588 break;
10589 case Py_GT:
10590 v = TEST_COND(result == 1);
10591 break;
10592 default:
10593 PyErr_BadArgument();
10594 return NULL;
10595 }
10596 Py_INCREF(v);
10597 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010598 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010599
Brian Curtindfc80e32011-08-10 20:28:54 -050010600 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010601}
10602
Alexander Belopolsky40018472011-02-26 01:02:56 +000010603int
10604PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010605{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010606 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010607 int kind1, kind2, kind;
10608 void *buf1, *buf2;
10609 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010610 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010611
10612 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010613 sub = PyUnicode_FromObject(element);
10614 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010615 PyErr_Format(PyExc_TypeError,
10616 "'in <string>' requires string as left operand, not %s",
10617 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010618 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010619 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010620 if (PyUnicode_READY(sub) == -1)
10621 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010622
Thomas Wouters477c8d52006-05-27 19:21:47 +000010623 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010624 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010625 Py_DECREF(sub);
10626 return -1;
10627 }
10628
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010629 kind1 = PyUnicode_KIND(str);
10630 kind2 = PyUnicode_KIND(sub);
10631 kind = kind1 > kind2 ? kind1 : kind2;
10632 buf1 = PyUnicode_DATA(str);
10633 buf2 = PyUnicode_DATA(sub);
10634 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010635 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010636 if (!buf1) {
10637 Py_DECREF(sub);
10638 return -1;
10639 }
10640 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010641 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010642 if (!buf2) {
10643 Py_DECREF(sub);
10644 if (kind1 != kind) PyMem_Free(buf1);
10645 return -1;
10646 }
10647 len1 = PyUnicode_GET_LENGTH(str);
10648 len2 = PyUnicode_GET_LENGTH(sub);
10649
10650 switch(kind) {
10651 case PyUnicode_1BYTE_KIND:
10652 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10653 break;
10654 case PyUnicode_2BYTE_KIND:
10655 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10656 break;
10657 case PyUnicode_4BYTE_KIND:
10658 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10659 break;
10660 default:
10661 result = -1;
10662 assert(0);
10663 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010664
10665 Py_DECREF(str);
10666 Py_DECREF(sub);
10667
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010668 if (kind1 != kind)
10669 PyMem_Free(buf1);
10670 if (kind2 != kind)
10671 PyMem_Free(buf2);
10672
Guido van Rossum403d68b2000-03-13 15:55:09 +000010673 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010674}
10675
Guido van Rossumd57fd912000-03-10 22:53:23 +000010676/* Concat to string or Unicode object giving a new Unicode object. */
10677
Alexander Belopolsky40018472011-02-26 01:02:56 +000010678PyObject *
10679PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010680{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010681 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010682 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010683
10684 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010685 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010686 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010687 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010688 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010689 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010690 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010691
10692 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010693 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010694 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010695 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010696 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010697 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010698 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010699 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010700 }
10701
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010702 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010703 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10704 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010705
Guido van Rossumd57fd912000-03-10 22:53:23 +000010706 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010707 w = PyUnicode_New(
10708 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10709 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010710 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010711 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010712 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10713 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010714 Py_DECREF(u);
10715 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010716 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010717 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010718
Benjamin Peterson29060642009-01-31 22:14:21 +000010719 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010720 Py_XDECREF(u);
10721 Py_XDECREF(v);
10722 return NULL;
10723}
10724
Victor Stinnerb0923652011-10-04 01:17:31 +020010725static void
10726unicode_append_inplace(PyObject **p_left, PyObject *right)
10727{
10728 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010729
10730 assert(PyUnicode_IS_READY(*p_left));
10731 assert(PyUnicode_IS_READY(right));
10732
10733 left_len = PyUnicode_GET_LENGTH(*p_left);
10734 right_len = PyUnicode_GET_LENGTH(right);
10735 if (left_len > PY_SSIZE_T_MAX - right_len) {
10736 PyErr_SetString(PyExc_OverflowError,
10737 "strings are too large to concat");
10738 goto error;
10739 }
10740 new_len = left_len + right_len;
10741
10742 /* Now we own the last reference to 'left', so we can resize it
10743 * in-place.
10744 */
10745 if (unicode_resize(p_left, new_len) != 0) {
10746 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10747 * deallocated so it cannot be put back into
10748 * 'variable'. The MemoryError is raised when there
10749 * is no value in 'variable', which might (very
10750 * remotely) be a cause of incompatibilities.
10751 */
10752 goto error;
10753 }
10754 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010755 copy_characters(*p_left, left_len, right, 0, right_len);
10756 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010757 return;
10758
10759error:
10760 Py_DECREF(*p_left);
10761 *p_left = NULL;
10762}
10763
Walter Dörwald1ab83302007-05-18 17:15:44 +000010764void
Victor Stinner23e56682011-10-03 03:54:37 +020010765PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010766{
Victor Stinner23e56682011-10-03 03:54:37 +020010767 PyObject *left, *res;
10768
10769 if (p_left == NULL) {
10770 if (!PyErr_Occurred())
10771 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010772 return;
10773 }
Victor Stinner23e56682011-10-03 03:54:37 +020010774 left = *p_left;
10775 if (right == NULL || !PyUnicode_Check(left)) {
10776 if (!PyErr_Occurred())
10777 PyErr_BadInternalCall();
10778 goto error;
10779 }
10780
Victor Stinnere1335c72011-10-04 20:53:03 +020010781 if (PyUnicode_READY(left))
10782 goto error;
10783 if (PyUnicode_READY(right))
10784 goto error;
10785
Victor Stinner23e56682011-10-03 03:54:37 +020010786 if (PyUnicode_CheckExact(left) && left != unicode_empty
10787 && PyUnicode_CheckExact(right) && right != unicode_empty
10788 && unicode_resizable(left)
10789 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10790 || _PyUnicode_WSTR(left) != NULL))
10791 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010792 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10793 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010794 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010795 not so different than duplicating the string. */
10796 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010797 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010798 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010799 if (p_left != NULL)
10800 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010801 return;
10802 }
10803 }
10804
10805 res = PyUnicode_Concat(left, right);
10806 if (res == NULL)
10807 goto error;
10808 Py_DECREF(left);
10809 *p_left = res;
10810 return;
10811
10812error:
10813 Py_DECREF(*p_left);
10814 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010815}
10816
10817void
10818PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10819{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010820 PyUnicode_Append(pleft, right);
10821 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010822}
10823
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010824PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010825 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010826\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010827Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010828string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010829interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010830
10831static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010832unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010833{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010834 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010835 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010836 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010837 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010838 int kind1, kind2, kind;
10839 void *buf1, *buf2;
10840 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010841
Jesus Ceaac451502011-04-20 17:09:23 +020010842 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10843 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010844 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010845
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010846 kind1 = PyUnicode_KIND(self);
10847 kind2 = PyUnicode_KIND(substring);
10848 kind = kind1 > kind2 ? kind1 : kind2;
10849 buf1 = PyUnicode_DATA(self);
10850 buf2 = PyUnicode_DATA(substring);
10851 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010852 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010853 if (!buf1) {
10854 Py_DECREF(substring);
10855 return NULL;
10856 }
10857 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010858 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010859 if (!buf2) {
10860 Py_DECREF(substring);
10861 if (kind1 != kind) PyMem_Free(buf1);
10862 return NULL;
10863 }
10864 len1 = PyUnicode_GET_LENGTH(self);
10865 len2 = PyUnicode_GET_LENGTH(substring);
10866
10867 ADJUST_INDICES(start, end, len1);
10868 switch(kind) {
10869 case PyUnicode_1BYTE_KIND:
10870 iresult = ucs1lib_count(
10871 ((Py_UCS1*)buf1) + start, end - start,
10872 buf2, len2, PY_SSIZE_T_MAX
10873 );
10874 break;
10875 case PyUnicode_2BYTE_KIND:
10876 iresult = ucs2lib_count(
10877 ((Py_UCS2*)buf1) + start, end - start,
10878 buf2, len2, PY_SSIZE_T_MAX
10879 );
10880 break;
10881 case PyUnicode_4BYTE_KIND:
10882 iresult = ucs4lib_count(
10883 ((Py_UCS4*)buf1) + start, end - start,
10884 buf2, len2, PY_SSIZE_T_MAX
10885 );
10886 break;
10887 default:
10888 assert(0); iresult = 0;
10889 }
10890
10891 result = PyLong_FromSsize_t(iresult);
10892
10893 if (kind1 != kind)
10894 PyMem_Free(buf1);
10895 if (kind2 != kind)
10896 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010897
10898 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010899
Guido van Rossumd57fd912000-03-10 22:53:23 +000010900 return result;
10901}
10902
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010903PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010904 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010905\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010906Encode S using the codec registered for encoding. Default encoding\n\
10907is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010908handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010909a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10910'xmlcharrefreplace' as well as any other name registered with\n\
10911codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010912
10913static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010914unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010915{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010916 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010917 char *encoding = NULL;
10918 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010919
Benjamin Peterson308d6372009-09-18 21:42:35 +000010920 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10921 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010922 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010923 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010924}
10925
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010926PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010927 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010928\n\
10929Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010930If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010931
10932static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010933unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010934{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010935 Py_ssize_t i, j, line_pos, src_len, incr;
10936 Py_UCS4 ch;
10937 PyObject *u;
10938 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010939 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010940 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010941 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010942
10943 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010944 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010945
Antoine Pitrou22425222011-10-04 19:10:51 +020010946 if (PyUnicode_READY(self) == -1)
10947 return NULL;
10948
Thomas Wouters7e474022000-07-16 12:04:32 +000010949 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010950 src_len = PyUnicode_GET_LENGTH(self);
10951 i = j = line_pos = 0;
10952 kind = PyUnicode_KIND(self);
10953 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010954 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010955 for (; i < src_len; i++) {
10956 ch = PyUnicode_READ(kind, src_data, i);
10957 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010958 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010959 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010960 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010961 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010962 goto overflow;
10963 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010964 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010965 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010966 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010967 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010968 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010969 goto overflow;
10970 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010971 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010972 if (ch == '\n' || ch == '\r')
10973 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010974 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010975 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010976 if (!found && PyUnicode_CheckExact(self)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +010010977 Py_INCREF(self);
10978 return self;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010979 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010980
Guido van Rossumd57fd912000-03-10 22:53:23 +000010981 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010982 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010983 if (!u)
10984 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010985 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010986
Antoine Pitroue71d5742011-10-04 15:55:09 +020010987 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010988
Antoine Pitroue71d5742011-10-04 15:55:09 +020010989 for (; i < src_len; i++) {
10990 ch = PyUnicode_READ(kind, src_data, i);
10991 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010992 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010993 incr = tabsize - (line_pos % tabsize);
10994 line_pos += incr;
10995 while (incr--) {
10996 PyUnicode_WRITE(kind, dest_data, j, ' ');
10997 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010998 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010999 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011000 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011001 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011002 line_pos++;
11003 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011004 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011005 if (ch == '\n' || ch == '\r')
11006 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011007 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011008 }
11009 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020011010#ifndef DONT_MAKE_RESULT_READY
11011 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011012 Py_DECREF(u);
11013 return NULL;
11014 }
Victor Stinner17efeed2011-10-04 20:05:46 +020011015#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011016 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010011017 return u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011018
Antoine Pitroue71d5742011-10-04 15:55:09 +020011019 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011020 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11021 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011022}
11023
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011024PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011025 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011026\n\
11027Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011028such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011029arguments start and end are interpreted as in slice notation.\n\
11030\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011031Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011032
11033static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011034unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011035{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011036 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011037 Py_ssize_t start;
11038 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011039 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011040
Jesus Ceaac451502011-04-20 17:09:23 +020011041 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11042 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011043 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011045 if (PyUnicode_READY(self) == -1)
11046 return NULL;
11047 if (PyUnicode_READY(substring) == -1)
11048 return NULL;
11049
Victor Stinner7931d9a2011-11-04 00:22:48 +010011050 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011051
11052 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011053
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011054 if (result == -2)
11055 return NULL;
11056
Christian Heimes217cfd12007-12-02 14:31:20 +000011057 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011058}
11059
11060static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011061unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011062{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011063 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11064 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011065 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011066 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011067}
11068
Guido van Rossumc2504932007-09-18 19:42:40 +000011069/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011070 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011071static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011072unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011073{
Guido van Rossumc2504932007-09-18 19:42:40 +000011074 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011075 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011076
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011077 if (_PyUnicode_HASH(self) != -1)
11078 return _PyUnicode_HASH(self);
11079 if (PyUnicode_READY(self) == -1)
11080 return -1;
11081 len = PyUnicode_GET_LENGTH(self);
11082
11083 /* The hash function as a macro, gets expanded three times below. */
11084#define HASH(P) \
11085 x = (Py_uhash_t)*P << 7; \
11086 while (--len >= 0) \
11087 x = (1000003*x) ^ (Py_uhash_t)*P++;
11088
11089 switch (PyUnicode_KIND(self)) {
11090 case PyUnicode_1BYTE_KIND: {
11091 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11092 HASH(c);
11093 break;
11094 }
11095 case PyUnicode_2BYTE_KIND: {
11096 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11097 HASH(s);
11098 break;
11099 }
11100 default: {
11101 Py_UCS4 *l;
11102 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11103 "Impossible switch case in unicode_hash");
11104 l = PyUnicode_4BYTE_DATA(self);
11105 HASH(l);
11106 break;
11107 }
11108 }
11109 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11110
Guido van Rossumc2504932007-09-18 19:42:40 +000011111 if (x == -1)
11112 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011113 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011114 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011115}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011116#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011117
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011118PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011119 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011120\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011121Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011122
11123static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011124unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011125{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011126 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011127 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011128 Py_ssize_t start;
11129 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011130
Jesus Ceaac451502011-04-20 17:09:23 +020011131 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11132 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011133 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011134
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011135 if (PyUnicode_READY(self) == -1)
11136 return NULL;
11137 if (PyUnicode_READY(substring) == -1)
11138 return NULL;
11139
Victor Stinner7931d9a2011-11-04 00:22:48 +010011140 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011141
11142 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011144 if (result == -2)
11145 return NULL;
11146
Guido van Rossumd57fd912000-03-10 22:53:23 +000011147 if (result < 0) {
11148 PyErr_SetString(PyExc_ValueError, "substring not found");
11149 return NULL;
11150 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011151
Christian Heimes217cfd12007-12-02 14:31:20 +000011152 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011153}
11154
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011155PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011156 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011157\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011158Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011159at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011160
11161static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011162unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011163{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011164 Py_ssize_t i, length;
11165 int kind;
11166 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011167 int cased;
11168
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011169 if (PyUnicode_READY(self) == -1)
11170 return NULL;
11171 length = PyUnicode_GET_LENGTH(self);
11172 kind = PyUnicode_KIND(self);
11173 data = PyUnicode_DATA(self);
11174
Guido van Rossumd57fd912000-03-10 22:53:23 +000011175 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011176 if (length == 1)
11177 return PyBool_FromLong(
11178 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011180 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011181 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011182 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011183
Guido van Rossumd57fd912000-03-10 22:53:23 +000011184 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011185 for (i = 0; i < length; i++) {
11186 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011187
Benjamin Peterson29060642009-01-31 22:14:21 +000011188 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11189 return PyBool_FromLong(0);
11190 else if (!cased && Py_UNICODE_ISLOWER(ch))
11191 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011192 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011193 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011194}
11195
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011196PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011197 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011198\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011199Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011200at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201
11202static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011203unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011205 Py_ssize_t i, length;
11206 int kind;
11207 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208 int cased;
11209
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011210 if (PyUnicode_READY(self) == -1)
11211 return NULL;
11212 length = PyUnicode_GET_LENGTH(self);
11213 kind = PyUnicode_KIND(self);
11214 data = PyUnicode_DATA(self);
11215
Guido van Rossumd57fd912000-03-10 22:53:23 +000011216 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011217 if (length == 1)
11218 return PyBool_FromLong(
11219 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011220
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011221 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011222 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011223 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011224
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011226 for (i = 0; i < length; i++) {
11227 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011228
Benjamin Peterson29060642009-01-31 22:14:21 +000011229 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11230 return PyBool_FromLong(0);
11231 else if (!cased && Py_UNICODE_ISUPPER(ch))
11232 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011233 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011234 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011235}
11236
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011237PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011238 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011239\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011240Return True if S is a titlecased string and there is at least one\n\
11241character in S, i.e. upper- and titlecase characters may only\n\
11242follow uncased characters and lowercase characters only cased ones.\n\
11243Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011244
11245static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011246unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011247{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011248 Py_ssize_t i, length;
11249 int kind;
11250 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251 int cased, previous_is_cased;
11252
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011253 if (PyUnicode_READY(self) == -1)
11254 return NULL;
11255 length = PyUnicode_GET_LENGTH(self);
11256 kind = PyUnicode_KIND(self);
11257 data = PyUnicode_DATA(self);
11258
Guido van Rossumd57fd912000-03-10 22:53:23 +000011259 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011260 if (length == 1) {
11261 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11262 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11263 (Py_UNICODE_ISUPPER(ch) != 0));
11264 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011265
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011266 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011267 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011268 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011269
Guido van Rossumd57fd912000-03-10 22:53:23 +000011270 cased = 0;
11271 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011272 for (i = 0; i < length; i++) {
11273 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011274
Benjamin Peterson29060642009-01-31 22:14:21 +000011275 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11276 if (previous_is_cased)
11277 return PyBool_FromLong(0);
11278 previous_is_cased = 1;
11279 cased = 1;
11280 }
11281 else if (Py_UNICODE_ISLOWER(ch)) {
11282 if (!previous_is_cased)
11283 return PyBool_FromLong(0);
11284 previous_is_cased = 1;
11285 cased = 1;
11286 }
11287 else
11288 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011289 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011290 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011291}
11292
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011293PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011294 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011295\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011296Return True if all characters in S are whitespace\n\
11297and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011298
11299static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011300unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011301{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011302 Py_ssize_t i, length;
11303 int kind;
11304 void *data;
11305
11306 if (PyUnicode_READY(self) == -1)
11307 return NULL;
11308 length = PyUnicode_GET_LENGTH(self);
11309 kind = PyUnicode_KIND(self);
11310 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011311
Guido van Rossumd57fd912000-03-10 22:53:23 +000011312 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011313 if (length == 1)
11314 return PyBool_FromLong(
11315 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011316
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011317 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011318 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011319 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011320
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011321 for (i = 0; i < length; i++) {
11322 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011323 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011324 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011325 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011326 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011327}
11328
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011329PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011330 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011331\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011332Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011333and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011334
11335static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011336unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011337{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011338 Py_ssize_t i, length;
11339 int kind;
11340 void *data;
11341
11342 if (PyUnicode_READY(self) == -1)
11343 return NULL;
11344 length = PyUnicode_GET_LENGTH(self);
11345 kind = PyUnicode_KIND(self);
11346 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011347
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011348 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011349 if (length == 1)
11350 return PyBool_FromLong(
11351 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011352
11353 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011354 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011355 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011356
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011357 for (i = 0; i < length; i++) {
11358 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011359 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011360 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011361 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011362}
11363
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011364PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011365 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011366\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011367Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011368and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011369
11370static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011371unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011372{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011373 int kind;
11374 void *data;
11375 Py_ssize_t len, i;
11376
11377 if (PyUnicode_READY(self) == -1)
11378 return NULL;
11379
11380 kind = PyUnicode_KIND(self);
11381 data = PyUnicode_DATA(self);
11382 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011383
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011384 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011385 if (len == 1) {
11386 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11387 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11388 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011389
11390 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011391 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011392 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011393
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011394 for (i = 0; i < len; i++) {
11395 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011396 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011397 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011398 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011399 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011400}
11401
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011402PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011403 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011404\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011405Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011406False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407
11408static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011409unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011410{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011411 Py_ssize_t i, length;
11412 int kind;
11413 void *data;
11414
11415 if (PyUnicode_READY(self) == -1)
11416 return NULL;
11417 length = PyUnicode_GET_LENGTH(self);
11418 kind = PyUnicode_KIND(self);
11419 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011422 if (length == 1)
11423 return PyBool_FromLong(
11424 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011425
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011426 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011427 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011428 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011429
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011430 for (i = 0; i < length; i++) {
11431 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011432 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011434 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435}
11436
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011437PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011438 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011440Return True if all characters in S are digits\n\
11441and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011442
11443static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011444unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011445{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011446 Py_ssize_t i, length;
11447 int kind;
11448 void *data;
11449
11450 if (PyUnicode_READY(self) == -1)
11451 return NULL;
11452 length = PyUnicode_GET_LENGTH(self);
11453 kind = PyUnicode_KIND(self);
11454 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011455
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011457 if (length == 1) {
11458 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11459 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11460 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011461
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011462 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011463 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011464 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011465
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011466 for (i = 0; i < length; i++) {
11467 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011468 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011470 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011471}
11472
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011473PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011474 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011476Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011477False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011478
11479static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011480unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011481{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011482 Py_ssize_t i, length;
11483 int kind;
11484 void *data;
11485
11486 if (PyUnicode_READY(self) == -1)
11487 return NULL;
11488 length = PyUnicode_GET_LENGTH(self);
11489 kind = PyUnicode_KIND(self);
11490 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011493 if (length == 1)
11494 return PyBool_FromLong(
11495 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011496
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011497 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011498 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011499 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011500
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011501 for (i = 0; i < length; i++) {
11502 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011503 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011504 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011505 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011506}
11507
Martin v. Löwis47383402007-08-15 07:32:56 +000011508int
11509PyUnicode_IsIdentifier(PyObject *self)
11510{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011511 int kind;
11512 void *data;
11513 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011514 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011515
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011516 if (PyUnicode_READY(self) == -1) {
11517 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011518 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011519 }
11520
11521 /* Special case for empty strings */
11522 if (PyUnicode_GET_LENGTH(self) == 0)
11523 return 0;
11524 kind = PyUnicode_KIND(self);
11525 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011526
11527 /* PEP 3131 says that the first character must be in
11528 XID_Start and subsequent characters in XID_Continue,
11529 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011530 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011531 letters, digits, underscore). However, given the current
11532 definition of XID_Start and XID_Continue, it is sufficient
11533 to check just for these, except that _ must be allowed
11534 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011535 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011536 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011537 return 0;
11538
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011539 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011540 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011541 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011542 return 1;
11543}
11544
11545PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011546 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011547\n\
11548Return True if S is a valid identifier according\n\
11549to the language definition.");
11550
11551static PyObject*
11552unicode_isidentifier(PyObject *self)
11553{
11554 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11555}
11556
Georg Brandl559e5d72008-06-11 18:37:52 +000011557PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011558 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011559\n\
11560Return True if all characters in S are considered\n\
11561printable in repr() or S is empty, False otherwise.");
11562
11563static PyObject*
11564unicode_isprintable(PyObject *self)
11565{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011566 Py_ssize_t i, length;
11567 int kind;
11568 void *data;
11569
11570 if (PyUnicode_READY(self) == -1)
11571 return NULL;
11572 length = PyUnicode_GET_LENGTH(self);
11573 kind = PyUnicode_KIND(self);
11574 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011575
11576 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011577 if (length == 1)
11578 return PyBool_FromLong(
11579 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011580
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011581 for (i = 0; i < length; i++) {
11582 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011583 Py_RETURN_FALSE;
11584 }
11585 }
11586 Py_RETURN_TRUE;
11587}
11588
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011589PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011590 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591\n\
11592Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011593iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011594
11595static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011596unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011597{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011598 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011599}
11600
Martin v. Löwis18e16552006-02-15 17:27:45 +000011601static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011602unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011603{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011604 if (PyUnicode_READY(self) == -1)
11605 return -1;
11606 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011607}
11608
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011609PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011610 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011611\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011612Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011613done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011614
11615static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011616unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011617{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011618 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011619 Py_UCS4 fillchar = ' ';
11620
11621 if (PyUnicode_READY(self) == -1)
11622 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011623
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011624 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011625 return NULL;
11626
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011627 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011628 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011629 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011630 }
11631
Victor Stinner7931d9a2011-11-04 00:22:48 +010011632 return pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011633}
11634
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011635PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011636 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011637\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011638Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011639
11640static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011641unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011642{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011643 return fixup(self, fixlower);
11644}
11645
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011646#define LEFTSTRIP 0
11647#define RIGHTSTRIP 1
11648#define BOTHSTRIP 2
11649
11650/* Arrays indexed by above */
11651static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11652
11653#define STRIPNAME(i) (stripformat[i]+3)
11654
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011655/* externally visible for str.strip(unicode) */
11656PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011657_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011658{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011659 void *data;
11660 int kind;
11661 Py_ssize_t i, j, len;
11662 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011663
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011664 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11665 return NULL;
11666
11667 kind = PyUnicode_KIND(self);
11668 data = PyUnicode_DATA(self);
11669 len = PyUnicode_GET_LENGTH(self);
11670 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11671 PyUnicode_DATA(sepobj),
11672 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011673
Benjamin Peterson14339b62009-01-31 16:36:08 +000011674 i = 0;
11675 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011676 while (i < len &&
11677 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011678 i++;
11679 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011680 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011681
Benjamin Peterson14339b62009-01-31 16:36:08 +000011682 j = len;
11683 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011684 do {
11685 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011686 } while (j >= i &&
11687 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011688 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011689 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011690
Victor Stinner7931d9a2011-11-04 00:22:48 +010011691 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011692}
11693
11694PyObject*
11695PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11696{
11697 unsigned char *data;
11698 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011699 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011700
Victor Stinnerde636f32011-10-01 03:55:54 +020011701 if (PyUnicode_READY(self) == -1)
11702 return NULL;
11703
11704 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11705
Victor Stinner12bab6d2011-10-01 01:53:49 +020011706 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011707 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011708 if (PyUnicode_CheckExact(self)) {
11709 Py_INCREF(self);
11710 return self;
11711 }
11712 else
11713 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011714 }
11715
Victor Stinner12bab6d2011-10-01 01:53:49 +020011716 length = end - start;
11717 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011718 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011719
Victor Stinnerde636f32011-10-01 03:55:54 +020011720 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011721 PyErr_SetString(PyExc_IndexError, "string index out of range");
11722 return NULL;
11723 }
11724
Victor Stinnerb9275c12011-10-05 14:01:42 +020011725 if (PyUnicode_IS_ASCII(self)) {
11726 kind = PyUnicode_KIND(self);
11727 data = PyUnicode_1BYTE_DATA(self);
11728 return unicode_fromascii(data + start, length);
11729 }
11730 else {
11731 kind = PyUnicode_KIND(self);
11732 data = PyUnicode_1BYTE_DATA(self);
11733 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011734 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011735 length);
11736 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011737}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011738
11739static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011740do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011741{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011742 int kind;
11743 void *data;
11744 Py_ssize_t len, i, j;
11745
11746 if (PyUnicode_READY(self) == -1)
11747 return NULL;
11748
11749 kind = PyUnicode_KIND(self);
11750 data = PyUnicode_DATA(self);
11751 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011752
Benjamin Peterson14339b62009-01-31 16:36:08 +000011753 i = 0;
11754 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011755 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011756 i++;
11757 }
11758 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011759
Benjamin Peterson14339b62009-01-31 16:36:08 +000011760 j = len;
11761 if (striptype != LEFTSTRIP) {
11762 do {
11763 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011764 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011765 j++;
11766 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011767
Victor Stinner7931d9a2011-11-04 00:22:48 +010011768 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011769}
11770
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011771
11772static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011773do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011774{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011775 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011776
Benjamin Peterson14339b62009-01-31 16:36:08 +000011777 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11778 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011779
Benjamin Peterson14339b62009-01-31 16:36:08 +000011780 if (sep != NULL && sep != Py_None) {
11781 if (PyUnicode_Check(sep))
11782 return _PyUnicode_XStrip(self, striptype, sep);
11783 else {
11784 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011785 "%s arg must be None or str",
11786 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011787 return NULL;
11788 }
11789 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011790
Benjamin Peterson14339b62009-01-31 16:36:08 +000011791 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011792}
11793
11794
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011795PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011796 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011797\n\
11798Return a copy of the string S with leading and trailing\n\
11799whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011800If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011801
11802static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011803unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011804{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011805 if (PyTuple_GET_SIZE(args) == 0)
11806 return do_strip(self, BOTHSTRIP); /* Common case */
11807 else
11808 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011809}
11810
11811
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011812PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011813 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011814\n\
11815Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011816If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011817
11818static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011819unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011820{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011821 if (PyTuple_GET_SIZE(args) == 0)
11822 return do_strip(self, LEFTSTRIP); /* Common case */
11823 else
11824 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011825}
11826
11827
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011828PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011829 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011830\n\
11831Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011832If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011833
11834static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011835unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011836{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011837 if (PyTuple_GET_SIZE(args) == 0)
11838 return do_strip(self, RIGHTSTRIP); /* Common case */
11839 else
11840 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011841}
11842
11843
Guido van Rossumd57fd912000-03-10 22:53:23 +000011844static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011845unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011846{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011847 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011848 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011849
Georg Brandl222de0f2009-04-12 12:01:50 +000011850 if (len < 1) {
11851 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011852 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011853 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011854
Tim Peters7a29bd52001-09-12 03:03:31 +000011855 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011856 /* no repeat, return original string */
11857 Py_INCREF(str);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011858 return str;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011859 }
Tim Peters8f422462000-09-09 06:13:41 +000011860
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011861 if (PyUnicode_READY(str) == -1)
11862 return NULL;
11863
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011864 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011865 PyErr_SetString(PyExc_OverflowError,
11866 "repeated string is too long");
11867 return NULL;
11868 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011869 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011870
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011871 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011872 if (!u)
11873 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011874 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011875
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011876 if (PyUnicode_GET_LENGTH(str) == 1) {
11877 const int kind = PyUnicode_KIND(str);
11878 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11879 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011880 if (kind == PyUnicode_1BYTE_KIND)
11881 memset(to, (unsigned char)fill_char, len);
11882 else {
11883 for (n = 0; n < len; ++n)
11884 PyUnicode_WRITE(kind, to, n, fill_char);
11885 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011886 }
11887 else {
11888 /* number of characters copied this far */
11889 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011890 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011891 char *to = (char *) PyUnicode_DATA(u);
11892 Py_MEMCPY(to, PyUnicode_DATA(str),
11893 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011894 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011895 n = (done <= nchars-done) ? done : nchars-done;
11896 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011897 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011898 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011899 }
11900
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011901 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011902 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011903}
11904
Alexander Belopolsky40018472011-02-26 01:02:56 +000011905PyObject *
11906PyUnicode_Replace(PyObject *obj,
11907 PyObject *subobj,
11908 PyObject *replobj,
11909 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011910{
11911 PyObject *self;
11912 PyObject *str1;
11913 PyObject *str2;
11914 PyObject *result;
11915
11916 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011917 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011918 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011919 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011920 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011921 Py_DECREF(self);
11922 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923 }
11924 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011925 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011926 Py_DECREF(self);
11927 Py_DECREF(str1);
11928 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011929 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011930 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011931 Py_DECREF(self);
11932 Py_DECREF(str1);
11933 Py_DECREF(str2);
11934 return result;
11935}
11936
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011937PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011938 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939\n\
11940Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011941old replaced by new. If the optional argument count is\n\
11942given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011943
11944static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011945unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011946{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011947 PyObject *str1;
11948 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011949 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011950 PyObject *result;
11951
Martin v. Löwis18e16552006-02-15 17:27:45 +000011952 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011954 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011955 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011956 str1 = PyUnicode_FromObject(str1);
11957 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11958 return NULL;
11959 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011960 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011961 Py_DECREF(str1);
11962 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011963 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011964
11965 result = replace(self, str1, str2, maxcount);
11966
11967 Py_DECREF(str1);
11968 Py_DECREF(str2);
11969 return result;
11970}
11971
Alexander Belopolsky40018472011-02-26 01:02:56 +000011972static PyObject *
11973unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011974{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011975 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011976 Py_ssize_t isize;
11977 Py_ssize_t osize, squote, dquote, i, o;
11978 Py_UCS4 max, quote;
11979 int ikind, okind;
11980 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011981
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011982 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011983 return NULL;
11984
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011985 isize = PyUnicode_GET_LENGTH(unicode);
11986 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011987
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011988 /* Compute length of output, quote characters, and
11989 maximum character */
11990 osize = 2; /* quotes */
11991 max = 127;
11992 squote = dquote = 0;
11993 ikind = PyUnicode_KIND(unicode);
11994 for (i = 0; i < isize; i++) {
11995 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11996 switch (ch) {
11997 case '\'': squote++; osize++; break;
11998 case '"': dquote++; osize++; break;
11999 case '\\': case '\t': case '\r': case '\n':
12000 osize += 2; break;
12001 default:
12002 /* Fast-path ASCII */
12003 if (ch < ' ' || ch == 0x7f)
12004 osize += 4; /* \xHH */
12005 else if (ch < 0x7f)
12006 osize++;
12007 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12008 osize++;
12009 max = ch > max ? ch : max;
12010 }
12011 else if (ch < 0x100)
12012 osize += 4; /* \xHH */
12013 else if (ch < 0x10000)
12014 osize += 6; /* \uHHHH */
12015 else
12016 osize += 10; /* \uHHHHHHHH */
12017 }
12018 }
12019
12020 quote = '\'';
12021 if (squote) {
12022 if (dquote)
12023 /* Both squote and dquote present. Use squote,
12024 and escape them */
12025 osize += squote;
12026 else
12027 quote = '"';
12028 }
12029
12030 repr = PyUnicode_New(osize, max);
12031 if (repr == NULL)
12032 return NULL;
12033 okind = PyUnicode_KIND(repr);
12034 odata = PyUnicode_DATA(repr);
12035
12036 PyUnicode_WRITE(okind, odata, 0, quote);
12037 PyUnicode_WRITE(okind, odata, osize-1, quote);
12038
12039 for (i = 0, o = 1; i < isize; i++) {
12040 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012041
12042 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012043 if ((ch == quote) || (ch == '\\')) {
12044 PyUnicode_WRITE(okind, odata, o++, '\\');
12045 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012046 continue;
12047 }
12048
Benjamin Peterson29060642009-01-31 22:14:21 +000012049 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012050 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012051 PyUnicode_WRITE(okind, odata, o++, '\\');
12052 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012053 }
12054 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012055 PyUnicode_WRITE(okind, odata, o++, '\\');
12056 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012057 }
12058 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012059 PyUnicode_WRITE(okind, odata, o++, '\\');
12060 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012061 }
12062
12063 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012064 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012065 PyUnicode_WRITE(okind, odata, o++, '\\');
12066 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012067 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12068 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012069 }
12070
Georg Brandl559e5d72008-06-11 18:37:52 +000012071 /* Copy ASCII characters as-is */
12072 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012073 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012074 }
12075
Benjamin Peterson29060642009-01-31 22:14:21 +000012076 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012077 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012078 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012079 (categories Z* and C* except ASCII space)
12080 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012081 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012082 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012083 if (ch <= 0xff) {
12084 PyUnicode_WRITE(okind, odata, o++, '\\');
12085 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012086 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12087 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012088 }
12089 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012090 else if (ch >= 0x10000) {
12091 PyUnicode_WRITE(okind, odata, o++, '\\');
12092 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012093 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12094 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12095 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12096 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12097 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12098 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12099 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12100 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012101 }
12102 /* Map 16-bit characters to '\uxxxx' */
12103 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012104 PyUnicode_WRITE(okind, odata, o++, '\\');
12105 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012106 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12107 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12108 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12109 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012110 }
12111 }
12112 /* Copy characters as-is */
12113 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012114 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012115 }
12116 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012117 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012118 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012119 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012120 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012121}
12122
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012123PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012124 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012125\n\
12126Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012127such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012128arguments start and end are interpreted as in slice notation.\n\
12129\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012130Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012131
12132static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012133unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012134{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012135 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012136 Py_ssize_t start;
12137 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012138 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012139
Jesus Ceaac451502011-04-20 17:09:23 +020012140 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12141 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012142 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012144 if (PyUnicode_READY(self) == -1)
12145 return NULL;
12146 if (PyUnicode_READY(substring) == -1)
12147 return NULL;
12148
Victor Stinner7931d9a2011-11-04 00:22:48 +010012149 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012150
12151 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012152
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012153 if (result == -2)
12154 return NULL;
12155
Christian Heimes217cfd12007-12-02 14:31:20 +000012156 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012157}
12158
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012159PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012160 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012161\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012162Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012163
12164static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012165unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012166{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012167 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012168 Py_ssize_t start;
12169 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012170 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012171
Jesus Ceaac451502011-04-20 17:09:23 +020012172 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12173 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012174 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012176 if (PyUnicode_READY(self) == -1)
12177 return NULL;
12178 if (PyUnicode_READY(substring) == -1)
12179 return NULL;
12180
Victor Stinner7931d9a2011-11-04 00:22:48 +010012181 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012182
12183 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012184
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012185 if (result == -2)
12186 return NULL;
12187
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188 if (result < 0) {
12189 PyErr_SetString(PyExc_ValueError, "substring not found");
12190 return NULL;
12191 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012192
Christian Heimes217cfd12007-12-02 14:31:20 +000012193 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012194}
12195
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012196PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012197 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012198\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012199Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012200done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012201
12202static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012203unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012204{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012205 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012206 Py_UCS4 fillchar = ' ';
12207
Victor Stinnere9a29352011-10-01 02:14:59 +020012208 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012209 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012210
Victor Stinnere9a29352011-10-01 02:14:59 +020012211 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012212 return NULL;
12213
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012214 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012215 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012216 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012217 }
12218
Victor Stinner7931d9a2011-11-04 00:22:48 +010012219 return pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012220}
12221
Alexander Belopolsky40018472011-02-26 01:02:56 +000012222PyObject *
12223PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012224{
12225 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012226
Guido van Rossumd57fd912000-03-10 22:53:23 +000012227 s = PyUnicode_FromObject(s);
12228 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012229 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012230 if (sep != NULL) {
12231 sep = PyUnicode_FromObject(sep);
12232 if (sep == NULL) {
12233 Py_DECREF(s);
12234 return NULL;
12235 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012236 }
12237
Victor Stinner9310abb2011-10-05 00:59:23 +020012238 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012239
12240 Py_DECREF(s);
12241 Py_XDECREF(sep);
12242 return result;
12243}
12244
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012245PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012246 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012247\n\
12248Return a list of the words in S, using sep as the\n\
12249delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012250splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012251whitespace string is a separator and empty strings are\n\
12252removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012253
12254static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012255unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012256{
12257 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012258 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012259
Martin v. Löwis18e16552006-02-15 17:27:45 +000012260 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012261 return NULL;
12262
12263 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012264 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012265 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012266 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012267 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012268 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012269}
12270
Thomas Wouters477c8d52006-05-27 19:21:47 +000012271PyObject *
12272PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12273{
12274 PyObject* str_obj;
12275 PyObject* sep_obj;
12276 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012277 int kind1, kind2, kind;
12278 void *buf1 = NULL, *buf2 = NULL;
12279 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012280
12281 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012282 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012283 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012284 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012285 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012286 Py_DECREF(str_obj);
12287 return NULL;
12288 }
12289
Victor Stinner14f8f022011-10-05 20:58:25 +020012290 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012291 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012292 kind = Py_MAX(kind1, kind2);
12293 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012294 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012295 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012296 if (!buf1)
12297 goto onError;
12298 buf2 = PyUnicode_DATA(sep_obj);
12299 if (kind2 != kind)
12300 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12301 if (!buf2)
12302 goto onError;
12303 len1 = PyUnicode_GET_LENGTH(str_obj);
12304 len2 = PyUnicode_GET_LENGTH(sep_obj);
12305
Victor Stinner14f8f022011-10-05 20:58:25 +020012306 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012307 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012308 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12309 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12310 else
12311 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012312 break;
12313 case PyUnicode_2BYTE_KIND:
12314 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12315 break;
12316 case PyUnicode_4BYTE_KIND:
12317 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12318 break;
12319 default:
12320 assert(0);
12321 out = 0;
12322 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012323
12324 Py_DECREF(sep_obj);
12325 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012326 if (kind1 != kind)
12327 PyMem_Free(buf1);
12328 if (kind2 != kind)
12329 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012330
12331 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012332 onError:
12333 Py_DECREF(sep_obj);
12334 Py_DECREF(str_obj);
12335 if (kind1 != kind && buf1)
12336 PyMem_Free(buf1);
12337 if (kind2 != kind && buf2)
12338 PyMem_Free(buf2);
12339 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012340}
12341
12342
12343PyObject *
12344PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12345{
12346 PyObject* str_obj;
12347 PyObject* sep_obj;
12348 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012349 int kind1, kind2, kind;
12350 void *buf1 = NULL, *buf2 = NULL;
12351 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012352
12353 str_obj = PyUnicode_FromObject(str_in);
12354 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012355 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012356 sep_obj = PyUnicode_FromObject(sep_in);
12357 if (!sep_obj) {
12358 Py_DECREF(str_obj);
12359 return NULL;
12360 }
12361
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012362 kind1 = PyUnicode_KIND(str_in);
12363 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012364 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012365 buf1 = PyUnicode_DATA(str_in);
12366 if (kind1 != kind)
12367 buf1 = _PyUnicode_AsKind(str_in, kind);
12368 if (!buf1)
12369 goto onError;
12370 buf2 = PyUnicode_DATA(sep_obj);
12371 if (kind2 != kind)
12372 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12373 if (!buf2)
12374 goto onError;
12375 len1 = PyUnicode_GET_LENGTH(str_obj);
12376 len2 = PyUnicode_GET_LENGTH(sep_obj);
12377
12378 switch(PyUnicode_KIND(str_in)) {
12379 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012380 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12381 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12382 else
12383 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012384 break;
12385 case PyUnicode_2BYTE_KIND:
12386 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12387 break;
12388 case PyUnicode_4BYTE_KIND:
12389 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12390 break;
12391 default:
12392 assert(0);
12393 out = 0;
12394 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012395
12396 Py_DECREF(sep_obj);
12397 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012398 if (kind1 != kind)
12399 PyMem_Free(buf1);
12400 if (kind2 != kind)
12401 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012402
12403 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012404 onError:
12405 Py_DECREF(sep_obj);
12406 Py_DECREF(str_obj);
12407 if (kind1 != kind && buf1)
12408 PyMem_Free(buf1);
12409 if (kind2 != kind && buf2)
12410 PyMem_Free(buf2);
12411 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012412}
12413
12414PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012415 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012416\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012417Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012418the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012419found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012420
12421static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012422unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012423{
Victor Stinner9310abb2011-10-05 00:59:23 +020012424 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012425}
12426
12427PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012428 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012429\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012430Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012431the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012432separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012433
12434static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012435unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012436{
Victor Stinner9310abb2011-10-05 00:59:23 +020012437 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012438}
12439
Alexander Belopolsky40018472011-02-26 01:02:56 +000012440PyObject *
12441PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012442{
12443 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012444
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012445 s = PyUnicode_FromObject(s);
12446 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012447 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012448 if (sep != NULL) {
12449 sep = PyUnicode_FromObject(sep);
12450 if (sep == NULL) {
12451 Py_DECREF(s);
12452 return NULL;
12453 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012454 }
12455
Victor Stinner9310abb2011-10-05 00:59:23 +020012456 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012457
12458 Py_DECREF(s);
12459 Py_XDECREF(sep);
12460 return result;
12461}
12462
12463PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012464 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012465\n\
12466Return a list of the words in S, using sep as the\n\
12467delimiter string, starting at the end of the string and\n\
12468working to the front. If maxsplit is given, at most maxsplit\n\
12469splits are done. If sep is not specified, any whitespace string\n\
12470is a separator.");
12471
12472static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012473unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012474{
12475 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012476 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012477
Martin v. Löwis18e16552006-02-15 17:27:45 +000012478 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012479 return NULL;
12480
12481 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012482 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012483 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012484 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012485 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012486 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012487}
12488
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012489PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012490 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012491\n\
12492Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012493Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012494is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012495
12496static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012497unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012498{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012499 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012500 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012501
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012502 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12503 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012504 return NULL;
12505
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012506 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012507}
12508
12509static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012510PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012511{
Walter Dörwald346737f2007-05-31 10:44:43 +000012512 if (PyUnicode_CheckExact(self)) {
12513 Py_INCREF(self);
12514 return self;
12515 } else
12516 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012517 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012518}
12519
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012520PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012521 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012522\n\
12523Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012524and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012525
12526static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012527unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012528{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012529 return fixup(self, fixswapcase);
12530}
12531
Georg Brandlceee0772007-11-27 23:48:05 +000012532PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012533 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012534\n\
12535Return a translation table usable for str.translate().\n\
12536If there is only one argument, it must be a dictionary mapping Unicode\n\
12537ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012538Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012539If there are two arguments, they must be strings of equal length, and\n\
12540in the resulting dictionary, each character in x will be mapped to the\n\
12541character at the same position in y. If there is a third argument, it\n\
12542must be a string, whose characters will be mapped to None in the result.");
12543
12544static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012545unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012546{
12547 PyObject *x, *y = NULL, *z = NULL;
12548 PyObject *new = NULL, *key, *value;
12549 Py_ssize_t i = 0;
12550 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012551
Georg Brandlceee0772007-11-27 23:48:05 +000012552 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12553 return NULL;
12554 new = PyDict_New();
12555 if (!new)
12556 return NULL;
12557 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012558 int x_kind, y_kind, z_kind;
12559 void *x_data, *y_data, *z_data;
12560
Georg Brandlceee0772007-11-27 23:48:05 +000012561 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012562 if (!PyUnicode_Check(x)) {
12563 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12564 "be a string if there is a second argument");
12565 goto err;
12566 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012567 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012568 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12569 "arguments must have equal length");
12570 goto err;
12571 }
12572 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012573 x_kind = PyUnicode_KIND(x);
12574 y_kind = PyUnicode_KIND(y);
12575 x_data = PyUnicode_DATA(x);
12576 y_data = PyUnicode_DATA(y);
12577 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12578 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12579 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012580 if (!key || !value)
12581 goto err;
12582 res = PyDict_SetItem(new, key, value);
12583 Py_DECREF(key);
12584 Py_DECREF(value);
12585 if (res < 0)
12586 goto err;
12587 }
12588 /* create entries for deleting chars in z */
12589 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012590 z_kind = PyUnicode_KIND(z);
12591 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012592 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012593 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012594 if (!key)
12595 goto err;
12596 res = PyDict_SetItem(new, key, Py_None);
12597 Py_DECREF(key);
12598 if (res < 0)
12599 goto err;
12600 }
12601 }
12602 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012603 int kind;
12604 void *data;
12605
Georg Brandlceee0772007-11-27 23:48:05 +000012606 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012607 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012608 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12609 "to maketrans it must be a dict");
12610 goto err;
12611 }
12612 /* copy entries into the new dict, converting string keys to int keys */
12613 while (PyDict_Next(x, &i, &key, &value)) {
12614 if (PyUnicode_Check(key)) {
12615 /* convert string keys to integer keys */
12616 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012617 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012618 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12619 "table must be of length 1");
12620 goto err;
12621 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012622 kind = PyUnicode_KIND(key);
12623 data = PyUnicode_DATA(key);
12624 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012625 if (!newkey)
12626 goto err;
12627 res = PyDict_SetItem(new, newkey, value);
12628 Py_DECREF(newkey);
12629 if (res < 0)
12630 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012631 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012632 /* just keep integer keys */
12633 if (PyDict_SetItem(new, key, value) < 0)
12634 goto err;
12635 } else {
12636 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12637 "be strings or integers");
12638 goto err;
12639 }
12640 }
12641 }
12642 return new;
12643 err:
12644 Py_DECREF(new);
12645 return NULL;
12646}
12647
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012648PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012649 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012650\n\
12651Return a copy of the string S, where all characters have been mapped\n\
12652through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012653Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012654Unmapped characters are left untouched. Characters mapped to None\n\
12655are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012656
12657static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012658unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012659{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012660 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012661}
12662
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012663PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012664 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012665\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012666Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012667
12668static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012669unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012670{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012671 return fixup(self, fixupper);
12672}
12673
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012674PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012675 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012676\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012677Pad a numeric string S with zeros on the left, to fill a field\n\
12678of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012679
12680static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012681unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012682{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012683 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012684 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012685 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012686 int kind;
12687 void *data;
12688 Py_UCS4 chr;
12689
12690 if (PyUnicode_READY(self) == -1)
12691 return NULL;
12692
Martin v. Löwis18e16552006-02-15 17:27:45 +000012693 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012694 return NULL;
12695
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012696 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012697 if (PyUnicode_CheckExact(self)) {
12698 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012699 return self;
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012700 }
12701 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012702 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012703 }
12704
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012705 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012706
12707 u = pad(self, fill, 0, '0');
12708
Walter Dörwald068325e2002-04-15 13:36:47 +000012709 if (u == NULL)
12710 return NULL;
12711
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012712 kind = PyUnicode_KIND(u);
12713 data = PyUnicode_DATA(u);
12714 chr = PyUnicode_READ(kind, data, fill);
12715
12716 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012717 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012718 PyUnicode_WRITE(kind, data, 0, chr);
12719 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012720 }
12721
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012722 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012723 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012724}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012725
12726#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012727static PyObject *
12728unicode__decimal2ascii(PyObject *self)
12729{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012730 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012731}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012732#endif
12733
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012734PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012735 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012736\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012737Return True if S starts with the specified prefix, False otherwise.\n\
12738With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012739With optional end, stop comparing S at that position.\n\
12740prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012741
12742static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012743unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012744 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012745{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012746 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012747 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012748 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012749 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012750 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012751
Jesus Ceaac451502011-04-20 17:09:23 +020012752 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012753 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012754 if (PyTuple_Check(subobj)) {
12755 Py_ssize_t i;
12756 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012757 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012758 if (substring == NULL)
12759 return NULL;
12760 result = tailmatch(self, substring, start, end, -1);
12761 Py_DECREF(substring);
12762 if (result) {
12763 Py_RETURN_TRUE;
12764 }
12765 }
12766 /* nothing matched */
12767 Py_RETURN_FALSE;
12768 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012769 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012770 if (substring == NULL) {
12771 if (PyErr_ExceptionMatches(PyExc_TypeError))
12772 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12773 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012774 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012775 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012776 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012777 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012778 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012779}
12780
12781
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012782PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012783 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012784\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012785Return True if S ends with the specified suffix, False otherwise.\n\
12786With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012787With optional end, stop comparing S at that position.\n\
12788suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012789
12790static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012791unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012792 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012793{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012794 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012795 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012796 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012797 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012798 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012799
Jesus Ceaac451502011-04-20 17:09:23 +020012800 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012801 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012802 if (PyTuple_Check(subobj)) {
12803 Py_ssize_t i;
12804 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012805 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012806 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012807 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012808 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012809 result = tailmatch(self, substring, start, end, +1);
12810 Py_DECREF(substring);
12811 if (result) {
12812 Py_RETURN_TRUE;
12813 }
12814 }
12815 Py_RETURN_FALSE;
12816 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012817 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012818 if (substring == NULL) {
12819 if (PyErr_ExceptionMatches(PyExc_TypeError))
12820 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12821 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012822 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012823 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012824 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012825 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012826 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012827}
12828
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012829#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012830
12831PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012832 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012833\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012834Return a formatted version of S, using substitutions from args and kwargs.\n\
12835The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012836
Eric Smith27bbca62010-11-04 17:06:58 +000012837PyDoc_STRVAR(format_map__doc__,
12838 "S.format_map(mapping) -> str\n\
12839\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012840Return a formatted version of S, using substitutions from mapping.\n\
12841The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012842
Eric Smith4a7d76d2008-05-30 18:10:19 +000012843static PyObject *
12844unicode__format__(PyObject* self, PyObject* args)
12845{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012846 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012847
12848 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12849 return NULL;
12850
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012851 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012852 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012853 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012854}
12855
Eric Smith8c663262007-08-25 02:26:07 +000012856PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012857 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012858\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012859Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012860
12861static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012862unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012863{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012864 Py_ssize_t size;
12865
12866 /* If it's a compact object, account for base structure +
12867 character data. */
12868 if (PyUnicode_IS_COMPACT_ASCII(v))
12869 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12870 else if (PyUnicode_IS_COMPACT(v))
12871 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012872 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012873 else {
12874 /* If it is a two-block object, account for base object, and
12875 for character block if present. */
12876 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012877 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012878 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012879 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012880 }
12881 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012882 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012883 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012884 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012885 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012886 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012887
12888 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012889}
12890
12891PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012892 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012893
12894static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012895unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012896{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012897 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012898 if (!copy)
12899 return NULL;
12900 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012901}
12902
Guido van Rossumd57fd912000-03-10 22:53:23 +000012903static PyMethodDef unicode_methods[] = {
12904
12905 /* Order is according to common usage: often used methods should
12906 appear first, since lookup is done sequentially. */
12907
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012908 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012909 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12910 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012911 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012912 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12913 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12914 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12915 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12916 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12917 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12918 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012919 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012920 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12921 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12922 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012923 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012924 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12925 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12926 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012927 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012928 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012929 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012930 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012931 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12932 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12933 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12934 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12935 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12936 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12937 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12938 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12939 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12940 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12941 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12942 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12943 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12944 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012945 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012946 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012947 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012948 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012949 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012950 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012951 {"maketrans", (PyCFunction) unicode_maketrans,
12952 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012953 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012954#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012955 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012956#endif
12957
12958#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012959 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012960 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012961#endif
12962
Benjamin Peterson14339b62009-01-31 16:36:08 +000012963 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012964 {NULL, NULL}
12965};
12966
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012967static PyObject *
12968unicode_mod(PyObject *v, PyObject *w)
12969{
Brian Curtindfc80e32011-08-10 20:28:54 -050012970 if (!PyUnicode_Check(v))
12971 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012972 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012973}
12974
12975static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012976 0, /*nb_add*/
12977 0, /*nb_subtract*/
12978 0, /*nb_multiply*/
12979 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012980};
12981
Guido van Rossumd57fd912000-03-10 22:53:23 +000012982static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012983 (lenfunc) unicode_length, /* sq_length */
12984 PyUnicode_Concat, /* sq_concat */
12985 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12986 (ssizeargfunc) unicode_getitem, /* sq_item */
12987 0, /* sq_slice */
12988 0, /* sq_ass_item */
12989 0, /* sq_ass_slice */
12990 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012991};
12992
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012993static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012994unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012995{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012996 if (PyUnicode_READY(self) == -1)
12997 return NULL;
12998
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012999 if (PyIndex_Check(item)) {
13000 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013001 if (i == -1 && PyErr_Occurred())
13002 return NULL;
13003 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013004 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013005 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013006 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013007 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013008 PyObject *result;
13009 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013010 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013011 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013012
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013013 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013014 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013015 return NULL;
13016 }
13017
13018 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013019 return PyUnicode_New(0, 0);
13020 } else if (start == 0 && step == 1 &&
13021 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000013022 PyUnicode_CheckExact(self)) {
13023 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013024 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000013025 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013026 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013027 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013028 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013029 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013030 src_kind = PyUnicode_KIND(self);
13031 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013032 if (!PyUnicode_IS_ASCII(self)) {
13033 kind_limit = kind_maxchar_limit(src_kind);
13034 max_char = 0;
13035 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13036 ch = PyUnicode_READ(src_kind, src_data, cur);
13037 if (ch > max_char) {
13038 max_char = ch;
13039 if (max_char >= kind_limit)
13040 break;
13041 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013042 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013043 }
Victor Stinner55c99112011-10-13 01:17:06 +020013044 else
13045 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013046 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013047 if (result == NULL)
13048 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013049 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013050 dest_data = PyUnicode_DATA(result);
13051
13052 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013053 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13054 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013055 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013056 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013057 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013058 } else {
13059 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13060 return NULL;
13061 }
13062}
13063
13064static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013065 (lenfunc)unicode_length, /* mp_length */
13066 (binaryfunc)unicode_subscript, /* mp_subscript */
13067 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013068};
13069
Guido van Rossumd57fd912000-03-10 22:53:23 +000013070
Guido van Rossumd57fd912000-03-10 22:53:23 +000013071/* Helpers for PyUnicode_Format() */
13072
13073static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013074getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013075{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013076 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013077 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013078 (*p_argidx)++;
13079 if (arglen < 0)
13080 return args;
13081 else
13082 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013083 }
13084 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013085 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013086 return NULL;
13087}
13088
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013089/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013090
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013091static PyObject *
13092formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013093{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013094 char *p;
13095 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013096 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013097
Guido van Rossumd57fd912000-03-10 22:53:23 +000013098 x = PyFloat_AsDouble(v);
13099 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013100 return NULL;
13101
Guido van Rossumd57fd912000-03-10 22:53:23 +000013102 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013103 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013104
Eric Smith0923d1d2009-04-16 20:16:10 +000013105 p = PyOS_double_to_string(x, type, prec,
13106 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013107 if (p == NULL)
13108 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013109 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013110 PyMem_Free(p);
13111 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013112}
13113
Tim Peters38fd5b62000-09-21 05:43:11 +000013114static PyObject*
13115formatlong(PyObject *val, int flags, int prec, int type)
13116{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013117 char *buf;
13118 int len;
13119 PyObject *str; /* temporary string object. */
13120 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013121
Benjamin Peterson14339b62009-01-31 16:36:08 +000013122 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13123 if (!str)
13124 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013125 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013126 Py_DECREF(str);
13127 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013128}
13129
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013130static Py_UCS4
13131formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013132{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013133 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013134 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013135 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013136 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013137 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013138 goto onError;
13139 }
13140 else {
13141 /* Integer input truncated to a character */
13142 long x;
13143 x = PyLong_AsLong(v);
13144 if (x == -1 && PyErr_Occurred())
13145 goto onError;
13146
13147 if (x < 0 || x > 0x10ffff) {
13148 PyErr_SetString(PyExc_OverflowError,
13149 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013150 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013151 }
13152
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013153 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013154 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013155
Benjamin Peterson29060642009-01-31 22:14:21 +000013156 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013157 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013158 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013159 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013160}
13161
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013162static int
13163repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13164{
13165 int r;
13166 assert(count > 0);
13167 assert(PyUnicode_Check(obj));
13168 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013169 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013170 if (repeated == NULL)
13171 return -1;
13172 r = _PyAccu_Accumulate(acc, repeated);
13173 Py_DECREF(repeated);
13174 return r;
13175 }
13176 else {
13177 do {
13178 if (_PyAccu_Accumulate(acc, obj))
13179 return -1;
13180 } while (--count);
13181 return 0;
13182 }
13183}
13184
Alexander Belopolsky40018472011-02-26 01:02:56 +000013185PyObject *
13186PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013187{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013188 void *fmt;
13189 int fmtkind;
13190 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013191 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013192 int r;
13193 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013194 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013195 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013196 PyObject *temp = NULL;
13197 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013198 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013199 _PyAccu acc;
13200 static PyObject *plus, *minus, *blank, *zero, *percent;
13201
13202 if (!plus && !(plus = get_latin1_char('+')))
13203 return NULL;
13204 if (!minus && !(minus = get_latin1_char('-')))
13205 return NULL;
13206 if (!blank && !(blank = get_latin1_char(' ')))
13207 return NULL;
13208 if (!zero && !(zero = get_latin1_char('0')))
13209 return NULL;
13210 if (!percent && !(percent = get_latin1_char('%')))
13211 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013212
Guido van Rossumd57fd912000-03-10 22:53:23 +000013213 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013214 PyErr_BadInternalCall();
13215 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013216 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013217 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013218 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013219 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013220 if (_PyAccu_Init(&acc))
13221 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013222 fmt = PyUnicode_DATA(uformat);
13223 fmtkind = PyUnicode_KIND(uformat);
13224 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13225 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013226
Guido van Rossumd57fd912000-03-10 22:53:23 +000013227 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013228 arglen = PyTuple_Size(args);
13229 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013230 }
13231 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013232 arglen = -1;
13233 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013234 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013235 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013236 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013237 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013238
13239 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013240 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013241 PyObject *nonfmt;
13242 Py_ssize_t nonfmtpos;
13243 nonfmtpos = fmtpos++;
13244 while (fmtcnt >= 0 &&
13245 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13246 fmtpos++;
13247 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013248 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013249 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013250 if (nonfmt == NULL)
13251 goto onError;
13252 r = _PyAccu_Accumulate(&acc, nonfmt);
13253 Py_DECREF(nonfmt);
13254 if (r)
13255 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013256 }
13257 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013258 /* Got a format specifier */
13259 int flags = 0;
13260 Py_ssize_t width = -1;
13261 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013262 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013263 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013264 int isnumok;
13265 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013266 void *pbuf = NULL;
13267 Py_ssize_t pindex, len;
13268 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013269
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013270 fmtpos++;
13271 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13272 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013273 Py_ssize_t keylen;
13274 PyObject *key;
13275 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013276
Benjamin Peterson29060642009-01-31 22:14:21 +000013277 if (dict == NULL) {
13278 PyErr_SetString(PyExc_TypeError,
13279 "format requires a mapping");
13280 goto onError;
13281 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013282 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013283 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013284 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013285 /* Skip over balanced parentheses */
13286 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013287 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013288 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013289 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013290 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013291 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013292 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013293 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013294 if (fmtcnt < 0 || pcount > 0) {
13295 PyErr_SetString(PyExc_ValueError,
13296 "incomplete format key");
13297 goto onError;
13298 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013299 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013300 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013301 if (key == NULL)
13302 goto onError;
13303 if (args_owned) {
13304 Py_DECREF(args);
13305 args_owned = 0;
13306 }
13307 args = PyObject_GetItem(dict, key);
13308 Py_DECREF(key);
13309 if (args == NULL) {
13310 goto onError;
13311 }
13312 args_owned = 1;
13313 arglen = -1;
13314 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013315 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013316 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013317 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013318 case '-': flags |= F_LJUST; continue;
13319 case '+': flags |= F_SIGN; continue;
13320 case ' ': flags |= F_BLANK; continue;
13321 case '#': flags |= F_ALT; continue;
13322 case '0': flags |= F_ZERO; continue;
13323 }
13324 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013325 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013326 if (c == '*') {
13327 v = getnextarg(args, arglen, &argidx);
13328 if (v == NULL)
13329 goto onError;
13330 if (!PyLong_Check(v)) {
13331 PyErr_SetString(PyExc_TypeError,
13332 "* wants int");
13333 goto onError;
13334 }
13335 width = PyLong_AsLong(v);
13336 if (width == -1 && PyErr_Occurred())
13337 goto onError;
13338 if (width < 0) {
13339 flags |= F_LJUST;
13340 width = -width;
13341 }
13342 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013343 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013344 }
13345 else if (c >= '0' && c <= '9') {
13346 width = c - '0';
13347 while (--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 if (c < '0' || c > '9')
13350 break;
13351 if ((width*10) / 10 != width) {
13352 PyErr_SetString(PyExc_ValueError,
13353 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013354 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013355 }
13356 width = width*10 + (c - '0');
13357 }
13358 }
13359 if (c == '.') {
13360 prec = 0;
13361 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013362 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013363 if (c == '*') {
13364 v = getnextarg(args, arglen, &argidx);
13365 if (v == NULL)
13366 goto onError;
13367 if (!PyLong_Check(v)) {
13368 PyErr_SetString(PyExc_TypeError,
13369 "* wants int");
13370 goto onError;
13371 }
13372 prec = PyLong_AsLong(v);
13373 if (prec == -1 && PyErr_Occurred())
13374 goto onError;
13375 if (prec < 0)
13376 prec = 0;
13377 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013378 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013379 }
13380 else if (c >= '0' && c <= '9') {
13381 prec = c - '0';
13382 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013383 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013384 if (c < '0' || c > '9')
13385 break;
13386 if ((prec*10) / 10 != prec) {
13387 PyErr_SetString(PyExc_ValueError,
13388 "prec too big");
13389 goto onError;
13390 }
13391 prec = prec*10 + (c - '0');
13392 }
13393 }
13394 } /* prec */
13395 if (fmtcnt >= 0) {
13396 if (c == 'h' || c == 'l' || c == 'L') {
13397 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013398 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013399 }
13400 }
13401 if (fmtcnt < 0) {
13402 PyErr_SetString(PyExc_ValueError,
13403 "incomplete format");
13404 goto onError;
13405 }
13406 if (c != '%') {
13407 v = getnextarg(args, arglen, &argidx);
13408 if (v == NULL)
13409 goto onError;
13410 }
13411 sign = 0;
13412 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013413 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013414 switch (c) {
13415
13416 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013417 _PyAccu_Accumulate(&acc, percent);
13418 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013419
13420 case 's':
13421 case 'r':
13422 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013423 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013424 temp = v;
13425 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013426 }
13427 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013428 if (c == 's')
13429 temp = PyObject_Str(v);
13430 else if (c == 'r')
13431 temp = PyObject_Repr(v);
13432 else
13433 temp = PyObject_ASCII(v);
13434 if (temp == NULL)
13435 goto onError;
13436 if (PyUnicode_Check(temp))
13437 /* nothing to do */;
13438 else {
13439 Py_DECREF(temp);
13440 PyErr_SetString(PyExc_TypeError,
13441 "%s argument has non-string str()");
13442 goto onError;
13443 }
13444 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013445 if (PyUnicode_READY(temp) == -1) {
13446 Py_CLEAR(temp);
13447 goto onError;
13448 }
13449 pbuf = PyUnicode_DATA(temp);
13450 kind = PyUnicode_KIND(temp);
13451 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013452 if (prec >= 0 && len > prec)
13453 len = prec;
13454 break;
13455
13456 case 'i':
13457 case 'd':
13458 case 'u':
13459 case 'o':
13460 case 'x':
13461 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013462 isnumok = 0;
13463 if (PyNumber_Check(v)) {
13464 PyObject *iobj=NULL;
13465
13466 if (PyLong_Check(v)) {
13467 iobj = v;
13468 Py_INCREF(iobj);
13469 }
13470 else {
13471 iobj = PyNumber_Long(v);
13472 }
13473 if (iobj!=NULL) {
13474 if (PyLong_Check(iobj)) {
13475 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013476 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013477 Py_DECREF(iobj);
13478 if (!temp)
13479 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013480 if (PyUnicode_READY(temp) == -1) {
13481 Py_CLEAR(temp);
13482 goto onError;
13483 }
13484 pbuf = PyUnicode_DATA(temp);
13485 kind = PyUnicode_KIND(temp);
13486 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013487 sign = 1;
13488 }
13489 else {
13490 Py_DECREF(iobj);
13491 }
13492 }
13493 }
13494 if (!isnumok) {
13495 PyErr_Format(PyExc_TypeError,
13496 "%%%c format: a number is required, "
13497 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13498 goto onError;
13499 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013500 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013501 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013502 fillobj = zero;
13503 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013504 break;
13505
13506 case 'e':
13507 case 'E':
13508 case 'f':
13509 case 'F':
13510 case 'g':
13511 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013512 temp = formatfloat(v, flags, prec, c);
13513 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013514 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013515 if (PyUnicode_READY(temp) == -1) {
13516 Py_CLEAR(temp);
13517 goto onError;
13518 }
13519 pbuf = PyUnicode_DATA(temp);
13520 kind = PyUnicode_KIND(temp);
13521 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013522 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013523 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013524 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013525 fillobj = zero;
13526 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013527 break;
13528
13529 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013530 {
13531 Py_UCS4 ch = formatchar(v);
13532 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013533 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013534 temp = _PyUnicode_FromUCS4(&ch, 1);
13535 if (temp == NULL)
13536 goto onError;
13537 pbuf = PyUnicode_DATA(temp);
13538 kind = PyUnicode_KIND(temp);
13539 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013540 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013541 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013542
13543 default:
13544 PyErr_Format(PyExc_ValueError,
13545 "unsupported format character '%c' (0x%x) "
13546 "at index %zd",
13547 (31<=c && c<=126) ? (char)c : '?',
13548 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013549 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013550 goto onError;
13551 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013552 /* pbuf is initialized here. */
13553 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013554 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013555 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13556 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013557 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013558 pindex++;
13559 }
13560 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13561 signobj = plus;
13562 len--;
13563 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013564 }
13565 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013566 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013567 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013568 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013569 else
13570 sign = 0;
13571 }
13572 if (width < len)
13573 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013574 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013575 if (fill != ' ') {
13576 assert(signobj != NULL);
13577 if (_PyAccu_Accumulate(&acc, signobj))
13578 goto onError;
13579 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013580 if (width > len)
13581 width--;
13582 }
13583 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');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013585 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013586 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013587 second = get_latin1_char(
13588 PyUnicode_READ(kind, pbuf, pindex + 1));
13589 pindex += 2;
13590 if (second == NULL ||
13591 _PyAccu_Accumulate(&acc, zero) ||
13592 _PyAccu_Accumulate(&acc, second))
13593 goto onError;
13594 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013595 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013596 width -= 2;
13597 if (width < 0)
13598 width = 0;
13599 len -= 2;
13600 }
13601 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013602 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013603 if (repeat_accumulate(&acc, fillobj, width - len))
13604 goto onError;
13605 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013606 }
13607 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013608 if (sign) {
13609 assert(signobj != NULL);
13610 if (_PyAccu_Accumulate(&acc, signobj))
13611 goto onError;
13612 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013613 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013614 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13615 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013616 second = get_latin1_char(
13617 PyUnicode_READ(kind, pbuf, pindex + 1));
13618 pindex += 2;
13619 if (second == NULL ||
13620 _PyAccu_Accumulate(&acc, zero) ||
13621 _PyAccu_Accumulate(&acc, second))
13622 goto onError;
13623 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013624 }
13625 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013626 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013627 if (temp != NULL) {
13628 assert(pbuf == PyUnicode_DATA(temp));
13629 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013630 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013631 else {
13632 const char *p = (const char *) pbuf;
13633 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013634 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013635 v = PyUnicode_FromKindAndData(kind, p, len);
13636 }
13637 if (v == NULL)
13638 goto onError;
13639 r = _PyAccu_Accumulate(&acc, v);
13640 Py_DECREF(v);
13641 if (r)
13642 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013643 if (width > len && repeat_accumulate(&acc, blank, width - len))
13644 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013645 if (dict && (argidx < arglen) && c != '%') {
13646 PyErr_SetString(PyExc_TypeError,
13647 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013648 goto onError;
13649 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013650 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013651 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013652 } /* until end */
13653 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013654 PyErr_SetString(PyExc_TypeError,
13655 "not all arguments converted during string formatting");
13656 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013657 }
13658
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013659 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013660 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013661 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013662 }
13663 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013664 Py_XDECREF(temp);
13665 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013666 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013667
Benjamin Peterson29060642009-01-31 22:14:21 +000013668 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013669 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013670 Py_XDECREF(temp);
13671 Py_XDECREF(second);
13672 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013673 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013674 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013675 }
13676 return NULL;
13677}
13678
Jeremy Hylton938ace62002-07-17 16:30:39 +000013679static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013680unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13681
Tim Peters6d6c1a32001-08-02 04:15:00 +000013682static PyObject *
13683unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13684{
Benjamin Peterson29060642009-01-31 22:14:21 +000013685 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013686 static char *kwlist[] = {"object", "encoding", "errors", 0};
13687 char *encoding = NULL;
13688 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013689
Benjamin Peterson14339b62009-01-31 16:36:08 +000013690 if (type != &PyUnicode_Type)
13691 return unicode_subtype_new(type, args, kwds);
13692 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013693 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013694 return NULL;
13695 if (x == NULL)
Victor Stinner7931d9a2011-11-04 00:22:48 +010013696 return PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013697 if (encoding == NULL && errors == NULL)
13698 return PyObject_Str(x);
13699 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013700 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013701}
13702
Guido van Rossume023fe02001-08-30 03:12:59 +000013703static PyObject *
13704unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13705{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013706 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013707 Py_ssize_t length, char_size;
13708 int share_wstr, share_utf8;
13709 unsigned int kind;
13710 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013711
Benjamin Peterson14339b62009-01-31 16:36:08 +000013712 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013713
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013714 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013715 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013716 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013717 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013718 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013719 return NULL;
13720
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013721 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013722 if (self == NULL) {
13723 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013724 return NULL;
13725 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013726 kind = PyUnicode_KIND(unicode);
13727 length = PyUnicode_GET_LENGTH(unicode);
13728
13729 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013730#ifdef Py_DEBUG
13731 _PyUnicode_HASH(self) = -1;
13732#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013733 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013734#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013735 _PyUnicode_STATE(self).interned = 0;
13736 _PyUnicode_STATE(self).kind = kind;
13737 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013738 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013739 _PyUnicode_STATE(self).ready = 1;
13740 _PyUnicode_WSTR(self) = NULL;
13741 _PyUnicode_UTF8_LENGTH(self) = 0;
13742 _PyUnicode_UTF8(self) = NULL;
13743 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013744 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013745
13746 share_utf8 = 0;
13747 share_wstr = 0;
13748 if (kind == PyUnicode_1BYTE_KIND) {
13749 char_size = 1;
13750 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13751 share_utf8 = 1;
13752 }
13753 else if (kind == PyUnicode_2BYTE_KIND) {
13754 char_size = 2;
13755 if (sizeof(wchar_t) == 2)
13756 share_wstr = 1;
13757 }
13758 else {
13759 assert(kind == PyUnicode_4BYTE_KIND);
13760 char_size = 4;
13761 if (sizeof(wchar_t) == 4)
13762 share_wstr = 1;
13763 }
13764
13765 /* Ensure we won't overflow the length. */
13766 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13767 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013768 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013769 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013770 data = PyObject_MALLOC((length + 1) * char_size);
13771 if (data == NULL) {
13772 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013773 goto onError;
13774 }
13775
Victor Stinnerc3c74152011-10-02 20:39:55 +020013776 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013777 if (share_utf8) {
13778 _PyUnicode_UTF8_LENGTH(self) = length;
13779 _PyUnicode_UTF8(self) = data;
13780 }
13781 if (share_wstr) {
13782 _PyUnicode_WSTR_LENGTH(self) = length;
13783 _PyUnicode_WSTR(self) = (wchar_t *)data;
13784 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013785
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013786 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013787 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013788 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013789#ifdef Py_DEBUG
13790 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13791#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013792 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013793 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013794
13795onError:
13796 Py_DECREF(unicode);
13797 Py_DECREF(self);
13798 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013799}
13800
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013801PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013802 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013803\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013804Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013805encoding defaults to the current default string encoding.\n\
13806errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013807
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013808static PyObject *unicode_iter(PyObject *seq);
13809
Guido van Rossumd57fd912000-03-10 22:53:23 +000013810PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013811 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013812 "str", /* tp_name */
13813 sizeof(PyUnicodeObject), /* tp_size */
13814 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013815 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013816 (destructor)unicode_dealloc, /* tp_dealloc */
13817 0, /* tp_print */
13818 0, /* tp_getattr */
13819 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013820 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013821 unicode_repr, /* tp_repr */
13822 &unicode_as_number, /* tp_as_number */
13823 &unicode_as_sequence, /* tp_as_sequence */
13824 &unicode_as_mapping, /* tp_as_mapping */
13825 (hashfunc) unicode_hash, /* tp_hash*/
13826 0, /* tp_call*/
13827 (reprfunc) unicode_str, /* tp_str */
13828 PyObject_GenericGetAttr, /* tp_getattro */
13829 0, /* tp_setattro */
13830 0, /* tp_as_buffer */
13831 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013832 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013833 unicode_doc, /* tp_doc */
13834 0, /* tp_traverse */
13835 0, /* tp_clear */
13836 PyUnicode_RichCompare, /* tp_richcompare */
13837 0, /* tp_weaklistoffset */
13838 unicode_iter, /* tp_iter */
13839 0, /* tp_iternext */
13840 unicode_methods, /* tp_methods */
13841 0, /* tp_members */
13842 0, /* tp_getset */
13843 &PyBaseObject_Type, /* tp_base */
13844 0, /* tp_dict */
13845 0, /* tp_descr_get */
13846 0, /* tp_descr_set */
13847 0, /* tp_dictoffset */
13848 0, /* tp_init */
13849 0, /* tp_alloc */
13850 unicode_new, /* tp_new */
13851 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013852};
13853
13854/* Initialize the Unicode implementation */
13855
Victor Stinner3a50e702011-10-18 21:21:00 +020013856int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013857{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013858 int i;
13859
Thomas Wouters477c8d52006-05-27 19:21:47 +000013860 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013861 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013862 0x000A, /* LINE FEED */
13863 0x000D, /* CARRIAGE RETURN */
13864 0x001C, /* FILE SEPARATOR */
13865 0x001D, /* GROUP SEPARATOR */
13866 0x001E, /* RECORD SEPARATOR */
13867 0x0085, /* NEXT LINE */
13868 0x2028, /* LINE SEPARATOR */
13869 0x2029, /* PARAGRAPH SEPARATOR */
13870 };
13871
Fred Drakee4315f52000-05-09 19:53:39 +000013872 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013873 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013874 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013875 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013876 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013877
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013878 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013879 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013880 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013881 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013882
13883 /* initialize the linebreak bloom filter */
13884 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013885 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013886 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013887
13888 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013889
13890#ifdef HAVE_MBCS
13891 winver.dwOSVersionInfoSize = sizeof(winver);
13892 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13893 PyErr_SetFromWindowsErr(0);
13894 return -1;
13895 }
13896#endif
13897 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013898}
13899
13900/* Finalize the Unicode implementation */
13901
Christian Heimesa156e092008-02-16 07:38:31 +000013902int
13903PyUnicode_ClearFreeList(void)
13904{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013905 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013906}
13907
Guido van Rossumd57fd912000-03-10 22:53:23 +000013908void
Thomas Wouters78890102000-07-22 19:25:51 +000013909_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013910{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013911 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013912
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013913 Py_XDECREF(unicode_empty);
13914 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013915
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013916 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013917 if (unicode_latin1[i]) {
13918 Py_DECREF(unicode_latin1[i]);
13919 unicode_latin1[i] = NULL;
13920 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013921 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013922 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013923 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013924}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013925
Walter Dörwald16807132007-05-25 13:52:07 +000013926void
13927PyUnicode_InternInPlace(PyObject **p)
13928{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013929 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013930 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013931#ifdef Py_DEBUG
13932 assert(s != NULL);
13933 assert(_PyUnicode_CHECK(s));
13934#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013935 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013936 return;
13937#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013938 /* If it's a subclass, we don't really know what putting
13939 it in the interned dict might do. */
13940 if (!PyUnicode_CheckExact(s))
13941 return;
13942 if (PyUnicode_CHECK_INTERNED(s))
13943 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013944 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013945 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013946 return;
13947 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013948 s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013949 if (interned == NULL) {
13950 interned = PyDict_New();
13951 if (interned == NULL) {
13952 PyErr_Clear(); /* Don't leave an exception */
13953 return;
13954 }
13955 }
13956 /* It might be that the GetItem call fails even
13957 though the key is present in the dictionary,
13958 namely when this happens during a stack overflow. */
13959 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010013960 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013961 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013962
Benjamin Peterson29060642009-01-31 22:14:21 +000013963 if (t) {
13964 Py_INCREF(t);
13965 Py_DECREF(*p);
13966 *p = t;
13967 return;
13968 }
Walter Dörwald16807132007-05-25 13:52:07 +000013969
Benjamin Peterson14339b62009-01-31 16:36:08 +000013970 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010013971 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013972 PyErr_Clear();
13973 PyThreadState_GET()->recursion_critical = 0;
13974 return;
13975 }
13976 PyThreadState_GET()->recursion_critical = 0;
13977 /* The two references in interned are not counted by refcnt.
13978 The deallocator will take care of this */
13979 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013980 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013981}
13982
13983void
13984PyUnicode_InternImmortal(PyObject **p)
13985{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013986 PyUnicode_InternInPlace(p);
13987 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020013988 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013989 Py_INCREF(*p);
13990 }
Walter Dörwald16807132007-05-25 13:52:07 +000013991}
13992
13993PyObject *
13994PyUnicode_InternFromString(const char *cp)
13995{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013996 PyObject *s = PyUnicode_FromString(cp);
13997 if (s == NULL)
13998 return NULL;
13999 PyUnicode_InternInPlace(&s);
14000 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014001}
14002
Alexander Belopolsky40018472011-02-26 01:02:56 +000014003void
14004_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014005{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014006 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014007 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014008 Py_ssize_t i, n;
14009 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014010
Benjamin Peterson14339b62009-01-31 16:36:08 +000014011 if (interned == NULL || !PyDict_Check(interned))
14012 return;
14013 keys = PyDict_Keys(interned);
14014 if (keys == NULL || !PyList_Check(keys)) {
14015 PyErr_Clear();
14016 return;
14017 }
Walter Dörwald16807132007-05-25 13:52:07 +000014018
Benjamin Peterson14339b62009-01-31 16:36:08 +000014019 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14020 detector, interned unicode strings are not forcibly deallocated;
14021 rather, we give them their stolen references back, and then clear
14022 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014023
Benjamin Peterson14339b62009-01-31 16:36:08 +000014024 n = PyList_GET_SIZE(keys);
14025 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014026 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014027 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014028 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014029 if (PyUnicode_READY(s) == -1) {
14030 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014031 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014032 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014033 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014034 case SSTATE_NOT_INTERNED:
14035 /* XXX Shouldn't happen */
14036 break;
14037 case SSTATE_INTERNED_IMMORTAL:
14038 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014039 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014040 break;
14041 case SSTATE_INTERNED_MORTAL:
14042 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014043 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014044 break;
14045 default:
14046 Py_FatalError("Inconsistent interned string state.");
14047 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014048 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014049 }
14050 fprintf(stderr, "total size of all interned strings: "
14051 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14052 "mortal/immortal\n", mortal_size, immortal_size);
14053 Py_DECREF(keys);
14054 PyDict_Clear(interned);
14055 Py_DECREF(interned);
14056 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014057}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014058
14059
14060/********************* Unicode Iterator **************************/
14061
14062typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014063 PyObject_HEAD
14064 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014065 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014066} unicodeiterobject;
14067
14068static void
14069unicodeiter_dealloc(unicodeiterobject *it)
14070{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014071 _PyObject_GC_UNTRACK(it);
14072 Py_XDECREF(it->it_seq);
14073 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014074}
14075
14076static int
14077unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14078{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014079 Py_VISIT(it->it_seq);
14080 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014081}
14082
14083static PyObject *
14084unicodeiter_next(unicodeiterobject *it)
14085{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014086 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014087
Benjamin Peterson14339b62009-01-31 16:36:08 +000014088 assert(it != NULL);
14089 seq = it->it_seq;
14090 if (seq == NULL)
14091 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014092 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014093
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014094 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14095 int kind = PyUnicode_KIND(seq);
14096 void *data = PyUnicode_DATA(seq);
14097 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14098 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014099 if (item != NULL)
14100 ++it->it_index;
14101 return item;
14102 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014103
Benjamin Peterson14339b62009-01-31 16:36:08 +000014104 Py_DECREF(seq);
14105 it->it_seq = NULL;
14106 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014107}
14108
14109static PyObject *
14110unicodeiter_len(unicodeiterobject *it)
14111{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014112 Py_ssize_t len = 0;
14113 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014114 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014115 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014116}
14117
14118PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14119
14120static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014121 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014122 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014123 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014124};
14125
14126PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014127 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14128 "str_iterator", /* tp_name */
14129 sizeof(unicodeiterobject), /* tp_basicsize */
14130 0, /* tp_itemsize */
14131 /* methods */
14132 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14133 0, /* tp_print */
14134 0, /* tp_getattr */
14135 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014136 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014137 0, /* tp_repr */
14138 0, /* tp_as_number */
14139 0, /* tp_as_sequence */
14140 0, /* tp_as_mapping */
14141 0, /* tp_hash */
14142 0, /* tp_call */
14143 0, /* tp_str */
14144 PyObject_GenericGetAttr, /* tp_getattro */
14145 0, /* tp_setattro */
14146 0, /* tp_as_buffer */
14147 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14148 0, /* tp_doc */
14149 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14150 0, /* tp_clear */
14151 0, /* tp_richcompare */
14152 0, /* tp_weaklistoffset */
14153 PyObject_SelfIter, /* tp_iter */
14154 (iternextfunc)unicodeiter_next, /* tp_iternext */
14155 unicodeiter_methods, /* tp_methods */
14156 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014157};
14158
14159static PyObject *
14160unicode_iter(PyObject *seq)
14161{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014162 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014163
Benjamin Peterson14339b62009-01-31 16:36:08 +000014164 if (!PyUnicode_Check(seq)) {
14165 PyErr_BadInternalCall();
14166 return NULL;
14167 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014168 if (PyUnicode_READY(seq) == -1)
14169 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014170 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14171 if (it == NULL)
14172 return NULL;
14173 it->it_index = 0;
14174 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014175 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014176 _PyObject_GC_TRACK(it);
14177 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014178}
14179
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014180
14181size_t
14182Py_UNICODE_strlen(const Py_UNICODE *u)
14183{
14184 int res = 0;
14185 while(*u++)
14186 res++;
14187 return res;
14188}
14189
14190Py_UNICODE*
14191Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14192{
14193 Py_UNICODE *u = s1;
14194 while ((*u++ = *s2++));
14195 return s1;
14196}
14197
14198Py_UNICODE*
14199Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14200{
14201 Py_UNICODE *u = s1;
14202 while ((*u++ = *s2++))
14203 if (n-- == 0)
14204 break;
14205 return s1;
14206}
14207
14208Py_UNICODE*
14209Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14210{
14211 Py_UNICODE *u1 = s1;
14212 u1 += Py_UNICODE_strlen(u1);
14213 Py_UNICODE_strcpy(u1, s2);
14214 return s1;
14215}
14216
14217int
14218Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14219{
14220 while (*s1 && *s2 && *s1 == *s2)
14221 s1++, s2++;
14222 if (*s1 && *s2)
14223 return (*s1 < *s2) ? -1 : +1;
14224 if (*s1)
14225 return 1;
14226 if (*s2)
14227 return -1;
14228 return 0;
14229}
14230
14231int
14232Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14233{
14234 register Py_UNICODE u1, u2;
14235 for (; n != 0; n--) {
14236 u1 = *s1;
14237 u2 = *s2;
14238 if (u1 != u2)
14239 return (u1 < u2) ? -1 : +1;
14240 if (u1 == '\0')
14241 return 0;
14242 s1++;
14243 s2++;
14244 }
14245 return 0;
14246}
14247
14248Py_UNICODE*
14249Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14250{
14251 const Py_UNICODE *p;
14252 for (p = s; *p; p++)
14253 if (*p == c)
14254 return (Py_UNICODE*)p;
14255 return NULL;
14256}
14257
14258Py_UNICODE*
14259Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14260{
14261 const Py_UNICODE *p;
14262 p = s + Py_UNICODE_strlen(s);
14263 while (p != s) {
14264 p--;
14265 if (*p == c)
14266 return (Py_UNICODE*)p;
14267 }
14268 return NULL;
14269}
Victor Stinner331ea922010-08-10 16:37:20 +000014270
Victor Stinner71133ff2010-09-01 23:43:53 +000014271Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014272PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014273{
Victor Stinner577db2c2011-10-11 22:12:48 +020014274 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014275 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014276
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014277 if (!PyUnicode_Check(unicode)) {
14278 PyErr_BadArgument();
14279 return NULL;
14280 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014281 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014282 if (u == NULL)
14283 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014284 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014285 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014286 PyErr_NoMemory();
14287 return NULL;
14288 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014289 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014290 size *= sizeof(Py_UNICODE);
14291 copy = PyMem_Malloc(size);
14292 if (copy == NULL) {
14293 PyErr_NoMemory();
14294 return NULL;
14295 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014296 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014297 return copy;
14298}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014299
Georg Brandl66c221e2010-10-14 07:04:07 +000014300/* A _string module, to export formatter_parser and formatter_field_name_split
14301 to the string.Formatter class implemented in Python. */
14302
14303static PyMethodDef _string_methods[] = {
14304 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14305 METH_O, PyDoc_STR("split the argument as a field name")},
14306 {"formatter_parser", (PyCFunction) formatter_parser,
14307 METH_O, PyDoc_STR("parse the argument as a format string")},
14308 {NULL, NULL}
14309};
14310
14311static struct PyModuleDef _string_module = {
14312 PyModuleDef_HEAD_INIT,
14313 "_string",
14314 PyDoc_STR("string helper module"),
14315 0,
14316 _string_methods,
14317 NULL,
14318 NULL,
14319 NULL,
14320 NULL
14321};
14322
14323PyMODINIT_FUNC
14324PyInit__string(void)
14325{
14326 return PyModule_Create(&_string_module);
14327}
14328
14329
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014330#ifdef __cplusplus
14331}
14332#endif