blob: 6d9df182d30668ae52435b5e3659426205bf8aac [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"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050044#include "bytes_methods.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000045
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000046#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000047#include <windows.h>
48#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000049
Guido van Rossumd57fd912000-03-10 22:53:23 +000050/* Endianness switches; defaults to little endian */
51
52#ifdef WORDS_BIGENDIAN
53# define BYTEORDER_IS_BIG_ENDIAN
54#else
55# define BYTEORDER_IS_LITTLE_ENDIAN
56#endif
57
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000058/* --- Globals ------------------------------------------------------------
59
60 The globals are initialized by the _PyUnicode_Init() API and should
61 not be used before calling that API.
62
63*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000064
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000065
66#ifdef __cplusplus
67extern "C" {
68#endif
69
Victor Stinner8faf8212011-12-08 22:14:11 +010070/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
71#define MAX_UNICODE 0x10ffff
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 Stinnerc379ead2011-10-03 12:52:27 +0200121#define _PyUnicode_SHARE_UTF8(op) \
122 (assert(_PyUnicode_CHECK(op)), \
123 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
124 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
125#define _PyUnicode_SHARE_WSTR(op) \
126 (assert(_PyUnicode_CHECK(op)), \
127 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
128
Victor Stinner829c0ad2011-10-03 01:08:02 +0200129/* true if the Unicode object has an allocated UTF-8 memory block
130 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200131#define _PyUnicode_HAS_UTF8_MEMORY(op) \
132 (assert(_PyUnicode_CHECK(op)), \
133 (!PyUnicode_IS_COMPACT_ASCII(op) \
134 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200135 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
136
Victor Stinner03490912011-10-03 23:45:12 +0200137/* true if the Unicode object has an allocated wstr memory block
138 (not shared with other data) */
139#define _PyUnicode_HAS_WSTR_MEMORY(op) \
140 (assert(_PyUnicode_CHECK(op)), \
141 (_PyUnicode_WSTR(op) && \
142 (!PyUnicode_IS_READY(op) || \
143 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
144
Victor Stinner910337b2011-10-03 03:20:16 +0200145/* Generic helper macro to convert characters of different types.
146 from_type and to_type have to be valid type names, begin and end
147 are pointers to the source characters which should be of type
148 "from_type *". to is a pointer of type "to_type *" and points to the
149 buffer where the result characters are written to. */
150#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
151 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200152 to_type *_to = (to_type *) to; \
153 const from_type *_iter = (begin); \
154 const from_type *_end = (end); \
155 Py_ssize_t n = (_end) - (_iter); \
156 const from_type *_unrolled_end = \
157 _iter + (n & ~ (Py_ssize_t) 3); \
158 while (_iter < (_unrolled_end)) { \
159 _to[0] = (to_type) _iter[0]; \
160 _to[1] = (to_type) _iter[1]; \
161 _to[2] = (to_type) _iter[2]; \
162 _to[3] = (to_type) _iter[3]; \
163 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200164 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200165 while (_iter < (_end)) \
166 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200167 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200168
Walter Dörwald16807132007-05-25 13:52:07 +0000169/* This dictionary holds all interned unicode strings. Note that references
170 to strings in this dictionary are *not* counted in the string's ob_refcnt.
171 When the interned string reaches a refcnt of 0 the string deallocation
172 function will delete the reference from this dictionary.
173
174 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000175 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000176*/
177static PyObject *interned;
178
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000179/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200180static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000181
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200182/* List of static strings. */
183static _Py_Identifier *static_strings;
184
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000185/* Single character Unicode strings in the Latin-1 range are being
186 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200187static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000188
Christian Heimes190d79e2008-01-30 11:58:22 +0000189/* Fast detection of the most frequent whitespace characters */
190const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000191 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000192/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000193/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000194/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000195/* case 0x000C: * FORM FEED */
196/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000197 0, 1, 1, 1, 1, 1, 0, 0,
198 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000199/* case 0x001C: * FILE SEPARATOR */
200/* case 0x001D: * GROUP SEPARATOR */
201/* case 0x001E: * RECORD SEPARATOR */
202/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000203 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000204/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000205 1, 0, 0, 0, 0, 0, 0, 0,
206 0, 0, 0, 0, 0, 0, 0, 0,
207 0, 0, 0, 0, 0, 0, 0, 0,
208 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000209
Benjamin Peterson14339b62009-01-31 16:36:08 +0000210 0, 0, 0, 0, 0, 0, 0, 0,
211 0, 0, 0, 0, 0, 0, 0, 0,
212 0, 0, 0, 0, 0, 0, 0, 0,
213 0, 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,
217 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000218};
219
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200220/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200221static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200222static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200223static void copy_characters(
224 PyObject *to, Py_ssize_t to_start,
225 PyObject *from, Py_ssize_t from_start,
226 Py_ssize_t how_many);
Victor Stinner488fa492011-12-12 00:01:39 +0100227static int unicode_modifiable(PyObject *unicode);
228
Victor Stinnerfe226c02011-10-03 03:52:20 +0200229
Alexander Belopolsky40018472011-02-26 01:02:56 +0000230static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200231unicode_fromascii(const unsigned char *s, Py_ssize_t size);
232static PyObject *
233_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
234static PyObject *
235_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
236static PyObject *
237_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
238
239static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000240unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000241 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100242 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000243 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
244
Alexander Belopolsky40018472011-02-26 01:02:56 +0000245static void
246raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300247 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100248 PyObject *unicode,
249 Py_ssize_t startpos, Py_ssize_t endpos,
250 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000251
Christian Heimes190d79e2008-01-30 11:58:22 +0000252/* Same for linebreaks */
253static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000254 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000255/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000256/* 0x000B, * LINE TABULATION */
257/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000258/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000259 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000260 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000261/* 0x001C, * FILE SEPARATOR */
262/* 0x001D, * GROUP SEPARATOR */
263/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000264 0, 0, 0, 0, 1, 1, 1, 0,
265 0, 0, 0, 0, 0, 0, 0, 0,
266 0, 0, 0, 0, 0, 0, 0, 0,
267 0, 0, 0, 0, 0, 0, 0, 0,
268 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000269
Benjamin Peterson14339b62009-01-31 16:36:08 +0000270 0, 0, 0, 0, 0, 0, 0, 0,
271 0, 0, 0, 0, 0, 0, 0, 0,
272 0, 0, 0, 0, 0, 0, 0, 0,
273 0, 0, 0, 0, 0, 0, 0, 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};
279
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300280/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
281 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000282Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000283PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000284{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000285#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000286 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000287#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000288 /* This is actually an illegal character, so it should
289 not be passed to unichr. */
290 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000291#endif
292}
293
Victor Stinner910337b2011-10-03 03:20:16 +0200294#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200295int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100296_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200297{
298 PyASCIIObject *ascii;
299 unsigned int kind;
300
301 assert(PyUnicode_Check(op));
302
303 ascii = (PyASCIIObject *)op;
304 kind = ascii->state.kind;
305
Victor Stinnera3b334d2011-10-03 13:53:37 +0200306 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200307 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200308 assert(ascii->state.ready == 1);
309 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200310 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200311 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200312 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200313
Victor Stinnera41463c2011-10-04 01:05:08 +0200314 if (ascii->state.compact == 1) {
315 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200316 assert(kind == PyUnicode_1BYTE_KIND
317 || kind == PyUnicode_2BYTE_KIND
318 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200319 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200320 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200321 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100322 }
323 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200324 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
325
326 data = unicode->data.any;
327 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100328 assert(ascii->length == 0);
329 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200330 assert(ascii->state.compact == 0);
331 assert(ascii->state.ascii == 0);
332 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100333 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 assert(ascii->wstr != NULL);
335 assert(data == NULL);
336 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200337 }
338 else {
339 assert(kind == PyUnicode_1BYTE_KIND
340 || kind == PyUnicode_2BYTE_KIND
341 || kind == PyUnicode_4BYTE_KIND);
342 assert(ascii->state.compact == 0);
343 assert(ascii->state.ready == 1);
344 assert(data != NULL);
345 if (ascii->state.ascii) {
346 assert (compact->utf8 == data);
347 assert (compact->utf8_length == ascii->length);
348 }
349 else
350 assert (compact->utf8 != data);
351 }
352 }
353 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200354 if (
355#if SIZEOF_WCHAR_T == 2
356 kind == PyUnicode_2BYTE_KIND
357#else
358 kind == PyUnicode_4BYTE_KIND
359#endif
360 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200361 {
362 assert(ascii->wstr == data);
363 assert(compact->wstr_length == ascii->length);
364 } else
365 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200366 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200367
368 if (compact->utf8 == NULL)
369 assert(compact->utf8_length == 0);
370 if (ascii->wstr == NULL)
371 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200372 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200373 /* check that the best kind is used */
374 if (check_content && kind != PyUnicode_WCHAR_KIND)
375 {
376 Py_ssize_t i;
377 Py_UCS4 maxchar = 0;
378 void *data = PyUnicode_DATA(ascii);
379 for (i=0; i < ascii->length; i++)
380 {
381 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
382 if (ch > maxchar)
383 maxchar = ch;
384 }
385 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100386 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200387 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100388 assert(maxchar <= 255);
389 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200390 else
391 assert(maxchar < 128);
392 }
Victor Stinner77faf692011-11-20 18:56:05 +0100393 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200394 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100395 assert(maxchar <= 0xFFFF);
396 }
397 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200398 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100399 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100400 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200401 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400402 return 1;
403}
Victor Stinner910337b2011-10-03 03:20:16 +0200404#endif
405
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100406static PyObject*
407unicode_result_wchar(PyObject *unicode)
408{
409#ifndef Py_DEBUG
410 Py_ssize_t len;
411
412 assert(Py_REFCNT(unicode) == 1);
413
414 len = _PyUnicode_WSTR_LENGTH(unicode);
415 if (len == 0) {
416 Py_INCREF(unicode_empty);
417 Py_DECREF(unicode);
418 return unicode_empty;
419 }
420
421 if (len == 1) {
422 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
423 if (ch < 256) {
424 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
425 Py_DECREF(unicode);
426 return latin1_char;
427 }
428 }
429
430 if (_PyUnicode_Ready(unicode) < 0) {
431 Py_XDECREF(unicode);
432 return NULL;
433 }
434#else
435 /* don't make the result ready in debug mode to ensure that the caller
436 makes the string ready before using it */
437 assert(_PyUnicode_CheckConsistency(unicode, 1));
438#endif
439 return unicode;
440}
441
442static PyObject*
443unicode_result_ready(PyObject *unicode)
444{
445 Py_ssize_t length;
446
447 length = PyUnicode_GET_LENGTH(unicode);
448 if (length == 0) {
449 if (unicode != unicode_empty) {
450 Py_INCREF(unicode_empty);
451 Py_DECREF(unicode);
452 }
453 return unicode_empty;
454 }
455
456 if (length == 1) {
457 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
458 if (ch < 256) {
459 PyObject *latin1_char = unicode_latin1[ch];
460 if (latin1_char != NULL) {
461 if (unicode != latin1_char) {
462 Py_INCREF(latin1_char);
463 Py_DECREF(unicode);
464 }
465 return latin1_char;
466 }
467 else {
468 assert(_PyUnicode_CheckConsistency(unicode, 1));
469 Py_INCREF(unicode);
470 unicode_latin1[ch] = unicode;
471 return unicode;
472 }
473 }
474 }
475
476 assert(_PyUnicode_CheckConsistency(unicode, 1));
477 return unicode;
478}
479
480static PyObject*
481unicode_result(PyObject *unicode)
482{
483 assert(_PyUnicode_CHECK(unicode));
484 if (PyUnicode_IS_READY(unicode))
485 return unicode_result_ready(unicode);
486 else
487 return unicode_result_wchar(unicode);
488}
489
Victor Stinnerc4b49542011-12-11 22:44:26 +0100490static PyObject*
491unicode_result_unchanged(PyObject *unicode)
492{
493 if (PyUnicode_CheckExact(unicode)) {
494 if (PyUnicode_READY(unicode) < 0)
495 return NULL;
496 Py_INCREF(unicode);
497 return unicode;
498 }
499 else
500 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100501 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100502}
503
Victor Stinner3a50e702011-10-18 21:21:00 +0200504#ifdef HAVE_MBCS
505static OSVERSIONINFOEX winver;
506#endif
507
Thomas Wouters477c8d52006-05-27 19:21:47 +0000508/* --- Bloom Filters ----------------------------------------------------- */
509
510/* stuff to implement simple "bloom filters" for Unicode characters.
511 to keep things simple, we use a single bitmask, using the least 5
512 bits from each unicode characters as the bit index. */
513
514/* the linebreak mask is set up by Unicode_Init below */
515
Antoine Pitrouf068f942010-01-13 14:19:12 +0000516#if LONG_BIT >= 128
517#define BLOOM_WIDTH 128
518#elif LONG_BIT >= 64
519#define BLOOM_WIDTH 64
520#elif LONG_BIT >= 32
521#define BLOOM_WIDTH 32
522#else
523#error "LONG_BIT is smaller than 32"
524#endif
525
Thomas Wouters477c8d52006-05-27 19:21:47 +0000526#define BLOOM_MASK unsigned long
527
528static BLOOM_MASK bloom_linebreak;
529
Antoine Pitrouf068f942010-01-13 14:19:12 +0000530#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
531#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000532
Benjamin Peterson29060642009-01-31 22:14:21 +0000533#define BLOOM_LINEBREAK(ch) \
534 ((ch) < 128U ? ascii_linebreak[(ch)] : \
535 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000536
Alexander Belopolsky40018472011-02-26 01:02:56 +0000537Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200538make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539{
540 /* calculate simple bloom-style bitmask for a given unicode string */
541
Antoine Pitrouf068f942010-01-13 14:19:12 +0000542 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543 Py_ssize_t i;
544
545 mask = 0;
546 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200547 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000548
549 return mask;
550}
551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200552#define BLOOM_MEMBER(mask, chr, str) \
553 (BLOOM(mask, chr) \
554 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000555
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200556/* Compilation of templated routines */
557
558#include "stringlib/asciilib.h"
559#include "stringlib/fastsearch.h"
560#include "stringlib/partition.h"
561#include "stringlib/split.h"
562#include "stringlib/count.h"
563#include "stringlib/find.h"
564#include "stringlib/find_max_char.h"
565#include "stringlib/localeutil.h"
566#include "stringlib/undef.h"
567
568#include "stringlib/ucs1lib.h"
569#include "stringlib/fastsearch.h"
570#include "stringlib/partition.h"
571#include "stringlib/split.h"
572#include "stringlib/count.h"
573#include "stringlib/find.h"
574#include "stringlib/find_max_char.h"
575#include "stringlib/localeutil.h"
576#include "stringlib/undef.h"
577
578#include "stringlib/ucs2lib.h"
579#include "stringlib/fastsearch.h"
580#include "stringlib/partition.h"
581#include "stringlib/split.h"
582#include "stringlib/count.h"
583#include "stringlib/find.h"
584#include "stringlib/find_max_char.h"
585#include "stringlib/localeutil.h"
586#include "stringlib/undef.h"
587
588#include "stringlib/ucs4lib.h"
589#include "stringlib/fastsearch.h"
590#include "stringlib/partition.h"
591#include "stringlib/split.h"
592#include "stringlib/count.h"
593#include "stringlib/find.h"
594#include "stringlib/find_max_char.h"
595#include "stringlib/localeutil.h"
596#include "stringlib/undef.h"
597
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200598#include "stringlib/unicodedefs.h"
599#include "stringlib/fastsearch.h"
600#include "stringlib/count.h"
601#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100602#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200603
Guido van Rossumd57fd912000-03-10 22:53:23 +0000604/* --- Unicode Object ----------------------------------------------------- */
605
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200606static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200607fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200608
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200609Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
610 Py_ssize_t size, Py_UCS4 ch,
611 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200612{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200613 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
614
615 switch (kind) {
616 case PyUnicode_1BYTE_KIND:
617 {
618 Py_UCS1 ch1 = (Py_UCS1) ch;
619 if (ch1 == ch)
620 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
621 else
622 return -1;
623 }
624 case PyUnicode_2BYTE_KIND:
625 {
626 Py_UCS2 ch2 = (Py_UCS2) ch;
627 if (ch2 == ch)
628 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
629 else
630 return -1;
631 }
632 case PyUnicode_4BYTE_KIND:
633 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
634 default:
635 assert(0);
636 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200637 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200638}
639
Victor Stinnerfe226c02011-10-03 03:52:20 +0200640static PyObject*
641resize_compact(PyObject *unicode, Py_ssize_t length)
642{
643 Py_ssize_t char_size;
644 Py_ssize_t struct_size;
645 Py_ssize_t new_size;
646 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100647 PyObject *new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200648 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100649 assert(PyUnicode_IS_COMPACT(unicode));
650
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200651 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100652 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200653 struct_size = sizeof(PyASCIIObject);
654 else
655 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200656 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200657
Victor Stinnerfe226c02011-10-03 03:52:20 +0200658 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
659 PyErr_NoMemory();
660 return NULL;
661 }
662 new_size = (struct_size + (length + 1) * char_size);
663
Victor Stinner84def372011-12-11 20:04:56 +0100664 _Py_DEC_REFTOTAL;
665 _Py_ForgetReference(unicode);
666
667 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
668 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100669 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200670 PyErr_NoMemory();
671 return NULL;
672 }
Victor Stinner84def372011-12-11 20:04:56 +0100673 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200674 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100675
Victor Stinnerfe226c02011-10-03 03:52:20 +0200676 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200677 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200678 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100679 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200680 _PyUnicode_WSTR_LENGTH(unicode) = length;
681 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200682 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
683 length, 0);
684 return unicode;
685}
686
Alexander Belopolsky40018472011-02-26 01:02:56 +0000687static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200688resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000689{
Victor Stinner95663112011-10-04 01:03:50 +0200690 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100691 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200692 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200693 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000694
Victor Stinnerfe226c02011-10-03 03:52:20 +0200695 if (PyUnicode_IS_READY(unicode)) {
696 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200697 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200698 void *data;
699
700 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200701 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200702 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
703 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200704
705 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
706 PyErr_NoMemory();
707 return -1;
708 }
709 new_size = (length + 1) * char_size;
710
Victor Stinner7a9105a2011-12-12 00:13:42 +0100711 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
712 {
713 PyObject_DEL(_PyUnicode_UTF8(unicode));
714 _PyUnicode_UTF8(unicode) = NULL;
715 _PyUnicode_UTF8_LENGTH(unicode) = 0;
716 }
717
Victor Stinnerfe226c02011-10-03 03:52:20 +0200718 data = (PyObject *)PyObject_REALLOC(data, new_size);
719 if (data == NULL) {
720 PyErr_NoMemory();
721 return -1;
722 }
723 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200724 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200725 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200726 _PyUnicode_WSTR_LENGTH(unicode) = length;
727 }
728 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200729 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200730 _PyUnicode_UTF8_LENGTH(unicode) = length;
731 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200732 _PyUnicode_LENGTH(unicode) = length;
733 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200734 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200735 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200736 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200737 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200738 }
Victor Stinner95663112011-10-04 01:03:50 +0200739 assert(_PyUnicode_WSTR(unicode) != NULL);
740
741 /* check for integer overflow */
742 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
743 PyErr_NoMemory();
744 return -1;
745 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100746 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200747 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100748 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200749 if (!wstr) {
750 PyErr_NoMemory();
751 return -1;
752 }
753 _PyUnicode_WSTR(unicode) = wstr;
754 _PyUnicode_WSTR(unicode)[length] = 0;
755 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200756 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000757 return 0;
758}
759
Victor Stinnerfe226c02011-10-03 03:52:20 +0200760static PyObject*
761resize_copy(PyObject *unicode, Py_ssize_t length)
762{
763 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100764 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200765 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100766
767 if (PyUnicode_READY(unicode) < 0)
768 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200769
770 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
771 if (copy == NULL)
772 return NULL;
773
774 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200775 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200776 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200777 }
778 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200779 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100780
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200781 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200782 if (w == NULL)
783 return NULL;
784 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
785 copy_length = Py_MIN(copy_length, length);
786 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
787 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200788 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200789 }
790}
791
Guido van Rossumd57fd912000-03-10 22:53:23 +0000792/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000793 Ux0000 terminated; some code (e.g. new_identifier)
794 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000795
796 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000797 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000798
799*/
800
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200801#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200802static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200803#endif
804
Alexander Belopolsky40018472011-02-26 01:02:56 +0000805static PyUnicodeObject *
806_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000807{
808 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200809 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000810
Thomas Wouters477c8d52006-05-27 19:21:47 +0000811 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000812 if (length == 0 && unicode_empty != NULL) {
813 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200814 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000815 }
816
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000817 /* Ensure we won't overflow the size. */
818 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
819 return (PyUnicodeObject *)PyErr_NoMemory();
820 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200821 if (length < 0) {
822 PyErr_SetString(PyExc_SystemError,
823 "Negative size passed to _PyUnicode_New");
824 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000825 }
826
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200827#ifdef Py_DEBUG
828 ++unicode_old_new_calls;
829#endif
830
831 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
832 if (unicode == NULL)
833 return NULL;
834 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
835 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
836 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100837 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000838 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100839 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000840 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200841
Jeremy Hyltond8082792003-09-16 19:41:39 +0000842 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000843 * the caller fails before initializing str -- unicode_resize()
844 * reads str[0], and the Keep-Alive optimization can keep memory
845 * allocated for str alive across a call to unicode_dealloc(unicode).
846 * We don't want unicode_resize to read uninitialized memory in
847 * that case.
848 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200849 _PyUnicode_WSTR(unicode)[0] = 0;
850 _PyUnicode_WSTR(unicode)[length] = 0;
851 _PyUnicode_WSTR_LENGTH(unicode) = length;
852 _PyUnicode_HASH(unicode) = -1;
853 _PyUnicode_STATE(unicode).interned = 0;
854 _PyUnicode_STATE(unicode).kind = 0;
855 _PyUnicode_STATE(unicode).compact = 0;
856 _PyUnicode_STATE(unicode).ready = 0;
857 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200858 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200859 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200860 _PyUnicode_UTF8(unicode) = NULL;
861 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100862 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000863 return unicode;
864}
865
Victor Stinnerf42dc442011-10-02 23:33:16 +0200866static const char*
867unicode_kind_name(PyObject *unicode)
868{
Victor Stinner42dfd712011-10-03 14:41:45 +0200869 /* don't check consistency: unicode_kind_name() is called from
870 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200871 if (!PyUnicode_IS_COMPACT(unicode))
872 {
873 if (!PyUnicode_IS_READY(unicode))
874 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600875 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200876 {
877 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200878 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200879 return "legacy ascii";
880 else
881 return "legacy latin1";
882 case PyUnicode_2BYTE_KIND:
883 return "legacy UCS2";
884 case PyUnicode_4BYTE_KIND:
885 return "legacy UCS4";
886 default:
887 return "<legacy invalid kind>";
888 }
889 }
890 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600891 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200892 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200893 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200894 return "ascii";
895 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200896 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200897 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200898 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200899 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200900 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200901 default:
902 return "<invalid compact kind>";
903 }
904}
905
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200906#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200907static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200908
909/* Functions wrapping macros for use in debugger */
910char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200911 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200912}
913
914void *_PyUnicode_compact_data(void *unicode) {
915 return _PyUnicode_COMPACT_DATA(unicode);
916}
917void *_PyUnicode_data(void *unicode){
918 printf("obj %p\n", unicode);
919 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
920 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
921 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
922 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
923 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
924 return PyUnicode_DATA(unicode);
925}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200926
927void
928_PyUnicode_Dump(PyObject *op)
929{
930 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200931 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
932 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
933 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200934
Victor Stinnera849a4b2011-10-03 12:12:11 +0200935 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200936 {
937 if (ascii->state.ascii)
938 data = (ascii + 1);
939 else
940 data = (compact + 1);
941 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200942 else
943 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200944 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
945
Victor Stinnera849a4b2011-10-03 12:12:11 +0200946 if (ascii->wstr == data)
947 printf("shared ");
948 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200949
Victor Stinnera3b334d2011-10-03 13:53:37 +0200950 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200951 printf(" (%zu), ", compact->wstr_length);
952 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
953 printf("shared ");
954 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200955 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200956 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200957}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200958#endif
959
960PyObject *
961PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
962{
963 PyObject *obj;
964 PyCompactUnicodeObject *unicode;
965 void *data;
966 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200967 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200968 Py_ssize_t char_size;
969 Py_ssize_t struct_size;
970
971 /* Optimization for empty strings */
972 if (size == 0 && unicode_empty != NULL) {
973 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200974 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200975 }
976
977#ifdef Py_DEBUG
978 ++unicode_new_new_calls;
979#endif
980
Victor Stinner9e9d6892011-10-04 01:02:02 +0200981 is_ascii = 0;
982 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200983 struct_size = sizeof(PyCompactUnicodeObject);
984 if (maxchar < 128) {
985 kind_state = PyUnicode_1BYTE_KIND;
986 char_size = 1;
987 is_ascii = 1;
988 struct_size = sizeof(PyASCIIObject);
989 }
990 else if (maxchar < 256) {
991 kind_state = PyUnicode_1BYTE_KIND;
992 char_size = 1;
993 }
994 else if (maxchar < 65536) {
995 kind_state = PyUnicode_2BYTE_KIND;
996 char_size = 2;
997 if (sizeof(wchar_t) == 2)
998 is_sharing = 1;
999 }
1000 else {
1001 kind_state = PyUnicode_4BYTE_KIND;
1002 char_size = 4;
1003 if (sizeof(wchar_t) == 4)
1004 is_sharing = 1;
1005 }
1006
1007 /* Ensure we won't overflow the size. */
1008 if (size < 0) {
1009 PyErr_SetString(PyExc_SystemError,
1010 "Negative size passed to PyUnicode_New");
1011 return NULL;
1012 }
1013 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1014 return PyErr_NoMemory();
1015
1016 /* Duplicated allocation code from _PyObject_New() instead of a call to
1017 * PyObject_New() so we are able to allocate space for the object and
1018 * it's data buffer.
1019 */
1020 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1021 if (obj == NULL)
1022 return PyErr_NoMemory();
1023 obj = PyObject_INIT(obj, &PyUnicode_Type);
1024 if (obj == NULL)
1025 return NULL;
1026
1027 unicode = (PyCompactUnicodeObject *)obj;
1028 if (is_ascii)
1029 data = ((PyASCIIObject*)obj) + 1;
1030 else
1031 data = unicode + 1;
1032 _PyUnicode_LENGTH(unicode) = size;
1033 _PyUnicode_HASH(unicode) = -1;
1034 _PyUnicode_STATE(unicode).interned = 0;
1035 _PyUnicode_STATE(unicode).kind = kind_state;
1036 _PyUnicode_STATE(unicode).compact = 1;
1037 _PyUnicode_STATE(unicode).ready = 1;
1038 _PyUnicode_STATE(unicode).ascii = is_ascii;
1039 if (is_ascii) {
1040 ((char*)data)[size] = 0;
1041 _PyUnicode_WSTR(unicode) = NULL;
1042 }
1043 else if (kind_state == PyUnicode_1BYTE_KIND) {
1044 ((char*)data)[size] = 0;
1045 _PyUnicode_WSTR(unicode) = NULL;
1046 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001047 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001048 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001049 }
1050 else {
1051 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001052 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001053 if (kind_state == PyUnicode_2BYTE_KIND)
1054 ((Py_UCS2*)data)[size] = 0;
1055 else /* kind_state == PyUnicode_4BYTE_KIND */
1056 ((Py_UCS4*)data)[size] = 0;
1057 if (is_sharing) {
1058 _PyUnicode_WSTR_LENGTH(unicode) = size;
1059 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1060 }
1061 else {
1062 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1063 _PyUnicode_WSTR(unicode) = NULL;
1064 }
1065 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01001066 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001067 return obj;
1068}
1069
1070#if SIZEOF_WCHAR_T == 2
1071/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1072 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001073 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001074
1075 This function assumes that unicode can hold one more code point than wstr
1076 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001077static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001078unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001079 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001080{
1081 const wchar_t *iter;
1082 Py_UCS4 *ucs4_out;
1083
Victor Stinner910337b2011-10-03 03:20:16 +02001084 assert(unicode != NULL);
1085 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001086 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1087 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1088
1089 for (iter = begin; iter < end; ) {
1090 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1091 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001092 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1093 && (iter+1) < end
1094 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001095 {
Victor Stinner551ac952011-11-29 22:58:13 +01001096 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001097 iter += 2;
1098 }
1099 else {
1100 *ucs4_out++ = *iter;
1101 iter++;
1102 }
1103 }
1104 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1105 _PyUnicode_GET_LENGTH(unicode)));
1106
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001107}
1108#endif
1109
Victor Stinnercd9950f2011-10-02 00:34:53 +02001110static int
Victor Stinner488fa492011-12-12 00:01:39 +01001111unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001112{
Victor Stinner488fa492011-12-12 00:01:39 +01001113 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001114 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001115 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001116 return -1;
1117 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001118 return 0;
1119}
1120
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001121static int
1122_copy_characters(PyObject *to, Py_ssize_t to_start,
1123 PyObject *from, Py_ssize_t from_start,
1124 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001125{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001126 unsigned int from_kind, to_kind;
1127 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001128 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001129
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001130 assert(PyUnicode_Check(from));
1131 assert(PyUnicode_Check(to));
1132 assert(PyUnicode_IS_READY(from));
1133 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001134
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001135 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1136 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1137 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001138
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001139 if (how_many == 0)
1140 return 0;
1141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001142 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001143 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001144 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001145 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001147#ifdef Py_DEBUG
1148 if (!check_maxchar
1149 && (from_kind > to_kind
1150 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001151 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001152 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1153 Py_UCS4 ch;
1154 Py_ssize_t i;
1155 for (i=0; i < how_many; i++) {
1156 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1157 assert(ch <= to_maxchar);
1158 }
1159 }
1160#endif
1161 fast = (from_kind == to_kind);
1162 if (check_maxchar
1163 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1164 {
1165 /* deny latin1 => ascii */
1166 fast = 0;
1167 }
1168
1169 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001170 Py_MEMCPY((char*)to_data + to_kind * to_start,
1171 (char*)from_data + from_kind * from_start,
1172 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001173 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001174 else if (from_kind == PyUnicode_1BYTE_KIND
1175 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001176 {
1177 _PyUnicode_CONVERT_BYTES(
1178 Py_UCS1, Py_UCS2,
1179 PyUnicode_1BYTE_DATA(from) + from_start,
1180 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1181 PyUnicode_2BYTE_DATA(to) + to_start
1182 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001183 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001184 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001185 && to_kind == PyUnicode_4BYTE_KIND)
1186 {
1187 _PyUnicode_CONVERT_BYTES(
1188 Py_UCS1, Py_UCS4,
1189 PyUnicode_1BYTE_DATA(from) + from_start,
1190 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1191 PyUnicode_4BYTE_DATA(to) + to_start
1192 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001193 }
1194 else if (from_kind == PyUnicode_2BYTE_KIND
1195 && to_kind == PyUnicode_4BYTE_KIND)
1196 {
1197 _PyUnicode_CONVERT_BYTES(
1198 Py_UCS2, Py_UCS4,
1199 PyUnicode_2BYTE_DATA(from) + from_start,
1200 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1201 PyUnicode_4BYTE_DATA(to) + to_start
1202 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001203 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001204 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001205 /* check if max_char(from substring) <= max_char(to) */
1206 if (from_kind > to_kind
1207 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001208 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001209 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001210 /* slow path to check for character overflow */
1211 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001212 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001213 Py_ssize_t i;
1214
Victor Stinner56c161a2011-10-06 02:47:11 +02001215#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001216 for (i=0; i < how_many; i++) {
1217 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001218 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001219 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1220 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001221#else
1222 if (!check_maxchar) {
1223 for (i=0; i < how_many; i++) {
1224 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1225 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1226 }
1227 }
1228 else {
1229 for (i=0; i < how_many; i++) {
1230 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1231 if (ch > to_maxchar)
1232 return 1;
1233 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1234 }
1235 }
1236#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001237 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001238 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001239 assert(0 && "inconsistent state");
1240 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001241 }
1242 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001243 return 0;
1244}
1245
1246static void
1247copy_characters(PyObject *to, Py_ssize_t to_start,
1248 PyObject *from, Py_ssize_t from_start,
1249 Py_ssize_t how_many)
1250{
1251 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1252}
1253
1254Py_ssize_t
1255PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1256 PyObject *from, Py_ssize_t from_start,
1257 Py_ssize_t how_many)
1258{
1259 int err;
1260
1261 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1262 PyErr_BadInternalCall();
1263 return -1;
1264 }
1265
1266 if (PyUnicode_READY(from))
1267 return -1;
1268 if (PyUnicode_READY(to))
1269 return -1;
1270
1271 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1272 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1273 PyErr_Format(PyExc_SystemError,
1274 "Cannot write %zi characters at %zi "
1275 "in a string of %zi characters",
1276 how_many, to_start, PyUnicode_GET_LENGTH(to));
1277 return -1;
1278 }
1279
1280 if (how_many == 0)
1281 return 0;
1282
Victor Stinner488fa492011-12-12 00:01:39 +01001283 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001284 return -1;
1285
1286 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1287 if (err) {
1288 PyErr_Format(PyExc_SystemError,
1289 "Cannot copy %s characters "
1290 "into a string of %s characters",
1291 unicode_kind_name(from),
1292 unicode_kind_name(to));
1293 return -1;
1294 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001295 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001296}
1297
Victor Stinner17222162011-09-28 22:15:37 +02001298/* Find the maximum code point and count the number of surrogate pairs so a
1299 correct string length can be computed before converting a string to UCS4.
1300 This function counts single surrogates as a character and not as a pair.
1301
1302 Return 0 on success, or -1 on error. */
1303static int
1304find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1305 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001306{
1307 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001308 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001309
Victor Stinnerc53be962011-10-02 21:33:54 +02001310 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001311 *num_surrogates = 0;
1312 *maxchar = 0;
1313
1314 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001315#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001316 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1317 && (iter+1) < end
1318 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001319 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001320 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001321 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001322 iter += 2;
1323 }
1324 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001325#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001326 {
1327 ch = *iter;
1328 iter++;
1329 }
1330 if (ch > *maxchar) {
1331 *maxchar = ch;
1332 if (*maxchar > MAX_UNICODE) {
1333 PyErr_Format(PyExc_ValueError,
1334 "character U+%x is not in range [U+0000; U+10ffff]",
1335 ch);
1336 return -1;
1337 }
1338 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001339 }
1340 return 0;
1341}
1342
1343#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001344static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001345#endif
1346
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001347int
1348_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001349{
1350 wchar_t *end;
1351 Py_UCS4 maxchar = 0;
1352 Py_ssize_t num_surrogates;
1353#if SIZEOF_WCHAR_T == 2
1354 Py_ssize_t length_wo_surrogates;
1355#endif
1356
Georg Brandl7597add2011-10-05 16:36:47 +02001357 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001358 strings were created using _PyObject_New() and where no canonical
1359 representation (the str field) has been set yet aka strings
1360 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001361 assert(_PyUnicode_CHECK(unicode));
1362 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001363 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001364 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001365 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001366 /* Actually, it should neither be interned nor be anything else: */
1367 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001368
1369#ifdef Py_DEBUG
1370 ++unicode_ready_calls;
1371#endif
1372
1373 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001374 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001375 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001376 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001377
1378 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001379 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1380 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001381 PyErr_NoMemory();
1382 return -1;
1383 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001384 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001385 _PyUnicode_WSTR(unicode), end,
1386 PyUnicode_1BYTE_DATA(unicode));
1387 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1388 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1389 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1390 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001391 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001392 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001393 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001394 }
1395 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001396 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001397 _PyUnicode_UTF8(unicode) = NULL;
1398 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001399 }
1400 PyObject_FREE(_PyUnicode_WSTR(unicode));
1401 _PyUnicode_WSTR(unicode) = NULL;
1402 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1403 }
1404 /* In this case we might have to convert down from 4-byte native
1405 wchar_t to 2-byte unicode. */
1406 else if (maxchar < 65536) {
1407 assert(num_surrogates == 0 &&
1408 "FindMaxCharAndNumSurrogatePairs() messed up");
1409
Victor Stinner506f5922011-09-28 22:34:18 +02001410#if SIZEOF_WCHAR_T == 2
1411 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001412 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001413 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1414 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1415 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001416 _PyUnicode_UTF8(unicode) = NULL;
1417 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001418#else
1419 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001420 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001421 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001422 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001423 PyErr_NoMemory();
1424 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001425 }
Victor Stinner506f5922011-09-28 22:34:18 +02001426 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1427 _PyUnicode_WSTR(unicode), end,
1428 PyUnicode_2BYTE_DATA(unicode));
1429 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1430 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1431 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001432 _PyUnicode_UTF8(unicode) = NULL;
1433 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001434 PyObject_FREE(_PyUnicode_WSTR(unicode));
1435 _PyUnicode_WSTR(unicode) = NULL;
1436 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1437#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001438 }
1439 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1440 else {
1441#if SIZEOF_WCHAR_T == 2
1442 /* in case the native representation is 2-bytes, we need to allocate a
1443 new normalized 4-byte version. */
1444 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001445 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1446 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001447 PyErr_NoMemory();
1448 return -1;
1449 }
1450 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1451 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001452 _PyUnicode_UTF8(unicode) = NULL;
1453 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001454 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1455 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001456 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001457 PyObject_FREE(_PyUnicode_WSTR(unicode));
1458 _PyUnicode_WSTR(unicode) = NULL;
1459 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1460#else
1461 assert(num_surrogates == 0);
1462
Victor Stinnerc3c74152011-10-02 20:39:55 +02001463 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001464 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001465 _PyUnicode_UTF8(unicode) = NULL;
1466 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001467 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1468#endif
1469 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1470 }
1471 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001472 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001473 return 0;
1474}
1475
Alexander Belopolsky40018472011-02-26 01:02:56 +00001476static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001477unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001478{
Walter Dörwald16807132007-05-25 13:52:07 +00001479 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001480 case SSTATE_NOT_INTERNED:
1481 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001482
Benjamin Peterson29060642009-01-31 22:14:21 +00001483 case SSTATE_INTERNED_MORTAL:
1484 /* revive dead object temporarily for DelItem */
1485 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001486 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001487 Py_FatalError(
1488 "deletion of interned string failed");
1489 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001490
Benjamin Peterson29060642009-01-31 22:14:21 +00001491 case SSTATE_INTERNED_IMMORTAL:
1492 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001493
Benjamin Peterson29060642009-01-31 22:14:21 +00001494 default:
1495 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001496 }
1497
Victor Stinner03490912011-10-03 23:45:12 +02001498 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001499 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001500 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001501 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001502 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1503 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001504
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001505 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001506}
1507
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001508#ifdef Py_DEBUG
1509static int
1510unicode_is_singleton(PyObject *unicode)
1511{
1512 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1513 if (unicode == unicode_empty)
1514 return 1;
1515 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1516 {
1517 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1518 if (ch < 256 && unicode_latin1[ch] == unicode)
1519 return 1;
1520 }
1521 return 0;
1522}
1523#endif
1524
Alexander Belopolsky40018472011-02-26 01:02:56 +00001525static int
Victor Stinner488fa492011-12-12 00:01:39 +01001526unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001527{
Victor Stinner488fa492011-12-12 00:01:39 +01001528 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001529 if (Py_REFCNT(unicode) != 1)
1530 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001531 if (_PyUnicode_HASH(unicode) != -1)
1532 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001533 if (PyUnicode_CHECK_INTERNED(unicode))
1534 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001535 if (!PyUnicode_CheckExact(unicode))
1536 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001537#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001538 /* singleton refcount is greater than 1 */
1539 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001540#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001541 return 1;
1542}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001543
Victor Stinnerfe226c02011-10-03 03:52:20 +02001544static int
1545unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1546{
1547 PyObject *unicode;
1548 Py_ssize_t old_length;
1549
1550 assert(p_unicode != NULL);
1551 unicode = *p_unicode;
1552
1553 assert(unicode != NULL);
1554 assert(PyUnicode_Check(unicode));
1555 assert(0 <= length);
1556
Victor Stinner910337b2011-10-03 03:20:16 +02001557 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001558 old_length = PyUnicode_WSTR_LENGTH(unicode);
1559 else
1560 old_length = PyUnicode_GET_LENGTH(unicode);
1561 if (old_length == length)
1562 return 0;
1563
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001564 if (length == 0) {
1565 Py_DECREF(*p_unicode);
1566 *p_unicode = unicode_empty;
1567 Py_INCREF(*p_unicode);
1568 return 0;
1569 }
1570
Victor Stinner488fa492011-12-12 00:01:39 +01001571 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001572 PyObject *copy = resize_copy(unicode, length);
1573 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001574 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001575 Py_DECREF(*p_unicode);
1576 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001577 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001578 }
1579
Victor Stinnerfe226c02011-10-03 03:52:20 +02001580 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001581 PyObject *new_unicode = resize_compact(unicode, length);
1582 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001583 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001584 *p_unicode = new_unicode;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001585 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001586 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001587 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001588 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001589}
1590
Alexander Belopolsky40018472011-02-26 01:02:56 +00001591int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001592PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001593{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001594 PyObject *unicode;
1595 if (p_unicode == NULL) {
1596 PyErr_BadInternalCall();
1597 return -1;
1598 }
1599 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001600 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001601 {
1602 PyErr_BadInternalCall();
1603 return -1;
1604 }
1605 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001606}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001607
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001608static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001609unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001610{
1611 PyObject *result;
1612 assert(PyUnicode_IS_READY(*p_unicode));
1613 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1614 return 0;
1615 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1616 maxchar);
1617 if (result == NULL)
1618 return -1;
1619 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1620 PyUnicode_GET_LENGTH(*p_unicode));
1621 Py_DECREF(*p_unicode);
1622 *p_unicode = result;
1623 return 0;
1624}
1625
1626static int
1627unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1628 Py_UCS4 ch)
1629{
1630 if (unicode_widen(p_unicode, ch) < 0)
1631 return -1;
1632 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1633 PyUnicode_DATA(*p_unicode),
1634 (*pos)++, ch);
1635 return 0;
1636}
1637
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001638static PyObject*
1639get_latin1_char(unsigned char ch)
1640{
Victor Stinnera464fc12011-10-02 20:39:30 +02001641 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001642 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001643 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001644 if (!unicode)
1645 return NULL;
1646 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001647 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001648 unicode_latin1[ch] = unicode;
1649 }
1650 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001651 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001652}
1653
Alexander Belopolsky40018472011-02-26 01:02:56 +00001654PyObject *
1655PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001656{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001657 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001658 Py_UCS4 maxchar = 0;
1659 Py_ssize_t num_surrogates;
1660
1661 if (u == NULL)
1662 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001663
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001664 /* If the Unicode data is known at construction time, we can apply
1665 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001666
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001667 /* Optimization for empty strings */
1668 if (size == 0 && unicode_empty != NULL) {
1669 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001670 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001671 }
Tim Petersced69f82003-09-16 20:30:58 +00001672
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001673 /* Single character Unicode objects in the Latin-1 range are
1674 shared when using this constructor */
1675 if (size == 1 && *u < 256)
1676 return get_latin1_char((unsigned char)*u);
1677
1678 /* If not empty and not single character, copy the Unicode data
1679 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001680 if (find_maxchar_surrogates(u, u + size,
1681 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001682 return NULL;
1683
Victor Stinner8faf8212011-12-08 22:14:11 +01001684 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001685 if (!unicode)
1686 return NULL;
1687
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001688 switch (PyUnicode_KIND(unicode)) {
1689 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001690 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001691 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1692 break;
1693 case PyUnicode_2BYTE_KIND:
1694#if Py_UNICODE_SIZE == 2
1695 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1696#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001697 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001698 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1699#endif
1700 break;
1701 case PyUnicode_4BYTE_KIND:
1702#if SIZEOF_WCHAR_T == 2
1703 /* This is the only case which has to process surrogates, thus
1704 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001705 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001706#else
1707 assert(num_surrogates == 0);
1708 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1709#endif
1710 break;
1711 default:
1712 assert(0 && "Impossible state");
1713 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001714
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001715 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001716}
1717
Alexander Belopolsky40018472011-02-26 01:02:56 +00001718PyObject *
1719PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001720{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001721 if (size < 0) {
1722 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001723 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001724 return NULL;
1725 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001726 if (u != NULL)
1727 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1728 else
1729 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001730}
1731
Alexander Belopolsky40018472011-02-26 01:02:56 +00001732PyObject *
1733PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001734{
1735 size_t size = strlen(u);
1736 if (size > PY_SSIZE_T_MAX) {
1737 PyErr_SetString(PyExc_OverflowError, "input too long");
1738 return NULL;
1739 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001740 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001741}
1742
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001743PyObject *
1744_PyUnicode_FromId(_Py_Identifier *id)
1745{
1746 if (!id->object) {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001747 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1748 strlen(id->string),
1749 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001750 if (!id->object)
1751 return NULL;
1752 PyUnicode_InternInPlace(&id->object);
1753 assert(!id->next);
1754 id->next = static_strings;
1755 static_strings = id;
1756 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001757 return id->object;
1758}
1759
1760void
1761_PyUnicode_ClearStaticStrings()
1762{
1763 _Py_Identifier *i;
1764 for (i = static_strings; i; i = i->next) {
1765 Py_DECREF(i->object);
1766 i->object = NULL;
1767 i->next = NULL;
1768 }
1769}
1770
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001771/* Internal function, don't check maximum character */
1772
Victor Stinnere57b1c02011-09-28 22:20:48 +02001773static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001774unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001775{
Victor Stinner785938e2011-12-11 20:09:03 +01001776 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001777 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001778#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001779 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001780#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001781 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001782 }
Victor Stinner785938e2011-12-11 20:09:03 +01001783 unicode = PyUnicode_New(size, 127);
1784 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001785 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001786 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1787 assert(_PyUnicode_CheckConsistency(unicode, 1));
1788 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001789}
1790
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001791static Py_UCS4
1792kind_maxchar_limit(unsigned int kind)
1793{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001794 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001795 case PyUnicode_1BYTE_KIND:
1796 return 0x80;
1797 case PyUnicode_2BYTE_KIND:
1798 return 0x100;
1799 case PyUnicode_4BYTE_KIND:
1800 return 0x10000;
1801 default:
1802 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001803 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001804 }
1805}
1806
Victor Stinner702c7342011-10-05 13:50:52 +02001807static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001808_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001809{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001810 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001811 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001812
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001813 if (size == 0) {
1814 Py_INCREF(unicode_empty);
1815 return unicode_empty;
1816 }
1817 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001818 if (size == 1)
1819 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001820
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001821 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001822 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001823 if (!res)
1824 return NULL;
1825 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001826 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001827 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001828}
1829
Victor Stinnere57b1c02011-09-28 22:20:48 +02001830static PyObject*
1831_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001832{
1833 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001834 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001835
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001836 if (size == 0) {
1837 Py_INCREF(unicode_empty);
1838 return unicode_empty;
1839 }
1840 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001841 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001842 return get_latin1_char((unsigned char)u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001843
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001844 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001845 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001846 if (!res)
1847 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001848 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001849 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001850 else {
1851 _PyUnicode_CONVERT_BYTES(
1852 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1853 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001854 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001855 return res;
1856}
1857
Victor Stinnere57b1c02011-09-28 22:20:48 +02001858static PyObject*
1859_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001860{
1861 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001862 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001863
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001864 if (size == 0) {
1865 Py_INCREF(unicode_empty);
1866 return unicode_empty;
1867 }
1868 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001869 if (size == 1 && u[0] < 256)
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001870 return get_latin1_char((unsigned char)u[0]);
1871
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001872 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001873 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001874 if (!res)
1875 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001876 if (max_char < 256)
1877 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1878 PyUnicode_1BYTE_DATA(res));
1879 else if (max_char < 0x10000)
1880 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1881 PyUnicode_2BYTE_DATA(res));
1882 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001883 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001884 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001885 return res;
1886}
1887
1888PyObject*
1889PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1890{
Victor Stinnercfed46e2011-11-22 01:29:14 +01001891 if (size < 0) {
1892 PyErr_SetString(PyExc_ValueError, "size must be positive");
1893 return NULL;
1894 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06001895 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001896 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001897 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001898 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001899 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001900 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001901 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001902 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02001903 PyErr_SetString(PyExc_SystemError, "invalid kind");
1904 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001905 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001906}
1907
Victor Stinner25a4b292011-10-06 12:31:55 +02001908/* Ensure that a string uses the most efficient storage, if it is not the
1909 case: create a new string with of the right kind. Write NULL into *p_unicode
1910 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001911static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001912unicode_adjust_maxchar(PyObject **p_unicode)
1913{
1914 PyObject *unicode, *copy;
1915 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001916 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001917 unsigned int kind;
1918
1919 assert(p_unicode != NULL);
1920 unicode = *p_unicode;
1921 assert(PyUnicode_IS_READY(unicode));
1922 if (PyUnicode_IS_ASCII(unicode))
1923 return;
1924
1925 len = PyUnicode_GET_LENGTH(unicode);
1926 kind = PyUnicode_KIND(unicode);
1927 if (kind == PyUnicode_1BYTE_KIND) {
1928 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001929 max_char = ucs1lib_find_max_char(u, u + len);
1930 if (max_char >= 128)
1931 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001932 }
1933 else if (kind == PyUnicode_2BYTE_KIND) {
1934 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001935 max_char = ucs2lib_find_max_char(u, u + len);
1936 if (max_char >= 256)
1937 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001938 }
1939 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001940 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001941 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001942 max_char = ucs4lib_find_max_char(u, u + len);
1943 if (max_char >= 0x10000)
1944 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001945 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001946 copy = PyUnicode_New(len, max_char);
1947 copy_characters(copy, 0, unicode, 0, len);
1948 Py_DECREF(unicode);
1949 *p_unicode = copy;
1950}
1951
Victor Stinner034f6cf2011-09-30 02:26:44 +02001952PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01001953_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02001954{
Victor Stinner87af4f22011-11-21 23:03:47 +01001955 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001956 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001957
Victor Stinner034f6cf2011-09-30 02:26:44 +02001958 if (!PyUnicode_Check(unicode)) {
1959 PyErr_BadInternalCall();
1960 return NULL;
1961 }
1962 if (PyUnicode_READY(unicode))
1963 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001964
Victor Stinner87af4f22011-11-21 23:03:47 +01001965 length = PyUnicode_GET_LENGTH(unicode);
1966 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001967 if (!copy)
1968 return NULL;
1969 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1970
Victor Stinner87af4f22011-11-21 23:03:47 +01001971 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
1972 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001973 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001974 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001975}
1976
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001977
Victor Stinnerbc603d12011-10-02 01:00:40 +02001978/* Widen Unicode objects to larger buffers. Don't write terminating null
1979 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001980
1981void*
1982_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1983{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001984 Py_ssize_t len;
1985 void *result;
1986 unsigned int skind;
1987
1988 if (PyUnicode_READY(s))
1989 return NULL;
1990
1991 len = PyUnicode_GET_LENGTH(s);
1992 skind = PyUnicode_KIND(s);
1993 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001994 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001995 return NULL;
1996 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06001997 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001998 case PyUnicode_2BYTE_KIND:
1999 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2000 if (!result)
2001 return PyErr_NoMemory();
2002 assert(skind == PyUnicode_1BYTE_KIND);
2003 _PyUnicode_CONVERT_BYTES(
2004 Py_UCS1, Py_UCS2,
2005 PyUnicode_1BYTE_DATA(s),
2006 PyUnicode_1BYTE_DATA(s) + len,
2007 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002008 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002009 case PyUnicode_4BYTE_KIND:
2010 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2011 if (!result)
2012 return PyErr_NoMemory();
2013 if (skind == PyUnicode_2BYTE_KIND) {
2014 _PyUnicode_CONVERT_BYTES(
2015 Py_UCS2, Py_UCS4,
2016 PyUnicode_2BYTE_DATA(s),
2017 PyUnicode_2BYTE_DATA(s) + len,
2018 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002019 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002020 else {
2021 assert(skind == PyUnicode_1BYTE_KIND);
2022 _PyUnicode_CONVERT_BYTES(
2023 Py_UCS1, Py_UCS4,
2024 PyUnicode_1BYTE_DATA(s),
2025 PyUnicode_1BYTE_DATA(s) + len,
2026 result);
2027 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002028 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002029 default:
2030 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002031 }
Victor Stinner01698042011-10-04 00:04:26 +02002032 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002033 return NULL;
2034}
2035
2036static Py_UCS4*
2037as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2038 int copy_null)
2039{
2040 int kind;
2041 void *data;
2042 Py_ssize_t len, targetlen;
2043 if (PyUnicode_READY(string) == -1)
2044 return NULL;
2045 kind = PyUnicode_KIND(string);
2046 data = PyUnicode_DATA(string);
2047 len = PyUnicode_GET_LENGTH(string);
2048 targetlen = len;
2049 if (copy_null)
2050 targetlen++;
2051 if (!target) {
2052 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2053 PyErr_NoMemory();
2054 return NULL;
2055 }
2056 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2057 if (!target) {
2058 PyErr_NoMemory();
2059 return NULL;
2060 }
2061 }
2062 else {
2063 if (targetsize < targetlen) {
2064 PyErr_Format(PyExc_SystemError,
2065 "string is longer than the buffer");
2066 if (copy_null && 0 < targetsize)
2067 target[0] = 0;
2068 return NULL;
2069 }
2070 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002071 if (kind == PyUnicode_1BYTE_KIND) {
2072 Py_UCS1 *start = (Py_UCS1 *) data;
2073 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002074 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002075 else if (kind == PyUnicode_2BYTE_KIND) {
2076 Py_UCS2 *start = (Py_UCS2 *) data;
2077 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2078 }
2079 else {
2080 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002081 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002082 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002083 if (copy_null)
2084 target[len] = 0;
2085 return target;
2086}
2087
2088Py_UCS4*
2089PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2090 int copy_null)
2091{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002092 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002093 PyErr_BadInternalCall();
2094 return NULL;
2095 }
2096 return as_ucs4(string, target, targetsize, copy_null);
2097}
2098
2099Py_UCS4*
2100PyUnicode_AsUCS4Copy(PyObject *string)
2101{
2102 return as_ucs4(string, NULL, 0, 1);
2103}
2104
2105#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002106
Alexander Belopolsky40018472011-02-26 01:02:56 +00002107PyObject *
2108PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002109{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002110 if (w == NULL) {
Victor Stinner382955f2011-12-11 21:44:00 +01002111 if (size == 0) {
2112 Py_INCREF(unicode_empty);
2113 return unicode_empty;
2114 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002115 PyErr_BadInternalCall();
2116 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002117 }
2118
Martin v. Löwis790465f2008-04-05 20:41:37 +00002119 if (size == -1) {
2120 size = wcslen(w);
2121 }
2122
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002123 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002124}
2125
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002126#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002127
Walter Dörwald346737f2007-05-31 10:44:43 +00002128static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002129makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2130 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002131{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002132 *fmt++ = '%';
2133 if (width) {
2134 if (zeropad)
2135 *fmt++ = '0';
2136 fmt += sprintf(fmt, "%d", width);
2137 }
2138 if (precision)
2139 fmt += sprintf(fmt, ".%d", precision);
2140 if (longflag)
2141 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002142 else if (longlongflag) {
2143 /* longlongflag should only ever be nonzero on machines with
2144 HAVE_LONG_LONG defined */
2145#ifdef HAVE_LONG_LONG
2146 char *f = PY_FORMAT_LONG_LONG;
2147 while (*f)
2148 *fmt++ = *f++;
2149#else
2150 /* we shouldn't ever get here */
2151 assert(0);
2152 *fmt++ = 'l';
2153#endif
2154 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002155 else if (size_tflag) {
2156 char *f = PY_FORMAT_SIZE_T;
2157 while (*f)
2158 *fmt++ = *f++;
2159 }
2160 *fmt++ = c;
2161 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002162}
2163
Victor Stinner96865452011-03-01 23:44:09 +00002164/* helper for PyUnicode_FromFormatV() */
2165
2166static const char*
2167parse_format_flags(const char *f,
2168 int *p_width, int *p_precision,
2169 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2170{
2171 int width, precision, longflag, longlongflag, size_tflag;
2172
2173 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2174 f++;
2175 width = 0;
2176 while (Py_ISDIGIT((unsigned)*f))
2177 width = (width*10) + *f++ - '0';
2178 precision = 0;
2179 if (*f == '.') {
2180 f++;
2181 while (Py_ISDIGIT((unsigned)*f))
2182 precision = (precision*10) + *f++ - '0';
2183 if (*f == '%') {
2184 /* "%.3%s" => f points to "3" */
2185 f--;
2186 }
2187 }
2188 if (*f == '\0') {
2189 /* bogus format "%.1" => go backward, f points to "1" */
2190 f--;
2191 }
2192 if (p_width != NULL)
2193 *p_width = width;
2194 if (p_precision != NULL)
2195 *p_precision = precision;
2196
2197 /* Handle %ld, %lu, %lld and %llu. */
2198 longflag = 0;
2199 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002200 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002201
2202 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002203 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002204 longflag = 1;
2205 ++f;
2206 }
2207#ifdef HAVE_LONG_LONG
2208 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002209 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002210 longlongflag = 1;
2211 f += 2;
2212 }
2213#endif
2214 }
2215 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002216 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002217 size_tflag = 1;
2218 ++f;
2219 }
2220 if (p_longflag != NULL)
2221 *p_longflag = longflag;
2222 if (p_longlongflag != NULL)
2223 *p_longlongflag = longlongflag;
2224 if (p_size_tflag != NULL)
2225 *p_size_tflag = size_tflag;
2226 return f;
2227}
2228
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002229/* maximum number of characters required for output of %ld. 21 characters
2230 allows for 64-bit integers (in decimal) and an optional sign. */
2231#define MAX_LONG_CHARS 21
2232/* maximum number of characters required for output of %lld.
2233 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2234 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2235#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2236
Walter Dörwaldd2034312007-05-18 16:29:38 +00002237PyObject *
2238PyUnicode_FromFormatV(const char *format, va_list vargs)
2239{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002240 va_list count;
2241 Py_ssize_t callcount = 0;
2242 PyObject **callresults = NULL;
2243 PyObject **callresult = NULL;
2244 Py_ssize_t n = 0;
2245 int width = 0;
2246 int precision = 0;
2247 int zeropad;
2248 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002249 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002250 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002251 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002252 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2253 Py_UCS4 argmaxchar;
2254 Py_ssize_t numbersize = 0;
2255 char *numberresults = NULL;
2256 char *numberresult = NULL;
2257 Py_ssize_t i;
2258 int kind;
2259 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002260
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002261 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002262 /* step 1: count the number of %S/%R/%A/%s format specifications
2263 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2264 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002265 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002266 * also estimate a upper bound for all the number formats in the string,
2267 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002268 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002269 for (f = format; *f; f++) {
2270 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002271 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002272 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2273 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2274 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2275 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002276
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002277 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002278#ifdef HAVE_LONG_LONG
2279 if (longlongflag) {
2280 if (width < MAX_LONG_LONG_CHARS)
2281 width = MAX_LONG_LONG_CHARS;
2282 }
2283 else
2284#endif
2285 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2286 including sign. Decimal takes the most space. This
2287 isn't enough for octal. If a width is specified we
2288 need more (which we allocate later). */
2289 if (width < MAX_LONG_CHARS)
2290 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002291
2292 /* account for the size + '\0' to separate numbers
2293 inside of the numberresults buffer */
2294 numbersize += (width + 1);
2295 }
2296 }
2297 else if ((unsigned char)*f > 127) {
2298 PyErr_Format(PyExc_ValueError,
2299 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2300 "string, got a non-ASCII byte: 0x%02x",
2301 (unsigned char)*f);
2302 return NULL;
2303 }
2304 }
2305 /* step 2: allocate memory for the results of
2306 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2307 if (callcount) {
2308 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2309 if (!callresults) {
2310 PyErr_NoMemory();
2311 return NULL;
2312 }
2313 callresult = callresults;
2314 }
2315 /* step 2.5: allocate memory for the results of formating numbers */
2316 if (numbersize) {
2317 numberresults = PyObject_Malloc(numbersize);
2318 if (!numberresults) {
2319 PyErr_NoMemory();
2320 goto fail;
2321 }
2322 numberresult = numberresults;
2323 }
2324
2325 /* step 3: format numbers and figure out how large a buffer we need */
2326 for (f = format; *f; f++) {
2327 if (*f == '%') {
2328 const char* p;
2329 int longflag;
2330 int longlongflag;
2331 int size_tflag;
2332 int numprinted;
2333
2334 p = f;
2335 zeropad = (f[1] == '0');
2336 f = parse_format_flags(f, &width, &precision,
2337 &longflag, &longlongflag, &size_tflag);
2338 switch (*f) {
2339 case 'c':
2340 {
2341 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002342 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002343 n++;
2344 break;
2345 }
2346 case '%':
2347 n++;
2348 break;
2349 case 'i':
2350 case 'd':
2351 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2352 width, precision, *f);
2353 if (longflag)
2354 numprinted = sprintf(numberresult, fmt,
2355 va_arg(count, long));
2356#ifdef HAVE_LONG_LONG
2357 else if (longlongflag)
2358 numprinted = sprintf(numberresult, fmt,
2359 va_arg(count, PY_LONG_LONG));
2360#endif
2361 else if (size_tflag)
2362 numprinted = sprintf(numberresult, fmt,
2363 va_arg(count, Py_ssize_t));
2364 else
2365 numprinted = sprintf(numberresult, fmt,
2366 va_arg(count, int));
2367 n += numprinted;
2368 /* advance by +1 to skip over the '\0' */
2369 numberresult += (numprinted + 1);
2370 assert(*(numberresult - 1) == '\0');
2371 assert(*(numberresult - 2) != '\0');
2372 assert(numprinted >= 0);
2373 assert(numberresult <= numberresults + numbersize);
2374 break;
2375 case 'u':
2376 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2377 width, precision, 'u');
2378 if (longflag)
2379 numprinted = sprintf(numberresult, fmt,
2380 va_arg(count, unsigned long));
2381#ifdef HAVE_LONG_LONG
2382 else if (longlongflag)
2383 numprinted = sprintf(numberresult, fmt,
2384 va_arg(count, unsigned PY_LONG_LONG));
2385#endif
2386 else if (size_tflag)
2387 numprinted = sprintf(numberresult, fmt,
2388 va_arg(count, size_t));
2389 else
2390 numprinted = sprintf(numberresult, fmt,
2391 va_arg(count, unsigned int));
2392 n += numprinted;
2393 numberresult += (numprinted + 1);
2394 assert(*(numberresult - 1) == '\0');
2395 assert(*(numberresult - 2) != '\0');
2396 assert(numprinted >= 0);
2397 assert(numberresult <= numberresults + numbersize);
2398 break;
2399 case 'x':
2400 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2401 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2402 n += numprinted;
2403 numberresult += (numprinted + 1);
2404 assert(*(numberresult - 1) == '\0');
2405 assert(*(numberresult - 2) != '\0');
2406 assert(numprinted >= 0);
2407 assert(numberresult <= numberresults + numbersize);
2408 break;
2409 case 'p':
2410 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2411 /* %p is ill-defined: ensure leading 0x. */
2412 if (numberresult[1] == 'X')
2413 numberresult[1] = 'x';
2414 else if (numberresult[1] != 'x') {
2415 memmove(numberresult + 2, numberresult,
2416 strlen(numberresult) + 1);
2417 numberresult[0] = '0';
2418 numberresult[1] = 'x';
2419 numprinted += 2;
2420 }
2421 n += numprinted;
2422 numberresult += (numprinted + 1);
2423 assert(*(numberresult - 1) == '\0');
2424 assert(*(numberresult - 2) != '\0');
2425 assert(numprinted >= 0);
2426 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002427 break;
2428 case 's':
2429 {
2430 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002431 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002432 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002433 if (!str)
2434 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002435 /* since PyUnicode_DecodeUTF8 returns already flexible
2436 unicode objects, there is no need to call ready on them */
2437 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002438 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002439 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002440 /* Remember the str and switch to the next slot */
2441 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002442 break;
2443 }
2444 case 'U':
2445 {
2446 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002447 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002448 if (PyUnicode_READY(obj) == -1)
2449 goto fail;
2450 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002451 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002452 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002453 break;
2454 }
2455 case 'V':
2456 {
2457 PyObject *obj = va_arg(count, PyObject *);
2458 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002459 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002460 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002461 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002462 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002463 if (PyUnicode_READY(obj) == -1)
2464 goto fail;
2465 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002466 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002467 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002468 *callresult++ = NULL;
2469 }
2470 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002471 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002472 if (!str_obj)
2473 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002474 if (PyUnicode_READY(str_obj)) {
2475 Py_DECREF(str_obj);
2476 goto fail;
2477 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002478 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002479 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002480 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002481 *callresult++ = str_obj;
2482 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002483 break;
2484 }
2485 case 'S':
2486 {
2487 PyObject *obj = va_arg(count, PyObject *);
2488 PyObject *str;
2489 assert(obj);
2490 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002491 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002492 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002493 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002494 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002495 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002496 /* Remember the str and switch to the next slot */
2497 *callresult++ = str;
2498 break;
2499 }
2500 case 'R':
2501 {
2502 PyObject *obj = va_arg(count, PyObject *);
2503 PyObject *repr;
2504 assert(obj);
2505 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002506 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002507 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002508 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002509 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002510 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002511 /* Remember the repr and switch to the next slot */
2512 *callresult++ = repr;
2513 break;
2514 }
2515 case 'A':
2516 {
2517 PyObject *obj = va_arg(count, PyObject *);
2518 PyObject *ascii;
2519 assert(obj);
2520 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002521 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002522 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002523 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002524 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002525 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002526 /* Remember the repr and switch to the next slot */
2527 *callresult++ = ascii;
2528 break;
2529 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002530 default:
2531 /* if we stumble upon an unknown
2532 formatting code, copy the rest of
2533 the format string to the output
2534 string. (we cannot just skip the
2535 code, since there's no way to know
2536 what's in the argument list) */
2537 n += strlen(p);
2538 goto expand;
2539 }
2540 } else
2541 n++;
2542 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002543 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002544 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002545 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002546 we don't have to resize the string.
2547 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002548 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002549 if (!string)
2550 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002551 kind = PyUnicode_KIND(string);
2552 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002553 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002554 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002555
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002556 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002557 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002558 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002559
2560 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002561 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2562 /* checking for == because the last argument could be a empty
2563 string, which causes i to point to end, the assert at the end of
2564 the loop */
2565 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002566
Benjamin Peterson14339b62009-01-31 16:36:08 +00002567 switch (*f) {
2568 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002569 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002570 const int ordinal = va_arg(vargs, int);
2571 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002572 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002573 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002574 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002575 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002576 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002577 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002578 case 'p':
2579 /* unused, since we already have the result */
2580 if (*f == 'p')
2581 (void) va_arg(vargs, void *);
2582 else
2583 (void) va_arg(vargs, int);
2584 /* extract the result from numberresults and append. */
2585 for (; *numberresult; ++i, ++numberresult)
2586 PyUnicode_WRITE(kind, data, i, *numberresult);
2587 /* skip over the separating '\0' */
2588 assert(*numberresult == '\0');
2589 numberresult++;
2590 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002591 break;
2592 case 's':
2593 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002594 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002595 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002596 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002597 size = PyUnicode_GET_LENGTH(*callresult);
2598 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002599 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002600 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002601 /* We're done with the unicode()/repr() => forget it */
2602 Py_DECREF(*callresult);
2603 /* switch to next unicode()/repr() result */
2604 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002605 break;
2606 }
2607 case 'U':
2608 {
2609 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002610 Py_ssize_t size;
2611 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2612 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002613 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002614 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002615 break;
2616 }
2617 case 'V':
2618 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002619 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002620 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002621 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002622 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002623 size = PyUnicode_GET_LENGTH(obj);
2624 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002625 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002626 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002627 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002628 size = PyUnicode_GET_LENGTH(*callresult);
2629 assert(PyUnicode_KIND(*callresult) <=
2630 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002631 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002632 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002633 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002634 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002635 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002636 break;
2637 }
2638 case 'S':
2639 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002640 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002641 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002642 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002643 /* unused, since we already have the result */
2644 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002645 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002646 copy_characters(string, i, *callresult, 0, size);
2647 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002648 /* We're done with the unicode()/repr() => forget it */
2649 Py_DECREF(*callresult);
2650 /* switch to next unicode()/repr() result */
2651 ++callresult;
2652 break;
2653 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002654 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002655 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002656 break;
2657 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002658 for (; *p; ++p, ++i)
2659 PyUnicode_WRITE(kind, data, i, *p);
2660 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002661 goto end;
2662 }
Victor Stinner1205f272010-09-11 00:54:47 +00002663 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002664 else {
2665 assert(i < PyUnicode_GET_LENGTH(string));
2666 PyUnicode_WRITE(kind, data, i++, *f);
2667 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002668 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002669 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002670
Benjamin Peterson29060642009-01-31 22:14:21 +00002671 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002672 if (callresults)
2673 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002674 if (numberresults)
2675 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002676 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002677 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002678 if (callresults) {
2679 PyObject **callresult2 = callresults;
2680 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002681 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002682 ++callresult2;
2683 }
2684 PyObject_Free(callresults);
2685 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002686 if (numberresults)
2687 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002688 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002689}
2690
Walter Dörwaldd2034312007-05-18 16:29:38 +00002691PyObject *
2692PyUnicode_FromFormat(const char *format, ...)
2693{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002694 PyObject* ret;
2695 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002696
2697#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002698 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002699#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002700 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002701#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002702 ret = PyUnicode_FromFormatV(format, vargs);
2703 va_end(vargs);
2704 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002705}
2706
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002707#ifdef HAVE_WCHAR_H
2708
Victor Stinner5593d8a2010-10-02 11:11:27 +00002709/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2710 convert a Unicode object to a wide character string.
2711
Victor Stinnerd88d9832011-09-06 02:00:05 +02002712 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002713 character) required to convert the unicode object. Ignore size argument.
2714
Victor Stinnerd88d9832011-09-06 02:00:05 +02002715 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002716 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002717 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002718static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002719unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002720 wchar_t *w,
2721 Py_ssize_t size)
2722{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002723 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002724 const wchar_t *wstr;
2725
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002726 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002727 if (wstr == NULL)
2728 return -1;
2729
Victor Stinner5593d8a2010-10-02 11:11:27 +00002730 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002731 if (size > res)
2732 size = res + 1;
2733 else
2734 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002735 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002736 return res;
2737 }
2738 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002739 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002740}
2741
2742Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002743PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002744 wchar_t *w,
2745 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002746{
2747 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002748 PyErr_BadInternalCall();
2749 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002750 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002751 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002752}
2753
Victor Stinner137c34c2010-09-29 10:25:54 +00002754wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002755PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002756 Py_ssize_t *size)
2757{
2758 wchar_t* buffer;
2759 Py_ssize_t buflen;
2760
2761 if (unicode == NULL) {
2762 PyErr_BadInternalCall();
2763 return NULL;
2764 }
2765
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002766 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002767 if (buflen == -1)
2768 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002769 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002770 PyErr_NoMemory();
2771 return NULL;
2772 }
2773
Victor Stinner137c34c2010-09-29 10:25:54 +00002774 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2775 if (buffer == NULL) {
2776 PyErr_NoMemory();
2777 return NULL;
2778 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002779 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002780 if (buflen == -1)
2781 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002782 if (size != NULL)
2783 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002784 return buffer;
2785}
2786
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002787#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002788
Alexander Belopolsky40018472011-02-26 01:02:56 +00002789PyObject *
2790PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002791{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002792 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002793 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002794 PyErr_SetString(PyExc_ValueError,
2795 "chr() arg not in range(0x110000)");
2796 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002797 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002799 if (ordinal < 256)
2800 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002801
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002802 v = PyUnicode_New(1, ordinal);
2803 if (v == NULL)
2804 return NULL;
2805 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002806 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002807 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002808}
2809
Alexander Belopolsky40018472011-02-26 01:02:56 +00002810PyObject *
2811PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002812{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002813 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002814 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002815 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002816 if (PyUnicode_READY(obj))
2817 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002818 Py_INCREF(obj);
2819 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002820 }
2821 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002822 /* For a Unicode subtype that's not a Unicode object,
2823 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002824 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002825 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002826 PyErr_Format(PyExc_TypeError,
2827 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002828 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002829 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002830}
2831
Alexander Belopolsky40018472011-02-26 01:02:56 +00002832PyObject *
2833PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002834 const char *encoding,
2835 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002836{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002837 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002838 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002839
Guido van Rossumd57fd912000-03-10 22:53:23 +00002840 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002841 PyErr_BadInternalCall();
2842 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002843 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002844
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002845 /* Decoding bytes objects is the most common case and should be fast */
2846 if (PyBytes_Check(obj)) {
2847 if (PyBytes_GET_SIZE(obj) == 0) {
2848 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002849 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002850 }
2851 else {
2852 v = PyUnicode_Decode(
2853 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2854 encoding, errors);
2855 }
2856 return v;
2857 }
2858
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002859 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002860 PyErr_SetString(PyExc_TypeError,
2861 "decoding str is not supported");
2862 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002863 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002864
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002865 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2866 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2867 PyErr_Format(PyExc_TypeError,
2868 "coercing to str: need bytes, bytearray "
2869 "or buffer-like object, %.80s found",
2870 Py_TYPE(obj)->tp_name);
2871 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002872 }
Tim Petersced69f82003-09-16 20:30:58 +00002873
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002874 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002875 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002876 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002877 }
Tim Petersced69f82003-09-16 20:30:58 +00002878 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002879 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002880
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002881 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002882 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002883}
2884
Victor Stinner600d3be2010-06-10 12:00:55 +00002885/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002886 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2887 1 on success. */
2888static int
2889normalize_encoding(const char *encoding,
2890 char *lower,
2891 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002892{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002893 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002894 char *l;
2895 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002896
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002897 if (encoding == NULL) {
2898 strcpy(lower, "utf-8");
2899 return 1;
2900 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002901 e = encoding;
2902 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002903 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002904 while (*e) {
2905 if (l == l_end)
2906 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002907 if (Py_ISUPPER(*e)) {
2908 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002909 }
2910 else if (*e == '_') {
2911 *l++ = '-';
2912 e++;
2913 }
2914 else {
2915 *l++ = *e++;
2916 }
2917 }
2918 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002919 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002920}
2921
Alexander Belopolsky40018472011-02-26 01:02:56 +00002922PyObject *
2923PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002924 Py_ssize_t size,
2925 const char *encoding,
2926 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002927{
2928 PyObject *buffer = NULL, *unicode;
2929 Py_buffer info;
2930 char lower[11]; /* Enough for any encoding shortcut */
2931
Fred Drakee4315f52000-05-09 19:53:39 +00002932 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002933 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002934 if ((strcmp(lower, "utf-8") == 0) ||
2935 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002936 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00002937 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002938 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002939 (strcmp(lower, "iso-8859-1") == 0))
2940 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002941#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002942 else if (strcmp(lower, "mbcs") == 0)
2943 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002944#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002945 else if (strcmp(lower, "ascii") == 0)
2946 return PyUnicode_DecodeASCII(s, size, errors);
2947 else if (strcmp(lower, "utf-16") == 0)
2948 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2949 else if (strcmp(lower, "utf-32") == 0)
2950 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2951 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002952
2953 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002954 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002955 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002956 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002957 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002958 if (buffer == NULL)
2959 goto onError;
2960 unicode = PyCodec_Decode(buffer, encoding, errors);
2961 if (unicode == NULL)
2962 goto onError;
2963 if (!PyUnicode_Check(unicode)) {
2964 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002965 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002966 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002967 Py_DECREF(unicode);
2968 goto onError;
2969 }
2970 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002971 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00002972
Benjamin Peterson29060642009-01-31 22:14:21 +00002973 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002974 Py_XDECREF(buffer);
2975 return NULL;
2976}
2977
Alexander Belopolsky40018472011-02-26 01:02:56 +00002978PyObject *
2979PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002980 const char *encoding,
2981 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002982{
2983 PyObject *v;
2984
2985 if (!PyUnicode_Check(unicode)) {
2986 PyErr_BadArgument();
2987 goto onError;
2988 }
2989
2990 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002991 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002992
2993 /* Decode via the codec registry */
2994 v = PyCodec_Decode(unicode, encoding, errors);
2995 if (v == NULL)
2996 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002997 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002998
Benjamin Peterson29060642009-01-31 22:14:21 +00002999 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003000 return NULL;
3001}
3002
Alexander Belopolsky40018472011-02-26 01:02:56 +00003003PyObject *
3004PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003005 const char *encoding,
3006 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003007{
3008 PyObject *v;
3009
3010 if (!PyUnicode_Check(unicode)) {
3011 PyErr_BadArgument();
3012 goto onError;
3013 }
3014
3015 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003016 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003017
3018 /* Decode via the codec registry */
3019 v = PyCodec_Decode(unicode, encoding, errors);
3020 if (v == NULL)
3021 goto onError;
3022 if (!PyUnicode_Check(v)) {
3023 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003024 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003025 Py_TYPE(v)->tp_name);
3026 Py_DECREF(v);
3027 goto onError;
3028 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003029 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003030
Benjamin Peterson29060642009-01-31 22:14:21 +00003031 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003032 return NULL;
3033}
3034
Alexander Belopolsky40018472011-02-26 01:02:56 +00003035PyObject *
3036PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003037 Py_ssize_t size,
3038 const char *encoding,
3039 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003040{
3041 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003042
Guido van Rossumd57fd912000-03-10 22:53:23 +00003043 unicode = PyUnicode_FromUnicode(s, size);
3044 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003045 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003046 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3047 Py_DECREF(unicode);
3048 return v;
3049}
3050
Alexander Belopolsky40018472011-02-26 01:02:56 +00003051PyObject *
3052PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003053 const char *encoding,
3054 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003055{
3056 PyObject *v;
3057
3058 if (!PyUnicode_Check(unicode)) {
3059 PyErr_BadArgument();
3060 goto onError;
3061 }
3062
3063 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003064 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003065
3066 /* Encode via the codec registry */
3067 v = PyCodec_Encode(unicode, encoding, errors);
3068 if (v == NULL)
3069 goto onError;
3070 return v;
3071
Benjamin Peterson29060642009-01-31 22:14:21 +00003072 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003073 return NULL;
3074}
3075
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003076static size_t
3077wcstombs_errorpos(const wchar_t *wstr)
3078{
3079 size_t len;
3080#if SIZEOF_WCHAR_T == 2
3081 wchar_t buf[3];
3082#else
3083 wchar_t buf[2];
3084#endif
3085 char outbuf[MB_LEN_MAX];
3086 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003087
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003088#if SIZEOF_WCHAR_T == 2
3089 buf[2] = 0;
3090#else
3091 buf[1] = 0;
3092#endif
3093 start = wstr;
3094 while (*wstr != L'\0')
3095 {
3096 previous = wstr;
3097#if SIZEOF_WCHAR_T == 2
3098 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3099 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3100 {
3101 buf[0] = wstr[0];
3102 buf[1] = wstr[1];
3103 wstr += 2;
3104 }
3105 else {
3106 buf[0] = *wstr;
3107 buf[1] = 0;
3108 wstr++;
3109 }
3110#else
3111 buf[0] = *wstr;
3112 wstr++;
3113#endif
3114 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003115 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003116 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003117 }
3118
3119 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003120 return 0;
3121}
3122
Victor Stinner1b579672011-12-17 05:47:23 +01003123static int
3124locale_error_handler(const char *errors, int *surrogateescape)
3125{
3126 if (errors == NULL) {
3127 *surrogateescape = 0;
3128 return 0;
3129 }
3130
3131 if (strcmp(errors, "strict") == 0) {
3132 *surrogateescape = 0;
3133 return 0;
3134 }
3135 if (strcmp(errors, "surrogateescape") == 0) {
3136 *surrogateescape = 1;
3137 return 0;
3138 }
3139 PyErr_Format(PyExc_ValueError,
3140 "only 'strict' and 'surrogateescape' error handlers "
3141 "are supported, not '%s'",
3142 errors);
3143 return -1;
3144}
3145
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003146PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003147PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003148{
3149 Py_ssize_t wlen, wlen2;
3150 wchar_t *wstr;
3151 PyObject *bytes = NULL;
3152 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003153 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003154 PyObject *exc;
3155 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003156 int surrogateescape;
3157
3158 if (locale_error_handler(errors, &surrogateescape) < 0)
3159 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003160
3161 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3162 if (wstr == NULL)
3163 return NULL;
3164
3165 wlen2 = wcslen(wstr);
3166 if (wlen2 != wlen) {
3167 PyMem_Free(wstr);
3168 PyErr_SetString(PyExc_TypeError, "embedded null character");
3169 return NULL;
3170 }
3171
3172 if (surrogateescape) {
3173 /* locale encoding with surrogateescape */
3174 char *str;
3175
3176 str = _Py_wchar2char(wstr, &error_pos);
3177 if (str == NULL) {
3178 if (error_pos == (size_t)-1) {
3179 PyErr_NoMemory();
3180 PyMem_Free(wstr);
3181 return NULL;
3182 }
3183 else {
3184 goto encode_error;
3185 }
3186 }
3187 PyMem_Free(wstr);
3188
3189 bytes = PyBytes_FromString(str);
3190 PyMem_Free(str);
3191 }
3192 else {
3193 size_t len, len2;
3194
3195 len = wcstombs(NULL, wstr, 0);
3196 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003197 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003198 goto encode_error;
3199 }
3200
3201 bytes = PyBytes_FromStringAndSize(NULL, len);
3202 if (bytes == NULL) {
3203 PyMem_Free(wstr);
3204 return NULL;
3205 }
3206
3207 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3208 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003209 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003210 goto encode_error;
3211 }
3212 PyMem_Free(wstr);
3213 }
3214 return bytes;
3215
3216encode_error:
3217 errmsg = strerror(errno);
3218 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003219
3220 if (error_pos == (size_t)-1)
3221 error_pos = wcstombs_errorpos(wstr);
3222
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003223 PyMem_Free(wstr);
3224 Py_XDECREF(bytes);
3225
Victor Stinner2f197072011-12-17 07:08:30 +01003226 if (errmsg != NULL) {
3227 size_t errlen;
3228 wstr = _Py_char2wchar(errmsg, &errlen);
3229 if (wstr != NULL) {
3230 reason = PyUnicode_FromWideChar(wstr, errlen);
3231 PyMem_Free(wstr);
3232 } else
3233 errmsg = NULL;
3234 }
3235 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003236 reason = PyUnicode_FromString(
3237 "wcstombs() encountered an unencodable "
3238 "wide character");
3239 if (reason == NULL)
3240 return NULL;
3241
3242 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3243 "locale", unicode,
3244 (Py_ssize_t)error_pos,
3245 (Py_ssize_t)(error_pos+1),
3246 reason);
3247 Py_DECREF(reason);
3248 if (exc != NULL) {
3249 PyCodec_StrictErrors(exc);
3250 Py_XDECREF(exc);
3251 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003252 return NULL;
3253}
3254
Victor Stinnerad158722010-10-27 00:25:46 +00003255PyObject *
3256PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003257{
Victor Stinner99b95382011-07-04 14:23:54 +02003258#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003259 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003260#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003261 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003262#else
Victor Stinner793b5312011-04-27 00:24:21 +02003263 PyInterpreterState *interp = PyThreadState_GET()->interp;
3264 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3265 cannot use it to encode and decode filenames before it is loaded. Load
3266 the Python codec requires to encode at least its own filename. Use the C
3267 version of the locale codec until the codec registry is initialized and
3268 the Python codec is loaded.
3269
3270 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3271 cannot only rely on it: check also interp->fscodec_initialized for
3272 subinterpreters. */
3273 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003274 return PyUnicode_AsEncodedString(unicode,
3275 Py_FileSystemDefaultEncoding,
3276 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003277 }
3278 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003279 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003280 }
Victor Stinnerad158722010-10-27 00:25:46 +00003281#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003282}
3283
Alexander Belopolsky40018472011-02-26 01:02:56 +00003284PyObject *
3285PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003286 const char *encoding,
3287 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003288{
3289 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003290 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003291
Guido van Rossumd57fd912000-03-10 22:53:23 +00003292 if (!PyUnicode_Check(unicode)) {
3293 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003294 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003295 }
Fred Drakee4315f52000-05-09 19:53:39 +00003296
Fred Drakee4315f52000-05-09 19:53:39 +00003297 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003298 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003299 if ((strcmp(lower, "utf-8") == 0) ||
3300 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003301 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003302 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003303 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003304 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003305 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003306 }
Victor Stinner37296e82010-06-10 13:36:23 +00003307 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003308 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003309 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003310 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003311#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003312 else if (strcmp(lower, "mbcs") == 0)
3313 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003314#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003315 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003316 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003317 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003318
3319 /* Encode via the codec registry */
3320 v = PyCodec_Encode(unicode, encoding, errors);
3321 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003322 return NULL;
3323
3324 /* The normal path */
3325 if (PyBytes_Check(v))
3326 return v;
3327
3328 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003329 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003330 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003331 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003332
3333 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3334 "encoder %s returned bytearray instead of bytes",
3335 encoding);
3336 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003337 Py_DECREF(v);
3338 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003339 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003340
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003341 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3342 Py_DECREF(v);
3343 return b;
3344 }
3345
3346 PyErr_Format(PyExc_TypeError,
3347 "encoder did not return a bytes object (type=%.400s)",
3348 Py_TYPE(v)->tp_name);
3349 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003350 return NULL;
3351}
3352
Alexander Belopolsky40018472011-02-26 01:02:56 +00003353PyObject *
3354PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003355 const char *encoding,
3356 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003357{
3358 PyObject *v;
3359
3360 if (!PyUnicode_Check(unicode)) {
3361 PyErr_BadArgument();
3362 goto onError;
3363 }
3364
3365 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003366 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003367
3368 /* Encode via the codec registry */
3369 v = PyCodec_Encode(unicode, encoding, errors);
3370 if (v == NULL)
3371 goto onError;
3372 if (!PyUnicode_Check(v)) {
3373 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003374 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003375 Py_TYPE(v)->tp_name);
3376 Py_DECREF(v);
3377 goto onError;
3378 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003379 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003380
Benjamin Peterson29060642009-01-31 22:14:21 +00003381 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003382 return NULL;
3383}
3384
Victor Stinner2f197072011-12-17 07:08:30 +01003385static size_t
3386mbstowcs_errorpos(const char *str, size_t len)
3387{
3388#ifdef HAVE_MBRTOWC
3389 const char *start = str;
3390 mbstate_t mbs;
3391 size_t converted;
3392 wchar_t ch;
3393
3394 memset(&mbs, 0, sizeof mbs);
3395 while (len)
3396 {
3397 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3398 if (converted == 0)
3399 /* Reached end of string */
3400 break;
3401 if (converted == (size_t)-1 || converted == (size_t)-2) {
3402 /* Conversion error or incomplete character */
3403 return str - start;
3404 }
3405 else {
3406 str += converted;
3407 len -= converted;
3408 }
3409 }
3410 /* failed to find the undecodable byte sequence */
3411 return 0;
3412#endif
3413 return 0;
3414}
3415
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003416PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003417PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003418 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003419{
3420 wchar_t smallbuf[256];
3421 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3422 wchar_t *wstr;
3423 size_t wlen, wlen2;
3424 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003425 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003426 size_t error_pos;
3427 char *errmsg;
3428 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003429
3430 if (locale_error_handler(errors, &surrogateescape) < 0)
3431 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003432
3433 if (str[len] != '\0' || len != strlen(str)) {
3434 PyErr_SetString(PyExc_TypeError, "embedded null character");
3435 return NULL;
3436 }
3437
3438 if (surrogateescape)
3439 {
3440 wstr = _Py_char2wchar(str, &wlen);
3441 if (wstr == NULL) {
3442 if (wlen == (size_t)-1)
3443 PyErr_NoMemory();
3444 else
3445 PyErr_SetFromErrno(PyExc_OSError);
3446 return NULL;
3447 }
3448
3449 unicode = PyUnicode_FromWideChar(wstr, wlen);
3450 PyMem_Free(wstr);
3451 }
3452 else {
3453#ifndef HAVE_BROKEN_MBSTOWCS
3454 wlen = mbstowcs(NULL, str, 0);
3455#else
3456 wlen = len;
3457#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003458 if (wlen == (size_t)-1)
3459 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003460 if (wlen+1 <= smallbuf_len) {
3461 wstr = smallbuf;
3462 }
3463 else {
3464 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3465 return PyErr_NoMemory();
3466
3467 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3468 if (!wstr)
3469 return PyErr_NoMemory();
3470 }
3471
3472 /* This shouldn't fail now */
3473 wlen2 = mbstowcs(wstr, str, wlen+1);
3474 if (wlen2 == (size_t)-1) {
3475 if (wstr != smallbuf)
3476 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003477 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003478 }
3479#ifdef HAVE_BROKEN_MBSTOWCS
3480 assert(wlen2 == wlen);
3481#endif
3482 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3483 if (wstr != smallbuf)
3484 PyMem_Free(wstr);
3485 }
3486 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003487
3488decode_error:
3489 errmsg = strerror(errno);
3490 assert(errmsg != NULL);
3491
3492 error_pos = mbstowcs_errorpos(str, len);
3493 if (errmsg != NULL) {
3494 size_t errlen;
3495 wstr = _Py_char2wchar(errmsg, &errlen);
3496 if (wstr != NULL) {
3497 reason = PyUnicode_FromWideChar(wstr, errlen);
3498 PyMem_Free(wstr);
3499 } else
3500 errmsg = NULL;
3501 }
3502 if (errmsg == NULL)
3503 reason = PyUnicode_FromString(
3504 "mbstowcs() encountered an invalid multibyte sequence");
3505 if (reason == NULL)
3506 return NULL;
3507
3508 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3509 "locale", str, len,
3510 (Py_ssize_t)error_pos,
3511 (Py_ssize_t)(error_pos+1),
3512 reason);
3513 Py_DECREF(reason);
3514 if (exc != NULL) {
3515 PyCodec_StrictErrors(exc);
3516 Py_XDECREF(exc);
3517 }
3518 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003519}
3520
3521PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003522PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003523{
3524 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003525 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003526}
3527
3528
3529PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003530PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003531 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003532 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3533}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003534
Christian Heimes5894ba72007-11-04 11:43:14 +00003535PyObject*
3536PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3537{
Victor Stinner99b95382011-07-04 14:23:54 +02003538#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003539 return PyUnicode_DecodeMBCS(s, size, NULL);
3540#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003541 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003542#else
Victor Stinner793b5312011-04-27 00:24:21 +02003543 PyInterpreterState *interp = PyThreadState_GET()->interp;
3544 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3545 cannot use it to encode and decode filenames before it is loaded. Load
3546 the Python codec requires to encode at least its own filename. Use the C
3547 version of the locale codec until the codec registry is initialized and
3548 the Python codec is loaded.
3549
3550 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3551 cannot only rely on it: check also interp->fscodec_initialized for
3552 subinterpreters. */
3553 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003554 return PyUnicode_Decode(s, size,
3555 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003556 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003557 }
3558 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003559 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003560 }
Victor Stinnerad158722010-10-27 00:25:46 +00003561#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003562}
3563
Martin v. Löwis011e8422009-05-05 04:43:17 +00003564
3565int
3566PyUnicode_FSConverter(PyObject* arg, void* addr)
3567{
3568 PyObject *output = NULL;
3569 Py_ssize_t size;
3570 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003571 if (arg == NULL) {
3572 Py_DECREF(*(PyObject**)addr);
3573 return 1;
3574 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003575 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003576 output = arg;
3577 Py_INCREF(output);
3578 }
3579 else {
3580 arg = PyUnicode_FromObject(arg);
3581 if (!arg)
3582 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003583 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003584 Py_DECREF(arg);
3585 if (!output)
3586 return 0;
3587 if (!PyBytes_Check(output)) {
3588 Py_DECREF(output);
3589 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3590 return 0;
3591 }
3592 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003593 size = PyBytes_GET_SIZE(output);
3594 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003595 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003596 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003597 Py_DECREF(output);
3598 return 0;
3599 }
3600 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003601 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003602}
3603
3604
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003605int
3606PyUnicode_FSDecoder(PyObject* arg, void* addr)
3607{
3608 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003609 if (arg == NULL) {
3610 Py_DECREF(*(PyObject**)addr);
3611 return 1;
3612 }
3613 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003614 if (PyUnicode_READY(arg))
3615 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003616 output = arg;
3617 Py_INCREF(output);
3618 }
3619 else {
3620 arg = PyBytes_FromObject(arg);
3621 if (!arg)
3622 return 0;
3623 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3624 PyBytes_GET_SIZE(arg));
3625 Py_DECREF(arg);
3626 if (!output)
3627 return 0;
3628 if (!PyUnicode_Check(output)) {
3629 Py_DECREF(output);
3630 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3631 return 0;
3632 }
3633 }
Victor Stinner065836e2011-10-27 01:56:33 +02003634 if (PyUnicode_READY(output) < 0) {
3635 Py_DECREF(output);
3636 return 0;
3637 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003638 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003639 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003640 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3641 Py_DECREF(output);
3642 return 0;
3643 }
3644 *(PyObject**)addr = output;
3645 return Py_CLEANUP_SUPPORTED;
3646}
3647
3648
Martin v. Löwis5b222132007-06-10 09:51:05 +00003649char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003650PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003651{
Christian Heimesf3863112007-11-22 07:46:41 +00003652 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003653
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003654 if (!PyUnicode_Check(unicode)) {
3655 PyErr_BadArgument();
3656 return NULL;
3657 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003658 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003659 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003660
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003661 if (PyUnicode_UTF8(unicode) == NULL) {
3662 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003663 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3664 if (bytes == NULL)
3665 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003666 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3667 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003668 Py_DECREF(bytes);
3669 return NULL;
3670 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003671 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3672 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3673 PyBytes_AS_STRING(bytes),
3674 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003675 Py_DECREF(bytes);
3676 }
3677
3678 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003679 *psize = PyUnicode_UTF8_LENGTH(unicode);
3680 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003681}
3682
3683char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003684PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003685{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003686 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3687}
3688
3689#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003690static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003691#endif
3692
3693
3694Py_UNICODE *
3695PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3696{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003697 const unsigned char *one_byte;
3698#if SIZEOF_WCHAR_T == 4
3699 const Py_UCS2 *two_bytes;
3700#else
3701 const Py_UCS4 *four_bytes;
3702 const Py_UCS4 *ucs4_end;
3703 Py_ssize_t num_surrogates;
3704#endif
3705 wchar_t *w;
3706 wchar_t *wchar_end;
3707
3708 if (!PyUnicode_Check(unicode)) {
3709 PyErr_BadArgument();
3710 return NULL;
3711 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003712 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003713 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003714 assert(_PyUnicode_KIND(unicode) != 0);
3715 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003716
3717#ifdef Py_DEBUG
3718 ++unicode_as_unicode_calls;
3719#endif
3720
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003721 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003722#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003723 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3724 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003725 num_surrogates = 0;
3726
3727 for (; four_bytes < ucs4_end; ++four_bytes) {
3728 if (*four_bytes > 0xFFFF)
3729 ++num_surrogates;
3730 }
3731
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003732 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3733 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3734 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003735 PyErr_NoMemory();
3736 return NULL;
3737 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003738 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003739
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003740 w = _PyUnicode_WSTR(unicode);
3741 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3742 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003743 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3744 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003745 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003746 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003747 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3748 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003749 }
3750 else
3751 *w = *four_bytes;
3752
3753 if (w > wchar_end) {
3754 assert(0 && "Miscalculated string end");
3755 }
3756 }
3757 *w = 0;
3758#else
3759 /* sizeof(wchar_t) == 4 */
3760 Py_FatalError("Impossible unicode object state, wstr and str "
3761 "should share memory already.");
3762 return NULL;
3763#endif
3764 }
3765 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003766 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3767 (_PyUnicode_LENGTH(unicode) + 1));
3768 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003769 PyErr_NoMemory();
3770 return NULL;
3771 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003772 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3773 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3774 w = _PyUnicode_WSTR(unicode);
3775 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003776
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003777 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3778 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003779 for (; w < wchar_end; ++one_byte, ++w)
3780 *w = *one_byte;
3781 /* null-terminate the wstr */
3782 *w = 0;
3783 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003784 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003785#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003786 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003787 for (; w < wchar_end; ++two_bytes, ++w)
3788 *w = *two_bytes;
3789 /* null-terminate the wstr */
3790 *w = 0;
3791#else
3792 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003793 PyObject_FREE(_PyUnicode_WSTR(unicode));
3794 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003795 Py_FatalError("Impossible unicode object state, wstr "
3796 "and str should share memory already.");
3797 return NULL;
3798#endif
3799 }
3800 else {
3801 assert(0 && "This should never happen.");
3802 }
3803 }
3804 }
3805 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003806 *size = PyUnicode_WSTR_LENGTH(unicode);
3807 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003808}
3809
Alexander Belopolsky40018472011-02-26 01:02:56 +00003810Py_UNICODE *
3811PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003812{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003813 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003814}
3815
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003816
Alexander Belopolsky40018472011-02-26 01:02:56 +00003817Py_ssize_t
3818PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003819{
3820 if (!PyUnicode_Check(unicode)) {
3821 PyErr_BadArgument();
3822 goto onError;
3823 }
3824 return PyUnicode_GET_SIZE(unicode);
3825
Benjamin Peterson29060642009-01-31 22:14:21 +00003826 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003827 return -1;
3828}
3829
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003830Py_ssize_t
3831PyUnicode_GetLength(PyObject *unicode)
3832{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003833 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003834 PyErr_BadArgument();
3835 return -1;
3836 }
3837
3838 return PyUnicode_GET_LENGTH(unicode);
3839}
3840
3841Py_UCS4
3842PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3843{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003844 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3845 PyErr_BadArgument();
3846 return (Py_UCS4)-1;
3847 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003848 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003849 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003850 return (Py_UCS4)-1;
3851 }
3852 return PyUnicode_READ_CHAR(unicode, index);
3853}
3854
3855int
3856PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3857{
3858 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003859 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003860 return -1;
3861 }
Victor Stinner488fa492011-12-12 00:01:39 +01003862 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003863 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003864 PyErr_SetString(PyExc_IndexError, "string index out of range");
3865 return -1;
3866 }
Victor Stinner488fa492011-12-12 00:01:39 +01003867 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003868 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003869 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3870 index, ch);
3871 return 0;
3872}
3873
Alexander Belopolsky40018472011-02-26 01:02:56 +00003874const char *
3875PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003876{
Victor Stinner42cb4622010-09-01 19:39:01 +00003877 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003878}
3879
Victor Stinner554f3f02010-06-16 23:33:54 +00003880/* create or adjust a UnicodeDecodeError */
3881static void
3882make_decode_exception(PyObject **exceptionObject,
3883 const char *encoding,
3884 const char *input, Py_ssize_t length,
3885 Py_ssize_t startpos, Py_ssize_t endpos,
3886 const char *reason)
3887{
3888 if (*exceptionObject == NULL) {
3889 *exceptionObject = PyUnicodeDecodeError_Create(
3890 encoding, input, length, startpos, endpos, reason);
3891 }
3892 else {
3893 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3894 goto onError;
3895 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3896 goto onError;
3897 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3898 goto onError;
3899 }
3900 return;
3901
3902onError:
3903 Py_DECREF(*exceptionObject);
3904 *exceptionObject = NULL;
3905}
3906
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003907/* error handling callback helper:
3908 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003909 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003910 and adjust various state variables.
3911 return 0 on success, -1 on error
3912*/
3913
Alexander Belopolsky40018472011-02-26 01:02:56 +00003914static int
3915unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003916 const char *encoding, const char *reason,
3917 const char **input, const char **inend, Py_ssize_t *startinpos,
3918 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003919 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003920{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003921 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003922
3923 PyObject *restuple = NULL;
3924 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003925 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003926 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003927 Py_ssize_t requiredsize;
3928 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003929 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003930 int res = -1;
3931
Victor Stinner596a6c42011-11-09 00:02:18 +01003932 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
3933 outsize = PyUnicode_GET_LENGTH(*output);
3934 else
3935 outsize = _PyUnicode_WSTR_LENGTH(*output);
3936
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003937 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003938 *errorHandler = PyCodec_LookupError(errors);
3939 if (*errorHandler == NULL)
3940 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003941 }
3942
Victor Stinner554f3f02010-06-16 23:33:54 +00003943 make_decode_exception(exceptionObject,
3944 encoding,
3945 *input, *inend - *input,
3946 *startinpos, *endinpos,
3947 reason);
3948 if (*exceptionObject == NULL)
3949 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003950
3951 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3952 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003953 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003954 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003955 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003956 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003957 }
3958 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003959 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003960 if (PyUnicode_READY(repunicode) < 0)
3961 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003962
3963 /* Copy back the bytes variables, which might have been modified by the
3964 callback */
3965 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3966 if (!inputobj)
3967 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003968 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003969 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003970 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003971 *input = PyBytes_AS_STRING(inputobj);
3972 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003973 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003974 /* we can DECREF safely, as the exception has another reference,
3975 so the object won't go away. */
3976 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003977
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003978 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003979 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003980 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003981 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3982 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003983 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003984
Victor Stinner596a6c42011-11-09 00:02:18 +01003985 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
3986 /* need more space? (at least enough for what we
3987 have+the replacement+the rest of the string (starting
3988 at the new input position), so we won't have to check space
3989 when there are no errors in the rest of the string) */
3990 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
3991 requiredsize = *outpos + replen + insize-newpos;
3992 if (requiredsize > outsize) {
3993 if (requiredsize<2*outsize)
3994 requiredsize = 2*outsize;
3995 if (unicode_resize(output, requiredsize) < 0)
3996 goto onError;
3997 }
3998 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003999 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01004000 copy_characters(*output, *outpos, repunicode, 0, replen);
4001 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004002 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004003 else {
4004 wchar_t *repwstr;
4005 Py_ssize_t repwlen;
4006 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4007 if (repwstr == NULL)
4008 goto onError;
4009 /* need more space? (at least enough for what we
4010 have+the replacement+the rest of the string (starting
4011 at the new input position), so we won't have to check space
4012 when there are no errors in the rest of the string) */
4013 requiredsize = *outpos + repwlen + insize-newpos;
4014 if (requiredsize > outsize) {
4015 if (requiredsize < 2*outsize)
4016 requiredsize = 2*outsize;
4017 if (unicode_resize(output, requiredsize) < 0)
4018 goto onError;
4019 }
4020 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4021 *outpos += repwlen;
4022 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004023 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004024 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004025
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004026 /* we made it! */
4027 res = 0;
4028
Benjamin Peterson29060642009-01-31 22:14:21 +00004029 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004030 Py_XDECREF(restuple);
4031 return res;
4032}
4033
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004034/* --- UTF-7 Codec -------------------------------------------------------- */
4035
Antoine Pitrou244651a2009-05-04 18:56:13 +00004036/* See RFC2152 for details. We encode conservatively and decode liberally. */
4037
4038/* Three simple macros defining base-64. */
4039
4040/* Is c a base-64 character? */
4041
4042#define IS_BASE64(c) \
4043 (((c) >= 'A' && (c) <= 'Z') || \
4044 ((c) >= 'a' && (c) <= 'z') || \
4045 ((c) >= '0' && (c) <= '9') || \
4046 (c) == '+' || (c) == '/')
4047
4048/* given that c is a base-64 character, what is its base-64 value? */
4049
4050#define FROM_BASE64(c) \
4051 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4052 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4053 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4054 (c) == '+' ? 62 : 63)
4055
4056/* What is the base-64 character of the bottom 6 bits of n? */
4057
4058#define TO_BASE64(n) \
4059 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4060
4061/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4062 * decoded as itself. We are permissive on decoding; the only ASCII
4063 * byte not decoding to itself is the + which begins a base64
4064 * string. */
4065
4066#define DECODE_DIRECT(c) \
4067 ((c) <= 127 && (c) != '+')
4068
4069/* The UTF-7 encoder treats ASCII characters differently according to
4070 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4071 * the above). See RFC2152. This array identifies these different
4072 * sets:
4073 * 0 : "Set D"
4074 * alphanumeric and '(),-./:?
4075 * 1 : "Set O"
4076 * !"#$%&*;<=>@[]^_`{|}
4077 * 2 : "whitespace"
4078 * ht nl cr sp
4079 * 3 : special (must be base64 encoded)
4080 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4081 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004082
Tim Petersced69f82003-09-16 20:30:58 +00004083static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004084char utf7_category[128] = {
4085/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4086 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4087/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4088 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4089/* sp ! " # $ % & ' ( ) * + , - . / */
4090 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4091/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4092 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4093/* @ A B C D E F G H I J K L M N O */
4094 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4095/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4096 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4097/* ` a b c d e f g h i j k l m n o */
4098 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4099/* p q r s t u v w x y z { | } ~ del */
4100 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004101};
4102
Antoine Pitrou244651a2009-05-04 18:56:13 +00004103/* ENCODE_DIRECT: this character should be encoded as itself. The
4104 * answer depends on whether we are encoding set O as itself, and also
4105 * on whether we are encoding whitespace as itself. RFC2152 makes it
4106 * clear that the answers to these questions vary between
4107 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004108
Antoine Pitrou244651a2009-05-04 18:56:13 +00004109#define ENCODE_DIRECT(c, directO, directWS) \
4110 ((c) < 128 && (c) > 0 && \
4111 ((utf7_category[(c)] == 0) || \
4112 (directWS && (utf7_category[(c)] == 2)) || \
4113 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004114
Alexander Belopolsky40018472011-02-26 01:02:56 +00004115PyObject *
4116PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004117 Py_ssize_t size,
4118 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004119{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004120 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4121}
4122
Antoine Pitrou244651a2009-05-04 18:56:13 +00004123/* The decoder. The only state we preserve is our read position,
4124 * i.e. how many characters we have consumed. So if we end in the
4125 * middle of a shift sequence we have to back off the read position
4126 * and the output to the beginning of the sequence, otherwise we lose
4127 * all the shift state (seen bits, number of bits seen, high
4128 * surrogate). */
4129
Alexander Belopolsky40018472011-02-26 01:02:56 +00004130PyObject *
4131PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004132 Py_ssize_t size,
4133 const char *errors,
4134 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004135{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004136 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004137 Py_ssize_t startinpos;
4138 Py_ssize_t endinpos;
4139 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004140 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004141 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004142 const char *errmsg = "";
4143 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004144 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004145 unsigned int base64bits = 0;
4146 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004147 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004148 PyObject *errorHandler = NULL;
4149 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004150
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004151 /* Start off assuming it's all ASCII. Widen later as necessary. */
4152 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004153 if (!unicode)
4154 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004155 if (size == 0) {
4156 if (consumed)
4157 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004158 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004159 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004160
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004161 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004162 e = s + size;
4163
4164 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004165 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004166 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004167 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004168
Antoine Pitrou244651a2009-05-04 18:56:13 +00004169 if (inShift) { /* in a base-64 section */
4170 if (IS_BASE64(ch)) { /* consume a base-64 character */
4171 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4172 base64bits += 6;
4173 s++;
4174 if (base64bits >= 16) {
4175 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004176 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004177 base64bits -= 16;
4178 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4179 if (surrogate) {
4180 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004181 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4182 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004183 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4184 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004185 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004186 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004187 }
4188 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004189 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4190 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004191 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004192 }
4193 }
Victor Stinner551ac952011-11-29 22:58:13 +01004194 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004195 /* first surrogate */
4196 surrogate = outCh;
4197 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004198 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004199 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4200 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004201 }
4202 }
4203 }
4204 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004205 inShift = 0;
4206 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004207 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004208 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4209 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004210 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004211 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004212 if (base64bits > 0) { /* left-over bits */
4213 if (base64bits >= 6) {
4214 /* We've seen at least one base-64 character */
4215 errmsg = "partial character in shift sequence";
4216 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004217 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004218 else {
4219 /* Some bits remain; they should be zero */
4220 if (base64buffer != 0) {
4221 errmsg = "non-zero padding bits in shift sequence";
4222 goto utf7Error;
4223 }
4224 }
4225 }
4226 if (ch != '-') {
4227 /* '-' is absorbed; other terminating
4228 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004229 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4230 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004231 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004232 }
4233 }
4234 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004235 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004236 s++; /* consume '+' */
4237 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004238 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004239 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4240 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004241 }
4242 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004243 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004244 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004245 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004246 }
4247 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004248 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004249 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4250 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004251 s++;
4252 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004253 else {
4254 startinpos = s-starts;
4255 s++;
4256 errmsg = "unexpected special character";
4257 goto utf7Error;
4258 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004259 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004260utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004261 endinpos = s-starts;
4262 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004263 errors, &errorHandler,
4264 "utf7", errmsg,
4265 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004266 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004267 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004268 }
4269
Antoine Pitrou244651a2009-05-04 18:56:13 +00004270 /* end of string */
4271
4272 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4273 /* if we're in an inconsistent state, that's an error */
4274 if (surrogate ||
4275 (base64bits >= 6) ||
4276 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004277 endinpos = size;
4278 if (unicode_decode_call_errorhandler(
4279 errors, &errorHandler,
4280 "utf7", "unterminated shift sequence",
4281 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004282 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004283 goto onError;
4284 if (s < e)
4285 goto restart;
4286 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004287 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004288
4289 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004290 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004291 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004292 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004293 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004294 }
4295 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004296 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004297 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004298 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004299
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004300 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004301 goto onError;
4302
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004303 Py_XDECREF(errorHandler);
4304 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004305 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004306
Benjamin Peterson29060642009-01-31 22:14:21 +00004307 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004308 Py_XDECREF(errorHandler);
4309 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004310 Py_DECREF(unicode);
4311 return NULL;
4312}
4313
4314
Alexander Belopolsky40018472011-02-26 01:02:56 +00004315PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004316_PyUnicode_EncodeUTF7(PyObject *str,
4317 int base64SetO,
4318 int base64WhiteSpace,
4319 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004320{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004321 int kind;
4322 void *data;
4323 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004324 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004325 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004326 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004327 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004328 unsigned int base64bits = 0;
4329 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004330 char * out;
4331 char * start;
4332
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004333 if (PyUnicode_READY(str) < 0)
4334 return NULL;
4335 kind = PyUnicode_KIND(str);
4336 data = PyUnicode_DATA(str);
4337 len = PyUnicode_GET_LENGTH(str);
4338
4339 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004340 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004341
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004342 /* It might be possible to tighten this worst case */
4343 allocated = 8 * len;
4344 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004345 return PyErr_NoMemory();
4346
Antoine Pitrou244651a2009-05-04 18:56:13 +00004347 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004348 if (v == NULL)
4349 return NULL;
4350
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004351 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004352 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004353 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004354
Antoine Pitrou244651a2009-05-04 18:56:13 +00004355 if (inShift) {
4356 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4357 /* shifting out */
4358 if (base64bits) { /* output remaining bits */
4359 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4360 base64buffer = 0;
4361 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004362 }
4363 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004364 /* Characters not in the BASE64 set implicitly unshift the sequence
4365 so no '-' is required, except if the character is itself a '-' */
4366 if (IS_BASE64(ch) || ch == '-') {
4367 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004368 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004369 *out++ = (char) ch;
4370 }
4371 else {
4372 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004373 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004374 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004375 else { /* not in a shift sequence */
4376 if (ch == '+') {
4377 *out++ = '+';
4378 *out++ = '-';
4379 }
4380 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4381 *out++ = (char) ch;
4382 }
4383 else {
4384 *out++ = '+';
4385 inShift = 1;
4386 goto encode_char;
4387 }
4388 }
4389 continue;
4390encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004391 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004392 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004393
Antoine Pitrou244651a2009-05-04 18:56:13 +00004394 /* code first surrogate */
4395 base64bits += 16;
4396 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4397 while (base64bits >= 6) {
4398 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4399 base64bits -= 6;
4400 }
4401 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004402 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004403 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004404 base64bits += 16;
4405 base64buffer = (base64buffer << 16) | ch;
4406 while (base64bits >= 6) {
4407 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4408 base64bits -= 6;
4409 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004410 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004411 if (base64bits)
4412 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4413 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004414 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004415 if (_PyBytes_Resize(&v, out - start) < 0)
4416 return NULL;
4417 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004418}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004419PyObject *
4420PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4421 Py_ssize_t size,
4422 int base64SetO,
4423 int base64WhiteSpace,
4424 const char *errors)
4425{
4426 PyObject *result;
4427 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4428 if (tmp == NULL)
4429 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004430 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004431 base64WhiteSpace, errors);
4432 Py_DECREF(tmp);
4433 return result;
4434}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004435
Antoine Pitrou244651a2009-05-04 18:56:13 +00004436#undef IS_BASE64
4437#undef FROM_BASE64
4438#undef TO_BASE64
4439#undef DECODE_DIRECT
4440#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004441
Guido van Rossumd57fd912000-03-10 22:53:23 +00004442/* --- UTF-8 Codec -------------------------------------------------------- */
4443
Tim Petersced69f82003-09-16 20:30:58 +00004444static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004445char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004446 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4447 illegal prefix. See RFC 3629 for details */
4448 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4449 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004450 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004451 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4452 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4453 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4454 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004455 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4456 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 +00004457 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4458 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004459 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4460 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4461 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4462 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4463 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 +00004464};
4465
Alexander Belopolsky40018472011-02-26 01:02:56 +00004466PyObject *
4467PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004468 Py_ssize_t size,
4469 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004470{
Walter Dörwald69652032004-09-07 20:24:22 +00004471 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4472}
4473
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004474#include "stringlib/ucs1lib.h"
4475#include "stringlib/codecs.h"
4476#include "stringlib/undef.h"
4477
4478#include "stringlib/ucs2lib.h"
4479#include "stringlib/codecs.h"
4480#include "stringlib/undef.h"
4481
4482#include "stringlib/ucs4lib.h"
4483#include "stringlib/codecs.h"
4484#include "stringlib/undef.h"
4485
Antoine Pitrouab868312009-01-10 15:40:25 +00004486/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4487#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4488
4489/* Mask to quickly check whether a C 'long' contains a
4490 non-ASCII, UTF8-encoded char. */
4491#if (SIZEOF_LONG == 8)
4492# define ASCII_CHAR_MASK 0x8080808080808080L
4493#elif (SIZEOF_LONG == 4)
4494# define ASCII_CHAR_MASK 0x80808080L
4495#else
4496# error C 'long' size should be either 4 or 8!
4497#endif
4498
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004499/* Scans a UTF-8 string and returns the maximum character to be expected
4500 and the size of the decoded unicode string.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004501
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004502 This function doesn't check for errors, these checks are performed in
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004503 PyUnicode_DecodeUTF8Stateful.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004504 */
4505static Py_UCS4
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004506utf8_scanner(const unsigned char *p, Py_ssize_t string_size, Py_ssize_t *unicode_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004507{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004508 Py_ssize_t char_count = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004509 const unsigned char *end = p + string_size;
4510 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004511
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004512 assert(unicode_size != NULL);
4513
4514 /* By having a cascade of independent loops which fallback onto each
4515 other, we minimize the amount of work done in the average loop
4516 iteration, and we also maximize the CPU's ability to predict
4517 branches correctly (because a given condition will have always the
4518 same boolean outcome except perhaps in the last iteration of the
4519 corresponding loop).
4520 In the general case this brings us rather close to decoding
4521 performance pre-PEP 393, despite the two-pass decoding.
4522
4523 Note that the pure ASCII loop is not duplicated once a non-ASCII
4524 character has been encountered. It is actually a pessimization (by
4525 a significant factor) to use this loop on text with many non-ASCII
4526 characters, and it is important to avoid bad performance on valid
4527 utf-8 data (invalid utf-8 being a different can of worms).
4528 */
4529
4530 /* ASCII */
4531 for (; p < end; ++p) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004532 /* Only check value if it's not a ASCII char... */
4533 if (*p < 0x80) {
4534 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4535 an explanation. */
4536 if (!((size_t) p & LONG_PTR_MASK)) {
4537 /* Help register allocation */
4538 register const unsigned char *_p = p;
4539 while (_p < aligned_end) {
4540 unsigned long value = *(unsigned long *) _p;
4541 if (value & ASCII_CHAR_MASK)
4542 break;
4543 _p += SIZEOF_LONG;
4544 char_count += SIZEOF_LONG;
4545 }
4546 p = _p;
4547 if (p == end)
4548 break;
4549 }
4550 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004551 if (*p < 0x80)
4552 ++char_count;
4553 else
4554 goto _ucs1loop;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004555 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004556 *unicode_size = char_count;
4557 return 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004558
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004559_ucs1loop:
4560 for (; p < end; ++p) {
4561 if (*p < 0xc4)
4562 char_count += ((*p & 0xc0) != 0x80);
4563 else
4564 goto _ucs2loop;
4565 }
4566 *unicode_size = char_count;
4567 return 255;
4568
4569_ucs2loop:
4570 for (; p < end; ++p) {
4571 if (*p < 0xf0)
4572 char_count += ((*p & 0xc0) != 0x80);
4573 else
4574 goto _ucs4loop;
4575 }
4576 *unicode_size = char_count;
4577 return 65535;
4578
4579_ucs4loop:
4580 for (; p < end; ++p) {
4581 char_count += ((*p & 0xc0) != 0x80);
4582 }
4583 *unicode_size = char_count;
4584 return 65537;
4585}
4586
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004587/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
Victor Stinner785938e2011-12-11 20:09:03 +01004588 in case of errors. Implicit parameters: unicode, kind, data, onError.
4589 Potential resizing overallocates, so the result needs to shrink at the end.
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004590*/
Victor Stinner785938e2011-12-11 20:09:03 +01004591#define WRITE_MAYBE_FAIL(index, value) \
4592 do { \
4593 Py_ssize_t pos = index; \
4594 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4595 unicode_resize(&unicode, pos + pos/8) < 0) \
4596 goto onError; \
4597 if (unicode_putchar(&unicode, &pos, value) < 0) \
4598 goto onError; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004599 } while (0)
4600
Victor Stinnerbf6e5602011-12-12 01:53:47 +01004601static PyObject *
Victor Stinner785938e2011-12-11 20:09:03 +01004602decode_utf8_errors(const char *starts,
4603 Py_ssize_t size,
4604 const char *errors,
4605 Py_ssize_t *consumed,
4606 const char *s,
4607 PyObject *unicode,
4608 Py_ssize_t i)
Walter Dörwald69652032004-09-07 20:24:22 +00004609{
Guido van Rossumd57fd912000-03-10 22:53:23 +00004610 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004611 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004612 Py_ssize_t startinpos;
4613 Py_ssize_t endinpos;
Victor Stinner785938e2011-12-11 20:09:03 +01004614 const char *e = starts + size;
4615 const char *aligned_end;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004616 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004617 PyObject *errorHandler = NULL;
4618 PyObject *exc = NULL;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004619
Antoine Pitrouab868312009-01-10 15:40:25 +00004620 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004621
4622 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004623 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004624
4625 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004626 /* Fast path for runs of ASCII characters. Given that common UTF-8
4627 input will consist of an overwhelming majority of ASCII
4628 characters, we try to optimize for this case by checking
4629 as many characters as a C 'long' can contain.
4630 First, check if we can do an aligned read, as most CPUs have
4631 a penalty for unaligned reads.
4632 */
4633 if (!((size_t) s & LONG_PTR_MASK)) {
4634 /* Help register allocation */
4635 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004636 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004637 while (_s < aligned_end) {
4638 /* Read a whole long at a time (either 4 or 8 bytes),
4639 and do a fast unrolled copy if it only contains ASCII
4640 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004641 unsigned long value = *(unsigned long *) _s;
4642 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004643 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004644 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4645 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4646 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4647 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004648#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004649 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4650 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4651 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4652 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004653#endif
4654 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004655 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004656 }
4657 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004658 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004659 if (s == e)
4660 break;
4661 ch = (unsigned char)*s;
4662 }
4663 }
4664
4665 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004666 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004667 s++;
4668 continue;
4669 }
4670
4671 n = utf8_code_length[ch];
4672
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004673 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004674 if (consumed)
4675 break;
4676 else {
4677 errmsg = "unexpected end of data";
4678 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004679 endinpos = startinpos+1;
4680 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4681 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004682 goto utf8Error;
4683 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004684 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004685
4686 switch (n) {
4687
4688 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004689 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004690 startinpos = s-starts;
4691 endinpos = startinpos+1;
4692 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004693
4694 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004695 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004696 startinpos = s-starts;
4697 endinpos = startinpos+1;
4698 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004699
4700 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004701 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004702 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004703 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004704 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004705 goto utf8Error;
4706 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004707 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004708 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004709 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004710 break;
4711
4712 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004713 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4714 will result in surrogates in range d800-dfff. Surrogates are
4715 not valid UTF-8 so they are rejected.
4716 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4717 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004718 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004719 (s[2] & 0xc0) != 0x80 ||
4720 ((unsigned char)s[0] == 0xE0 &&
4721 (unsigned char)s[1] < 0xA0) ||
4722 ((unsigned char)s[0] == 0xED &&
4723 (unsigned char)s[1] > 0x9F)) {
4724 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004725 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004726 endinpos = startinpos + 1;
4727
4728 /* if s[1] first two bits are 1 and 0, then the invalid
4729 continuation byte is s[2], so increment endinpos by 1,
4730 if not, s[1] is invalid and endinpos doesn't need to
4731 be incremented. */
4732 if ((s[1] & 0xC0) == 0x80)
4733 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004734 goto utf8Error;
4735 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004736 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004737 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004738 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004739 break;
4740
4741 case 4:
4742 if ((s[1] & 0xc0) != 0x80 ||
4743 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004744 (s[3] & 0xc0) != 0x80 ||
4745 ((unsigned char)s[0] == 0xF0 &&
4746 (unsigned char)s[1] < 0x90) ||
4747 ((unsigned char)s[0] == 0xF4 &&
4748 (unsigned char)s[1] > 0x8F)) {
4749 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004750 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004751 endinpos = startinpos + 1;
4752 if ((s[1] & 0xC0) == 0x80) {
4753 endinpos++;
4754 if ((s[2] & 0xC0) == 0x80)
4755 endinpos++;
4756 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004757 goto utf8Error;
4758 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004759 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004760 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01004761 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Ezio Melotti57221d02010-07-01 07:32:02 +00004762
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004763 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004764 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004765 }
4766 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004767 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004768
Benjamin Peterson29060642009-01-31 22:14:21 +00004769 utf8Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00004770 if (unicode_decode_call_errorhandler(
4771 errors, &errorHandler,
4772 "utf8", errmsg,
4773 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004774 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004775 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004776 /* Update data because unicode_decode_call_errorhandler might have
4777 re-created or resized the unicode object. */
Benjamin Peterson29060642009-01-31 22:14:21 +00004778 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004779 }
Walter Dörwald69652032004-09-07 20:24:22 +00004780 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004781 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004782
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004783 /* Adjust length and ready string when it contained errors and
4784 is of the old resizable kind. */
Victor Stinner785938e2011-12-11 20:09:03 +01004785 if (unicode_resize(&unicode, i) < 0)
4786 goto onError;
4787 unicode_adjust_maxchar(&unicode);
4788 if (unicode == NULL)
4789 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004790
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004791 Py_XDECREF(errorHandler);
4792 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004793 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004794 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004795
Benjamin Peterson29060642009-01-31 22:14:21 +00004796 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004797 Py_XDECREF(errorHandler);
4798 Py_XDECREF(exc);
Victor Stinner785938e2011-12-11 20:09:03 +01004799 Py_XDECREF(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004800 return NULL;
4801}
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004802#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004803
Victor Stinner785938e2011-12-11 20:09:03 +01004804PyObject *
4805PyUnicode_DecodeUTF8Stateful(const char *s,
4806 Py_ssize_t size,
4807 const char *errors,
4808 Py_ssize_t *consumed)
4809{
4810 Py_UCS4 maxchar = 0;
4811 Py_ssize_t unicode_size;
4812 int has_errors = 0;
4813 PyObject *unicode;
4814 int kind;
4815 void *data;
4816 const char *starts = s;
4817 const char *e;
4818 Py_ssize_t i;
4819
4820 if (size == 0) {
4821 if (consumed)
4822 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004823 Py_INCREF(unicode_empty);
4824 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004825 }
4826
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004827 maxchar = utf8_scanner((const unsigned char *)s, size, &unicode_size);
Victor Stinner785938e2011-12-11 20:09:03 +01004828
4829 /* When the string is ASCII only, just use memcpy and return.
4830 unicode_size may be != size if there is an incomplete UTF-8
4831 sequence at the end of the ASCII block. */
4832 if (maxchar < 128 && size == unicode_size) {
4833 if (consumed)
4834 *consumed = size;
Victor Stinnerab870212011-12-17 22:39:43 +01004835 return unicode_fromascii((const unsigned char *)s, size);
Victor Stinner785938e2011-12-11 20:09:03 +01004836 }
4837
4838 unicode = PyUnicode_New(unicode_size, maxchar);
4839 if (!unicode)
4840 return NULL;
4841 kind = PyUnicode_KIND(unicode);
4842 data = PyUnicode_DATA(unicode);
4843
4844 /* Unpack UTF-8 encoded data */
4845 i = 0;
4846 e = starts + size;
4847 switch (kind) {
4848 case PyUnicode_1BYTE_KIND:
4849 has_errors = ucs1lib_utf8_try_decode(s, e, (Py_UCS1 *) data, &s, &i);
4850 break;
4851 case PyUnicode_2BYTE_KIND:
4852 has_errors = ucs2lib_utf8_try_decode(s, e, (Py_UCS2 *) data, &s, &i);
4853 break;
4854 case PyUnicode_4BYTE_KIND:
4855 has_errors = ucs4lib_utf8_try_decode(s, e, (Py_UCS4 *) data, &s, &i);
4856 break;
4857 }
4858 if (!has_errors) {
4859 /* Ensure the unicode size calculation was correct */
4860 assert(i == unicode_size);
4861 assert(s == e);
4862 if (consumed)
4863 *consumed = size;
4864 return unicode;
4865 }
4866
4867 /* In case of errors, maxchar and size computation might be incorrect;
4868 code below refits and resizes as necessary. */
4869 return decode_utf8_errors(starts, size, errors, consumed, s, unicode, i);
4870}
4871
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004872#ifdef __APPLE__
4873
4874/* Simplified UTF-8 decoder using surrogateescape error handler,
4875 used to decode the command line arguments on Mac OS X. */
4876
4877wchar_t*
4878_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4879{
4880 int n;
4881 const char *e;
4882 wchar_t *unicode, *p;
4883
4884 /* Note: size will always be longer than the resulting Unicode
4885 character count */
4886 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4887 PyErr_NoMemory();
4888 return NULL;
4889 }
4890 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4891 if (!unicode)
4892 return NULL;
4893
4894 /* Unpack UTF-8 encoded data */
4895 p = unicode;
4896 e = s + size;
4897 while (s < e) {
4898 Py_UCS4 ch = (unsigned char)*s;
4899
4900 if (ch < 0x80) {
4901 *p++ = (wchar_t)ch;
4902 s++;
4903 continue;
4904 }
4905
4906 n = utf8_code_length[ch];
4907 if (s + n > e) {
4908 goto surrogateescape;
4909 }
4910
4911 switch (n) {
4912 case 0:
4913 case 1:
4914 goto surrogateescape;
4915
4916 case 2:
4917 if ((s[1] & 0xc0) != 0x80)
4918 goto surrogateescape;
4919 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4920 assert ((ch > 0x007F) && (ch <= 0x07FF));
4921 *p++ = (wchar_t)ch;
4922 break;
4923
4924 case 3:
4925 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4926 will result in surrogates in range d800-dfff. Surrogates are
4927 not valid UTF-8 so they are rejected.
4928 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4929 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4930 if ((s[1] & 0xc0) != 0x80 ||
4931 (s[2] & 0xc0) != 0x80 ||
4932 ((unsigned char)s[0] == 0xE0 &&
4933 (unsigned char)s[1] < 0xA0) ||
4934 ((unsigned char)s[0] == 0xED &&
4935 (unsigned char)s[1] > 0x9F)) {
4936
4937 goto surrogateescape;
4938 }
4939 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4940 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004941 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004942 break;
4943
4944 case 4:
4945 if ((s[1] & 0xc0) != 0x80 ||
4946 (s[2] & 0xc0) != 0x80 ||
4947 (s[3] & 0xc0) != 0x80 ||
4948 ((unsigned char)s[0] == 0xF0 &&
4949 (unsigned char)s[1] < 0x90) ||
4950 ((unsigned char)s[0] == 0xF4 &&
4951 (unsigned char)s[1] > 0x8F)) {
4952 goto surrogateescape;
4953 }
4954 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4955 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01004956 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004957
4958#if SIZEOF_WCHAR_T == 4
4959 *p++ = (wchar_t)ch;
4960#else
4961 /* compute and append the two surrogates: */
Victor Stinner551ac952011-11-29 22:58:13 +01004962 *p++ = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4963 *p++ = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004964#endif
4965 break;
4966 }
4967 s += n;
4968 continue;
4969
4970 surrogateescape:
4971 *p++ = 0xDC00 + ch;
4972 s++;
4973 }
4974 *p = L'\0';
4975 return unicode;
4976}
4977
4978#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004980/* Primary internal function which creates utf8 encoded bytes objects.
4981
4982 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004983 and allocate exactly as much space needed at the end. Else allocate the
4984 maximum possible needed (4 result bytes per Unicode character), and return
4985 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004986*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004987PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004988_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004989{
Victor Stinner6099a032011-12-18 14:22:26 +01004990 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004991 void *data;
4992 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004993
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004994 if (!PyUnicode_Check(unicode)) {
4995 PyErr_BadArgument();
4996 return NULL;
4997 }
4998
4999 if (PyUnicode_READY(unicode) == -1)
5000 return NULL;
5001
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005002 if (PyUnicode_UTF8(unicode))
5003 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5004 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005005
5006 kind = PyUnicode_KIND(unicode);
5007 data = PyUnicode_DATA(unicode);
5008 size = PyUnicode_GET_LENGTH(unicode);
5009
Benjamin Petersonead6b532011-12-20 17:23:42 -06005010 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005011 default:
5012 assert(0);
5013 case PyUnicode_1BYTE_KIND:
5014 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5015 assert(!PyUnicode_IS_ASCII(unicode));
5016 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5017 case PyUnicode_2BYTE_KIND:
5018 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5019 case PyUnicode_4BYTE_KIND:
5020 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005021 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005022}
5023
Alexander Belopolsky40018472011-02-26 01:02:56 +00005024PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005025PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5026 Py_ssize_t size,
5027 const char *errors)
5028{
5029 PyObject *v, *unicode;
5030
5031 unicode = PyUnicode_FromUnicode(s, size);
5032 if (unicode == NULL)
5033 return NULL;
5034 v = _PyUnicode_AsUTF8String(unicode, errors);
5035 Py_DECREF(unicode);
5036 return v;
5037}
5038
5039PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005040PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005041{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005042 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005043}
5044
Walter Dörwald41980ca2007-08-16 21:55:45 +00005045/* --- UTF-32 Codec ------------------------------------------------------- */
5046
5047PyObject *
5048PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005049 Py_ssize_t size,
5050 const char *errors,
5051 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005052{
5053 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5054}
5055
5056PyObject *
5057PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005058 Py_ssize_t size,
5059 const char *errors,
5060 int *byteorder,
5061 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005062{
5063 const char *starts = s;
5064 Py_ssize_t startinpos;
5065 Py_ssize_t endinpos;
5066 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005067 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005068 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005069 int bo = 0; /* assume native ordering by default */
5070 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005071 /* Offsets from q for retrieving bytes in the right order. */
5072#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5073 int iorder[] = {0, 1, 2, 3};
5074#else
5075 int iorder[] = {3, 2, 1, 0};
5076#endif
5077 PyObject *errorHandler = NULL;
5078 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005079
Walter Dörwald41980ca2007-08-16 21:55:45 +00005080 q = (unsigned char *)s;
5081 e = q + size;
5082
5083 if (byteorder)
5084 bo = *byteorder;
5085
5086 /* Check for BOM marks (U+FEFF) in the input and adjust current
5087 byte order setting accordingly. In native mode, the leading BOM
5088 mark is skipped, in all other modes, it is copied to the output
5089 stream as-is (giving a ZWNBSP character). */
5090 if (bo == 0) {
5091 if (size >= 4) {
5092 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00005093 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005094#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005095 if (bom == 0x0000FEFF) {
5096 q += 4;
5097 bo = -1;
5098 }
5099 else if (bom == 0xFFFE0000) {
5100 q += 4;
5101 bo = 1;
5102 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005103#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005104 if (bom == 0x0000FEFF) {
5105 q += 4;
5106 bo = 1;
5107 }
5108 else if (bom == 0xFFFE0000) {
5109 q += 4;
5110 bo = -1;
5111 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005112#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005113 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005114 }
5115
5116 if (bo == -1) {
5117 /* force LE */
5118 iorder[0] = 0;
5119 iorder[1] = 1;
5120 iorder[2] = 2;
5121 iorder[3] = 3;
5122 }
5123 else if (bo == 1) {
5124 /* force BE */
5125 iorder[0] = 3;
5126 iorder[1] = 2;
5127 iorder[2] = 1;
5128 iorder[3] = 0;
5129 }
5130
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005131 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005132 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005133 if (!unicode)
5134 return NULL;
5135 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005136 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005137 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005138
Walter Dörwald41980ca2007-08-16 21:55:45 +00005139 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005140 Py_UCS4 ch;
5141 /* remaining bytes at the end? (size should be divisible by 4) */
5142 if (e-q<4) {
5143 if (consumed)
5144 break;
5145 errmsg = "truncated data";
5146 startinpos = ((const char *)q)-starts;
5147 endinpos = ((const char *)e)-starts;
5148 goto utf32Error;
5149 /* The remaining input chars are ignored if the callback
5150 chooses to skip the input */
5151 }
5152 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5153 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005154
Benjamin Peterson29060642009-01-31 22:14:21 +00005155 if (ch >= 0x110000)
5156 {
5157 errmsg = "codepoint not in range(0x110000)";
5158 startinpos = ((const char *)q)-starts;
5159 endinpos = startinpos+4;
5160 goto utf32Error;
5161 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005162 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5163 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005164 q += 4;
5165 continue;
5166 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005167 if (unicode_decode_call_errorhandler(
5168 errors, &errorHandler,
5169 "utf32", errmsg,
5170 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005171 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005172 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005173 }
5174
5175 if (byteorder)
5176 *byteorder = bo;
5177
5178 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005179 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005180
5181 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005182 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005183 goto onError;
5184
5185 Py_XDECREF(errorHandler);
5186 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005187 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005188
Benjamin Peterson29060642009-01-31 22:14:21 +00005189 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005190 Py_DECREF(unicode);
5191 Py_XDECREF(errorHandler);
5192 Py_XDECREF(exc);
5193 return NULL;
5194}
5195
5196PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005197_PyUnicode_EncodeUTF32(PyObject *str,
5198 const char *errors,
5199 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005200{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005201 int kind;
5202 void *data;
5203 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005204 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005205 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005206 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005207 /* Offsets from p for storing byte pairs in the right order. */
5208#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5209 int iorder[] = {0, 1, 2, 3};
5210#else
5211 int iorder[] = {3, 2, 1, 0};
5212#endif
5213
Benjamin Peterson29060642009-01-31 22:14:21 +00005214#define STORECHAR(CH) \
5215 do { \
5216 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5217 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5218 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5219 p[iorder[0]] = (CH) & 0xff; \
5220 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005221 } while(0)
5222
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005223 if (!PyUnicode_Check(str)) {
5224 PyErr_BadArgument();
5225 return NULL;
5226 }
5227 if (PyUnicode_READY(str) < 0)
5228 return NULL;
5229 kind = PyUnicode_KIND(str);
5230 data = PyUnicode_DATA(str);
5231 len = PyUnicode_GET_LENGTH(str);
5232
5233 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005234 bytesize = nsize * 4;
5235 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005236 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005237 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005238 if (v == NULL)
5239 return NULL;
5240
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005241 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005242 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005243 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005244 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005245 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005246
5247 if (byteorder == -1) {
5248 /* force LE */
5249 iorder[0] = 0;
5250 iorder[1] = 1;
5251 iorder[2] = 2;
5252 iorder[3] = 3;
5253 }
5254 else if (byteorder == 1) {
5255 /* force BE */
5256 iorder[0] = 3;
5257 iorder[1] = 2;
5258 iorder[2] = 1;
5259 iorder[3] = 0;
5260 }
5261
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005262 for (i = 0; i < len; i++)
5263 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005264
5265 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005266 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005267#undef STORECHAR
5268}
5269
Alexander Belopolsky40018472011-02-26 01:02:56 +00005270PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005271PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5272 Py_ssize_t size,
5273 const char *errors,
5274 int byteorder)
5275{
5276 PyObject *result;
5277 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5278 if (tmp == NULL)
5279 return NULL;
5280 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5281 Py_DECREF(tmp);
5282 return result;
5283}
5284
5285PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005286PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005287{
Victor Stinnerb960b342011-11-20 19:12:52 +01005288 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005289}
5290
Guido van Rossumd57fd912000-03-10 22:53:23 +00005291/* --- UTF-16 Codec ------------------------------------------------------- */
5292
Tim Peters772747b2001-08-09 22:21:55 +00005293PyObject *
5294PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005295 Py_ssize_t size,
5296 const char *errors,
5297 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005298{
Walter Dörwald69652032004-09-07 20:24:22 +00005299 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5300}
5301
Antoine Pitrouab868312009-01-10 15:40:25 +00005302/* Two masks for fast checking of whether a C 'long' may contain
5303 UTF16-encoded surrogate characters. This is an efficient heuristic,
5304 assuming that non-surrogate characters with a code point >= 0x8000 are
5305 rare in most input.
5306 FAST_CHAR_MASK is used when the input is in native byte ordering,
5307 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005308*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005309#if (SIZEOF_LONG == 8)
5310# define FAST_CHAR_MASK 0x8000800080008000L
5311# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5312#elif (SIZEOF_LONG == 4)
5313# define FAST_CHAR_MASK 0x80008000L
5314# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5315#else
5316# error C 'long' size should be either 4 or 8!
5317#endif
5318
Walter Dörwald69652032004-09-07 20:24:22 +00005319PyObject *
5320PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005321 Py_ssize_t size,
5322 const char *errors,
5323 int *byteorder,
5324 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005325{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005326 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005327 Py_ssize_t startinpos;
5328 Py_ssize_t endinpos;
5329 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005330 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005331 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005332 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005333 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005334 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005335 /* Offsets from q for retrieving byte pairs in the right order. */
5336#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5337 int ihi = 1, ilo = 0;
5338#else
5339 int ihi = 0, ilo = 1;
5340#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005341 PyObject *errorHandler = NULL;
5342 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005343
5344 /* Note: size will always be longer than the resulting Unicode
5345 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005346 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005347 if (!unicode)
5348 return NULL;
5349 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005350 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005351 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005352
Tim Peters772747b2001-08-09 22:21:55 +00005353 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005354 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005355
5356 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005357 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005358
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005359 /* Check for BOM marks (U+FEFF) in the input and adjust current
5360 byte order setting accordingly. In native mode, the leading BOM
5361 mark is skipped, in all other modes, it is copied to the output
5362 stream as-is (giving a ZWNBSP character). */
5363 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005364 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005365 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005366#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005367 if (bom == 0xFEFF) {
5368 q += 2;
5369 bo = -1;
5370 }
5371 else if (bom == 0xFFFE) {
5372 q += 2;
5373 bo = 1;
5374 }
Tim Petersced69f82003-09-16 20:30:58 +00005375#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005376 if (bom == 0xFEFF) {
5377 q += 2;
5378 bo = 1;
5379 }
5380 else if (bom == 0xFFFE) {
5381 q += 2;
5382 bo = -1;
5383 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005384#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005385 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005386 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005387
Tim Peters772747b2001-08-09 22:21:55 +00005388 if (bo == -1) {
5389 /* force LE */
5390 ihi = 1;
5391 ilo = 0;
5392 }
5393 else if (bo == 1) {
5394 /* force BE */
5395 ihi = 0;
5396 ilo = 1;
5397 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005398#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5399 native_ordering = ilo < ihi;
5400#else
5401 native_ordering = ilo > ihi;
5402#endif
Tim Peters772747b2001-08-09 22:21:55 +00005403
Antoine Pitrouab868312009-01-10 15:40:25 +00005404 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005405 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005406 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005407 /* First check for possible aligned read of a C 'long'. Unaligned
5408 reads are more expensive, better to defer to another iteration. */
5409 if (!((size_t) q & LONG_PTR_MASK)) {
5410 /* Fast path for runs of non-surrogate chars. */
5411 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005412 int kind = PyUnicode_KIND(unicode);
5413 void *data = PyUnicode_DATA(unicode);
5414 while (_q < aligned_end) {
5415 unsigned long block = * (unsigned long *) _q;
5416 unsigned short *pblock = (unsigned short*)&block;
5417 Py_UCS4 maxch;
5418 if (native_ordering) {
5419 /* Can use buffer directly */
5420 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005421 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005422 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005423 else {
5424 /* Need to byte-swap */
5425 unsigned char *_p = (unsigned char*)pblock;
5426 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005427 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005428 _p[0] = _q[1];
5429 _p[1] = _q[0];
5430 _p[2] = _q[3];
5431 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005432#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005433 _p[4] = _q[5];
5434 _p[5] = _q[4];
5435 _p[6] = _q[7];
5436 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005437#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005438 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005439 maxch = Py_MAX(pblock[0], pblock[1]);
5440#if SIZEOF_LONG == 8
5441 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5442#endif
5443 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5444 if (unicode_widen(&unicode, maxch) < 0)
5445 goto onError;
5446 kind = PyUnicode_KIND(unicode);
5447 data = PyUnicode_DATA(unicode);
5448 }
5449 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5450 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5451#if SIZEOF_LONG == 8
5452 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5453 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5454#endif
5455 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005456 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005457 q = _q;
5458 if (q >= e)
5459 break;
5460 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005461 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005462
Benjamin Peterson14339b62009-01-31 16:36:08 +00005463 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005464
Victor Stinner551ac952011-11-29 22:58:13 +01005465 if (!Py_UNICODE_IS_SURROGATE(ch)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005466 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5467 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005468 continue;
5469 }
5470
5471 /* UTF-16 code pair: */
5472 if (q > e) {
5473 errmsg = "unexpected end of data";
5474 startinpos = (((const char *)q) - 2) - starts;
5475 endinpos = ((const char *)e) + 1 - starts;
5476 goto utf16Error;
5477 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005478 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5479 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005480 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005481 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005482 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005483 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005484 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005485 continue;
5486 }
5487 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005488 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005489 startinpos = (((const char *)q)-4)-starts;
5490 endinpos = startinpos+2;
5491 goto utf16Error;
5492 }
5493
Benjamin Peterson14339b62009-01-31 16:36:08 +00005494 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005495 errmsg = "illegal encoding";
5496 startinpos = (((const char *)q)-2)-starts;
5497 endinpos = startinpos+2;
5498 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005499
Benjamin Peterson29060642009-01-31 22:14:21 +00005500 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005501 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005502 errors,
5503 &errorHandler,
5504 "utf16", errmsg,
5505 &starts,
5506 (const char **)&e,
5507 &startinpos,
5508 &endinpos,
5509 &exc,
5510 (const char **)&q,
5511 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005512 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005513 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005514 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005515 /* remaining byte at the end? (size should be even) */
5516 if (e == q) {
5517 if (!consumed) {
5518 errmsg = "truncated data";
5519 startinpos = ((const char *)q) - starts;
5520 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005521 if (unicode_decode_call_errorhandler(
5522 errors,
5523 &errorHandler,
5524 "utf16", errmsg,
5525 &starts,
5526 (const char **)&e,
5527 &startinpos,
5528 &endinpos,
5529 &exc,
5530 (const char **)&q,
5531 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005532 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005533 goto onError;
5534 /* The remaining input chars are ignored if the callback
5535 chooses to skip the input */
5536 }
5537 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005538
5539 if (byteorder)
5540 *byteorder = bo;
5541
Walter Dörwald69652032004-09-07 20:24:22 +00005542 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005543 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005544
Guido van Rossumd57fd912000-03-10 22:53:23 +00005545 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005546 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005547 goto onError;
5548
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005549 Py_XDECREF(errorHandler);
5550 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005551 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005552
Benjamin Peterson29060642009-01-31 22:14:21 +00005553 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005554 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005555 Py_XDECREF(errorHandler);
5556 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005557 return NULL;
5558}
5559
Antoine Pitrouab868312009-01-10 15:40:25 +00005560#undef FAST_CHAR_MASK
5561#undef SWAPPED_FAST_CHAR_MASK
5562
Tim Peters772747b2001-08-09 22:21:55 +00005563PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005564_PyUnicode_EncodeUTF16(PyObject *str,
5565 const char *errors,
5566 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005567{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005568 int kind;
5569 void *data;
5570 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005571 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005572 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005573 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005574 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005575 /* Offsets from p for storing byte pairs in the right order. */
5576#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5577 int ihi = 1, ilo = 0;
5578#else
5579 int ihi = 0, ilo = 1;
5580#endif
5581
Benjamin Peterson29060642009-01-31 22:14:21 +00005582#define STORECHAR(CH) \
5583 do { \
5584 p[ihi] = ((CH) >> 8) & 0xff; \
5585 p[ilo] = (CH) & 0xff; \
5586 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005587 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005588
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005589 if (!PyUnicode_Check(str)) {
5590 PyErr_BadArgument();
5591 return NULL;
5592 }
5593 if (PyUnicode_READY(str) < 0)
5594 return NULL;
5595 kind = PyUnicode_KIND(str);
5596 data = PyUnicode_DATA(str);
5597 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005598
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005599 pairs = 0;
5600 if (kind == PyUnicode_4BYTE_KIND)
5601 for (i = 0; i < len; i++)
5602 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5603 pairs++;
5604 /* 2 * (len + pairs + (byteorder == 0)) */
5605 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005606 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005607 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005608 bytesize = nsize * 2;
5609 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005610 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005611 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005612 if (v == NULL)
5613 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005614
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005615 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005616 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005617 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005618 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005619 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005620
5621 if (byteorder == -1) {
5622 /* force LE */
5623 ihi = 1;
5624 ilo = 0;
5625 }
5626 else if (byteorder == 1) {
5627 /* force BE */
5628 ihi = 0;
5629 ilo = 1;
5630 }
5631
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005632 for (i = 0; i < len; i++) {
5633 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5634 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005635 if (ch >= 0x10000) {
Victor Stinner551ac952011-11-29 22:58:13 +01005636 ch2 = Py_UNICODE_LOW_SURROGATE(ch);
5637 ch = Py_UNICODE_HIGH_SURROGATE(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00005638 }
Tim Peters772747b2001-08-09 22:21:55 +00005639 STORECHAR(ch);
5640 if (ch2)
5641 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005642 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005643
5644 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005645 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005646#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005647}
5648
Alexander Belopolsky40018472011-02-26 01:02:56 +00005649PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005650PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5651 Py_ssize_t size,
5652 const char *errors,
5653 int byteorder)
5654{
5655 PyObject *result;
5656 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5657 if (tmp == NULL)
5658 return NULL;
5659 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5660 Py_DECREF(tmp);
5661 return result;
5662}
5663
5664PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005665PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005666{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005667 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005668}
5669
5670/* --- Unicode Escape Codec ----------------------------------------------- */
5671
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005672/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5673 if all the escapes in the string make it still a valid ASCII string.
5674 Returns -1 if any escapes were found which cause the string to
5675 pop out of ASCII range. Otherwise returns the length of the
5676 required buffer to hold the string.
5677 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005678static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005679length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5680{
5681 const unsigned char *p = (const unsigned char *)s;
5682 const unsigned char *end = p + size;
5683 Py_ssize_t length = 0;
5684
5685 if (size < 0)
5686 return -1;
5687
5688 for (; p < end; ++p) {
5689 if (*p > 127) {
5690 /* Non-ASCII */
5691 return -1;
5692 }
5693 else if (*p != '\\') {
5694 /* Normal character */
5695 ++length;
5696 }
5697 else {
5698 /* Backslash-escape, check next char */
5699 ++p;
5700 /* Escape sequence reaches till end of string or
5701 non-ASCII follow-up. */
5702 if (p >= end || *p > 127)
5703 return -1;
5704 switch (*p) {
5705 case '\n':
5706 /* backslash + \n result in zero characters */
5707 break;
5708 case '\\': case '\'': case '\"':
5709 case 'b': case 'f': case 't':
5710 case 'n': case 'r': case 'v': case 'a':
5711 ++length;
5712 break;
5713 case '0': case '1': case '2': case '3':
5714 case '4': case '5': case '6': case '7':
5715 case 'x': case 'u': case 'U': case 'N':
5716 /* these do not guarantee ASCII characters */
5717 return -1;
5718 default:
5719 /* count the backslash + the other character */
5720 length += 2;
5721 }
5722 }
5723 }
5724 return length;
5725}
5726
Fredrik Lundh06d12682001-01-24 07:59:11 +00005727static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005728
Alexander Belopolsky40018472011-02-26 01:02:56 +00005729PyObject *
5730PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005731 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005732 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005733{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005734 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005735 Py_ssize_t startinpos;
5736 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005737 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005738 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005739 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005740 char* message;
5741 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005742 PyObject *errorHandler = NULL;
5743 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005744 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005745 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005746
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005747 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005748
5749 /* After length_of_escaped_ascii_string() there are two alternatives,
5750 either the string is pure ASCII with named escapes like \n, etc.
5751 and we determined it's exact size (common case)
5752 or it contains \x, \u, ... escape sequences. then we create a
5753 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005754 if (len >= 0) {
5755 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005756 if (!v)
5757 goto onError;
5758 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005759 }
5760 else {
5761 /* Escaped strings will always be longer than the resulting
5762 Unicode string, so we start with size here and then reduce the
5763 length after conversion to the true value.
5764 (but if the error callback returns a long replacement string
5765 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005766 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005767 if (!v)
5768 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005769 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005770 }
5771
Guido van Rossumd57fd912000-03-10 22:53:23 +00005772 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005773 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005774 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005775 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005776
Guido van Rossumd57fd912000-03-10 22:53:23 +00005777 while (s < end) {
5778 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005779 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005780 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005781
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005782 /* The only case in which i == ascii_length is a backslash
5783 followed by a newline. */
5784 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005785
Guido van Rossumd57fd912000-03-10 22:53:23 +00005786 /* Non-escape characters are interpreted as Unicode ordinals */
5787 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005788 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5789 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005790 continue;
5791 }
5792
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005793 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005794 /* \ - Escapes */
5795 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005796 c = *s++;
5797 if (s > end)
5798 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005799
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005800 /* The only case in which i == ascii_length is a backslash
5801 followed by a newline. */
5802 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005803
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005804 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005805
Benjamin Peterson29060642009-01-31 22:14:21 +00005806 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005807#define WRITECHAR(ch) \
5808 do { \
5809 if (unicode_putchar(&v, &i, ch) < 0) \
5810 goto onError; \
5811 }while(0)
5812
Guido van Rossumd57fd912000-03-10 22:53:23 +00005813 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005814 case '\\': WRITECHAR('\\'); break;
5815 case '\'': WRITECHAR('\''); break;
5816 case '\"': WRITECHAR('\"'); break;
5817 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005818 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005819 case 'f': WRITECHAR('\014'); break;
5820 case 't': WRITECHAR('\t'); break;
5821 case 'n': WRITECHAR('\n'); break;
5822 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005823 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005824 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005825 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005826 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005827
Benjamin Peterson29060642009-01-31 22:14:21 +00005828 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005829 case '0': case '1': case '2': case '3':
5830 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005831 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005832 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005833 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005834 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005835 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005836 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005837 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005838 break;
5839
Benjamin Peterson29060642009-01-31 22:14:21 +00005840 /* hex escapes */
5841 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005842 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005843 digits = 2;
5844 message = "truncated \\xXX escape";
5845 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005846
Benjamin Peterson29060642009-01-31 22:14:21 +00005847 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005848 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005849 digits = 4;
5850 message = "truncated \\uXXXX escape";
5851 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005852
Benjamin Peterson29060642009-01-31 22:14:21 +00005853 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005854 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005855 digits = 8;
5856 message = "truncated \\UXXXXXXXX escape";
5857 hexescape:
5858 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005859 if (s+digits>end) {
5860 endinpos = size;
5861 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005862 errors, &errorHandler,
5863 "unicodeescape", "end of string in escape sequence",
5864 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005865 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005866 goto onError;
5867 goto nextByte;
5868 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005869 for (j = 0; j < digits; ++j) {
5870 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005871 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005872 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005873 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005874 errors, &errorHandler,
5875 "unicodeescape", message,
5876 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005877 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005878 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005879 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005880 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005881 }
5882 chr = (chr<<4) & ~0xF;
5883 if (c >= '0' && c <= '9')
5884 chr += c - '0';
5885 else if (c >= 'a' && c <= 'f')
5886 chr += 10 + c - 'a';
5887 else
5888 chr += 10 + c - 'A';
5889 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005890 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005891 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005892 /* _decoding_error will have already written into the
5893 target buffer. */
5894 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005895 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005896 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005897 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005898 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005899 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005900 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005901 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005902 errors, &errorHandler,
5903 "unicodeescape", "illegal Unicode character",
5904 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005905 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005906 goto onError;
5907 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005908 break;
5909
Benjamin Peterson29060642009-01-31 22:14:21 +00005910 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005911 case 'N':
5912 message = "malformed \\N character escape";
5913 if (ucnhash_CAPI == NULL) {
5914 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005915 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5916 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005917 if (ucnhash_CAPI == NULL)
5918 goto ucnhashError;
5919 }
5920 if (*s == '{') {
5921 const char *start = s+1;
5922 /* look for the closing brace */
5923 while (*s != '}' && s < end)
5924 s++;
5925 if (s > start && s < end && *s == '}') {
5926 /* found a name. look it up in the unicode database */
5927 message = "unknown Unicode character name";
5928 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005929 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005930 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005931 goto store;
5932 }
5933 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005934 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005935 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005936 errors, &errorHandler,
5937 "unicodeescape", message,
5938 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005939 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005940 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005941 break;
5942
5943 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005944 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005945 message = "\\ at end of string";
5946 s--;
5947 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005948 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005949 errors, &errorHandler,
5950 "unicodeescape", message,
5951 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005952 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005953 goto onError;
5954 }
5955 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005956 WRITECHAR('\\');
5957 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005958 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005959 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005960 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005961 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005962 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005963 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005964#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005965
Victor Stinner16e6a802011-12-12 13:24:15 +01005966 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005967 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005968 Py_XDECREF(errorHandler);
5969 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005970 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005971
Benjamin Peterson29060642009-01-31 22:14:21 +00005972 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005973 PyErr_SetString(
5974 PyExc_UnicodeError,
5975 "\\N escapes not supported (can't load unicodedata module)"
5976 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005977 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005978 Py_XDECREF(errorHandler);
5979 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005980 return NULL;
5981
Benjamin Peterson29060642009-01-31 22:14:21 +00005982 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005983 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005984 Py_XDECREF(errorHandler);
5985 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005986 return NULL;
5987}
5988
5989/* Return a Unicode-Escape string version of the Unicode object.
5990
5991 If quotes is true, the string is enclosed in u"" or u'' quotes as
5992 appropriate.
5993
5994*/
5995
Alexander Belopolsky40018472011-02-26 01:02:56 +00005996PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005997PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005998{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005999 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006000 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006001 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006002 int kind;
6003 void *data;
6004 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006005
Thomas Wouters89f507f2006-12-13 04:49:30 +00006006 /* Initial allocation is based on the longest-possible unichr
6007 escape.
6008
6009 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
6010 unichr, so in this case it's the longest unichr escape. In
6011 narrow (UTF-16) builds this is five chars per source unichr
6012 since there are two unichrs in the surrogate pair, so in narrow
6013 (UTF-16) builds it's not the longest unichr escape.
6014
6015 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
6016 so in the narrow (UTF-16) build case it's the longest unichr
6017 escape.
6018 */
6019
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006020 if (!PyUnicode_Check(unicode)) {
6021 PyErr_BadArgument();
6022 return NULL;
6023 }
6024 if (PyUnicode_READY(unicode) < 0)
6025 return NULL;
6026 len = PyUnicode_GET_LENGTH(unicode);
6027 kind = PyUnicode_KIND(unicode);
6028 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06006029 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006030 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6031 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6032 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6033 }
6034
6035 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006036 return PyBytes_FromStringAndSize(NULL, 0);
6037
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006038 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006039 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006040
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006041 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00006042 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006043 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00006044 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006045 if (repr == NULL)
6046 return NULL;
6047
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006048 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006049
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006050 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006051 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006052
Walter Dörwald79e913e2007-05-12 11:08:06 +00006053 /* Escape backslashes */
6054 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006055 *p++ = '\\';
6056 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00006057 continue;
Tim Petersced69f82003-09-16 20:30:58 +00006058 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006059
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006060 /* Map 21-bit characters to '\U00xxxxxx' */
6061 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006062 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006063 *p++ = '\\';
6064 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006065 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
6066 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
6067 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6068 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6069 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6070 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6071 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6072 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006073 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006074 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006075
Guido van Rossumd57fd912000-03-10 22:53:23 +00006076 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006077 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006078 *p++ = '\\';
6079 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006080 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6081 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6082 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6083 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006084 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006085
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006086 /* Map special whitespace to '\t', \n', '\r' */
6087 else if (ch == '\t') {
6088 *p++ = '\\';
6089 *p++ = 't';
6090 }
6091 else if (ch == '\n') {
6092 *p++ = '\\';
6093 *p++ = 'n';
6094 }
6095 else if (ch == '\r') {
6096 *p++ = '\\';
6097 *p++ = 'r';
6098 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006099
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006100 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006101 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006102 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006103 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006104 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6105 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006106 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006107
Guido van Rossumd57fd912000-03-10 22:53:23 +00006108 /* Copy everything else as-is */
6109 else
6110 *p++ = (char) ch;
6111 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006112
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006113 assert(p - PyBytes_AS_STRING(repr) > 0);
6114 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6115 return NULL;
6116 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006117}
6118
Alexander Belopolsky40018472011-02-26 01:02:56 +00006119PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006120PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6121 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006122{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006123 PyObject *result;
6124 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6125 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006126 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006127 result = PyUnicode_AsUnicodeEscapeString(tmp);
6128 Py_DECREF(tmp);
6129 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006130}
6131
6132/* --- Raw Unicode Escape Codec ------------------------------------------- */
6133
Alexander Belopolsky40018472011-02-26 01:02:56 +00006134PyObject *
6135PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006136 Py_ssize_t size,
6137 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006138{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006139 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006140 Py_ssize_t startinpos;
6141 Py_ssize_t endinpos;
6142 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006143 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006144 const char *end;
6145 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006146 PyObject *errorHandler = NULL;
6147 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006148
Guido van Rossumd57fd912000-03-10 22:53:23 +00006149 /* Escaped strings will always be longer than the resulting
6150 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006151 length after conversion to the true value. (But decoding error
6152 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006153 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006154 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006155 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006156 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006157 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006158 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006159 end = s + size;
6160 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006161 unsigned char c;
6162 Py_UCS4 x;
6163 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006164 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006165
Benjamin Peterson29060642009-01-31 22:14:21 +00006166 /* Non-escape characters are interpreted as Unicode ordinals */
6167 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006168 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6169 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006170 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006171 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006172 startinpos = s-starts;
6173
6174 /* \u-escapes are only interpreted iff the number of leading
6175 backslashes if odd */
6176 bs = s;
6177 for (;s < end;) {
6178 if (*s != '\\')
6179 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006180 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6181 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006182 }
6183 if (((s - bs) & 1) == 0 ||
6184 s >= end ||
6185 (*s != 'u' && *s != 'U')) {
6186 continue;
6187 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006188 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006189 count = *s=='u' ? 4 : 8;
6190 s++;
6191
6192 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006193 for (x = 0, i = 0; i < count; ++i, ++s) {
6194 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006195 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006196 endinpos = s-starts;
6197 if (unicode_decode_call_errorhandler(
6198 errors, &errorHandler,
6199 "rawunicodeescape", "truncated \\uXXXX",
6200 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006201 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006202 goto onError;
6203 goto nextByte;
6204 }
6205 x = (x<<4) & ~0xF;
6206 if (c >= '0' && c <= '9')
6207 x += c - '0';
6208 else if (c >= 'a' && c <= 'f')
6209 x += 10 + c - 'a';
6210 else
6211 x += 10 + c - 'A';
6212 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006213 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006214 if (unicode_putchar(&v, &outpos, x) < 0)
6215 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006216 } else {
6217 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006218 if (unicode_decode_call_errorhandler(
6219 errors, &errorHandler,
6220 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006221 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006222 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006223 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006224 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006225 nextByte:
6226 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006227 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006228 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006229 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006230 Py_XDECREF(errorHandler);
6231 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006232 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006233
Benjamin Peterson29060642009-01-31 22:14:21 +00006234 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006235 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006236 Py_XDECREF(errorHandler);
6237 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006238 return NULL;
6239}
6240
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006241
Alexander Belopolsky40018472011-02-26 01:02:56 +00006242PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006243PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006244{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006245 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006246 char *p;
6247 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006248 Py_ssize_t expandsize, pos;
6249 int kind;
6250 void *data;
6251 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006252
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006253 if (!PyUnicode_Check(unicode)) {
6254 PyErr_BadArgument();
6255 return NULL;
6256 }
6257 if (PyUnicode_READY(unicode) < 0)
6258 return NULL;
6259 kind = PyUnicode_KIND(unicode);
6260 data = PyUnicode_DATA(unicode);
6261 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006262 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6263 bytes, and 1 byte characters 4. */
6264 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006265
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006266 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006267 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006268
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006269 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006270 if (repr == NULL)
6271 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006272 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006273 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006274
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006275 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006276 for (pos = 0; pos < len; pos++) {
6277 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006278 /* Map 32-bit characters to '\Uxxxxxxxx' */
6279 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006280 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006281 *p++ = '\\';
6282 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006283 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6284 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6285 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6286 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6287 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6288 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6289 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6290 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006291 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006292 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006293 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006294 *p++ = '\\';
6295 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006296 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6297 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6298 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6299 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006300 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006301 /* Copy everything else as-is */
6302 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006303 *p++ = (char) ch;
6304 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006305
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006306 assert(p > q);
6307 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006308 return NULL;
6309 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006310}
6311
Alexander Belopolsky40018472011-02-26 01:02:56 +00006312PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006313PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6314 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006315{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006316 PyObject *result;
6317 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6318 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006319 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006320 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6321 Py_DECREF(tmp);
6322 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006323}
6324
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006325/* --- Unicode Internal Codec ------------------------------------------- */
6326
Alexander Belopolsky40018472011-02-26 01:02:56 +00006327PyObject *
6328_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006329 Py_ssize_t size,
6330 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006331{
6332 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006333 Py_ssize_t startinpos;
6334 Py_ssize_t endinpos;
6335 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006336 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006337 const char *end;
6338 const char *reason;
6339 PyObject *errorHandler = NULL;
6340 PyObject *exc = NULL;
6341
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006342 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006343 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006344 1))
6345 return NULL;
6346
Thomas Wouters89f507f2006-12-13 04:49:30 +00006347 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006348 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006349 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006350 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006351 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006352 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006353 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006354 end = s + size;
6355
6356 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006357 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006358 Py_UCS4 ch;
6359 /* We copy the raw representation one byte at a time because the
6360 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006361 ((char *) &uch)[0] = s[0];
6362 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006363#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006364 ((char *) &uch)[2] = s[2];
6365 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006366#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006367 ch = uch;
6368
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006369 /* We have to sanity check the raw data, otherwise doom looms for
6370 some malformed UCS-4 data. */
6371 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006372#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006373 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006374#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006375 end-s < Py_UNICODE_SIZE
6376 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006377 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006378 startinpos = s - starts;
6379 if (end-s < Py_UNICODE_SIZE) {
6380 endinpos = end-starts;
6381 reason = "truncated input";
6382 }
6383 else {
6384 endinpos = s - starts + Py_UNICODE_SIZE;
6385 reason = "illegal code point (> 0x10FFFF)";
6386 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006387 if (unicode_decode_call_errorhandler(
6388 errors, &errorHandler,
6389 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006390 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006391 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006392 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006393 continue;
6394 }
6395
6396 s += Py_UNICODE_SIZE;
6397#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006398 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006399 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006400 Py_UNICODE uch2;
6401 ((char *) &uch2)[0] = s[0];
6402 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006403 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006404 {
Victor Stinner551ac952011-11-29 22:58:13 +01006405 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006406 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006407 }
6408 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006409#endif
6410
6411 if (unicode_putchar(&v, &outpos, ch) < 0)
6412 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006413 }
6414
Victor Stinner16e6a802011-12-12 13:24:15 +01006415 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006416 goto onError;
6417 Py_XDECREF(errorHandler);
6418 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006419 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006420
Benjamin Peterson29060642009-01-31 22:14:21 +00006421 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006422 Py_XDECREF(v);
6423 Py_XDECREF(errorHandler);
6424 Py_XDECREF(exc);
6425 return NULL;
6426}
6427
Guido van Rossumd57fd912000-03-10 22:53:23 +00006428/* --- Latin-1 Codec ------------------------------------------------------ */
6429
Alexander Belopolsky40018472011-02-26 01:02:56 +00006430PyObject *
6431PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006432 Py_ssize_t size,
6433 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006434{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006435 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006436 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006437}
6438
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006439/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006440static void
6441make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006442 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006443 PyObject *unicode,
6444 Py_ssize_t startpos, Py_ssize_t endpos,
6445 const char *reason)
6446{
6447 if (*exceptionObject == NULL) {
6448 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006449 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006450 encoding, unicode, startpos, endpos, reason);
6451 }
6452 else {
6453 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6454 goto onError;
6455 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6456 goto onError;
6457 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6458 goto onError;
6459 return;
6460 onError:
6461 Py_DECREF(*exceptionObject);
6462 *exceptionObject = NULL;
6463 }
6464}
6465
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006466/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006467static void
6468raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006469 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006470 PyObject *unicode,
6471 Py_ssize_t startpos, Py_ssize_t endpos,
6472 const char *reason)
6473{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006474 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006475 encoding, unicode, startpos, endpos, reason);
6476 if (*exceptionObject != NULL)
6477 PyCodec_StrictErrors(*exceptionObject);
6478}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006479
6480/* error handling callback helper:
6481 build arguments, call the callback and check the arguments,
6482 put the result into newpos and return the replacement string, which
6483 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006484static PyObject *
6485unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006486 PyObject **errorHandler,
6487 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006488 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006489 Py_ssize_t startpos, Py_ssize_t endpos,
6490 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006491{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006492 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006493 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006494 PyObject *restuple;
6495 PyObject *resunicode;
6496
6497 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006498 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006499 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006500 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006501 }
6502
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006503 if (PyUnicode_READY(unicode) < 0)
6504 return NULL;
6505 len = PyUnicode_GET_LENGTH(unicode);
6506
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006507 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006508 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006509 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006510 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006511
6512 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006513 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006514 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006515 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006516 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006517 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006518 Py_DECREF(restuple);
6519 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006520 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006521 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006522 &resunicode, newpos)) {
6523 Py_DECREF(restuple);
6524 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006525 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006526 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6527 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6528 Py_DECREF(restuple);
6529 return NULL;
6530 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006531 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006532 *newpos = len + *newpos;
6533 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006534 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6535 Py_DECREF(restuple);
6536 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006537 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006538 Py_INCREF(resunicode);
6539 Py_DECREF(restuple);
6540 return resunicode;
6541}
6542
Alexander Belopolsky40018472011-02-26 01:02:56 +00006543static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006544unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006545 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006546 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006547{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006548 /* input state */
6549 Py_ssize_t pos=0, size;
6550 int kind;
6551 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006552 /* output object */
6553 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006554 /* pointer into the output */
6555 char *str;
6556 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006557 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006558 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6559 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006560 PyObject *errorHandler = NULL;
6561 PyObject *exc = NULL;
6562 /* the following variable is used for caching string comparisons
6563 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6564 int known_errorHandler = -1;
6565
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006566 if (PyUnicode_READY(unicode) < 0)
6567 return NULL;
6568 size = PyUnicode_GET_LENGTH(unicode);
6569 kind = PyUnicode_KIND(unicode);
6570 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006571 /* allocate enough for a simple encoding without
6572 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006573 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006574 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006575 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006576 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006577 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006578 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006579 ressize = size;
6580
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006581 while (pos < size) {
6582 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006583
Benjamin Peterson29060642009-01-31 22:14:21 +00006584 /* can we encode this? */
6585 if (c<limit) {
6586 /* no overflow check, because we know that the space is enough */
6587 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006588 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006589 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006590 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006591 Py_ssize_t requiredsize;
6592 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006593 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006594 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006595 Py_ssize_t collstart = pos;
6596 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006597 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006598 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006599 ++collend;
6600 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6601 if (known_errorHandler==-1) {
6602 if ((errors==NULL) || (!strcmp(errors, "strict")))
6603 known_errorHandler = 1;
6604 else if (!strcmp(errors, "replace"))
6605 known_errorHandler = 2;
6606 else if (!strcmp(errors, "ignore"))
6607 known_errorHandler = 3;
6608 else if (!strcmp(errors, "xmlcharrefreplace"))
6609 known_errorHandler = 4;
6610 else
6611 known_errorHandler = 0;
6612 }
6613 switch (known_errorHandler) {
6614 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006615 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006616 goto onError;
6617 case 2: /* replace */
6618 while (collstart++<collend)
6619 *str++ = '?'; /* fall through */
6620 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006621 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006622 break;
6623 case 4: /* xmlcharrefreplace */
6624 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006625 /* determine replacement size */
6626 for (i = collstart, repsize = 0; i < collend; ++i) {
6627 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6628 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006629 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006630 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006631 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006632 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006633 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006634 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006635 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006636 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006637 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006638 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006639 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006640 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006641 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006642 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006643 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006644 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006645 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006646 if (requiredsize > ressize) {
6647 if (requiredsize<2*ressize)
6648 requiredsize = 2*ressize;
6649 if (_PyBytes_Resize(&res, requiredsize))
6650 goto onError;
6651 str = PyBytes_AS_STRING(res) + respos;
6652 ressize = requiredsize;
6653 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006654 /* generate replacement */
6655 for (i = collstart; i < collend; ++i) {
6656 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006657 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006658 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006659 break;
6660 default:
6661 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006662 encoding, reason, unicode, &exc,
6663 collstart, collend, &newpos);
6664 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6665 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006666 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006667 if (PyBytes_Check(repunicode)) {
6668 /* Directly copy bytes result to output. */
6669 repsize = PyBytes_Size(repunicode);
6670 if (repsize > 1) {
6671 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006672 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006673 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6674 Py_DECREF(repunicode);
6675 goto onError;
6676 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006677 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006678 ressize += repsize-1;
6679 }
6680 memcpy(str, PyBytes_AsString(repunicode), repsize);
6681 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006682 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006683 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006684 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006685 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006686 /* need more space? (at least enough for what we
6687 have+the replacement+the rest of the string, so
6688 we won't have to check space for encodable characters) */
6689 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006690 repsize = PyUnicode_GET_LENGTH(repunicode);
6691 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006692 if (requiredsize > ressize) {
6693 if (requiredsize<2*ressize)
6694 requiredsize = 2*ressize;
6695 if (_PyBytes_Resize(&res, requiredsize)) {
6696 Py_DECREF(repunicode);
6697 goto onError;
6698 }
6699 str = PyBytes_AS_STRING(res) + respos;
6700 ressize = requiredsize;
6701 }
6702 /* check if there is anything unencodable in the replacement
6703 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006704 for (i = 0; repsize-->0; ++i, ++str) {
6705 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006706 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006707 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006708 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006709 Py_DECREF(repunicode);
6710 goto onError;
6711 }
6712 *str = (char)c;
6713 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006714 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006715 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006716 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006717 }
6718 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006719 /* Resize if we allocated to much */
6720 size = str - PyBytes_AS_STRING(res);
6721 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006722 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006723 if (_PyBytes_Resize(&res, size) < 0)
6724 goto onError;
6725 }
6726
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006727 Py_XDECREF(errorHandler);
6728 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006729 return res;
6730
6731 onError:
6732 Py_XDECREF(res);
6733 Py_XDECREF(errorHandler);
6734 Py_XDECREF(exc);
6735 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006736}
6737
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006738/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006739PyObject *
6740PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006741 Py_ssize_t size,
6742 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006743{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006744 PyObject *result;
6745 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6746 if (unicode == NULL)
6747 return NULL;
6748 result = unicode_encode_ucs1(unicode, errors, 256);
6749 Py_DECREF(unicode);
6750 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006751}
6752
Alexander Belopolsky40018472011-02-26 01:02:56 +00006753PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006754_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006755{
6756 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006757 PyErr_BadArgument();
6758 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006759 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006760 if (PyUnicode_READY(unicode) == -1)
6761 return NULL;
6762 /* Fast path: if it is a one-byte string, construct
6763 bytes object directly. */
6764 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6765 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6766 PyUnicode_GET_LENGTH(unicode));
6767 /* Non-Latin-1 characters present. Defer to above function to
6768 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006769 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006770}
6771
6772PyObject*
6773PyUnicode_AsLatin1String(PyObject *unicode)
6774{
6775 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006776}
6777
6778/* --- 7-bit ASCII Codec -------------------------------------------------- */
6779
Alexander Belopolsky40018472011-02-26 01:02:56 +00006780PyObject *
6781PyUnicode_DecodeASCII(const char *s,
6782 Py_ssize_t size,
6783 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006784{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006785 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006786 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006787 int kind;
6788 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006789 Py_ssize_t startinpos;
6790 Py_ssize_t endinpos;
6791 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006792 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006793 int has_error;
6794 const unsigned char *p = (const unsigned char *)s;
6795 const unsigned char *end = p + size;
6796 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006797 PyObject *errorHandler = NULL;
6798 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006799
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006800 if (size == 0) {
6801 Py_INCREF(unicode_empty);
6802 return unicode_empty;
6803 }
6804
Guido van Rossumd57fd912000-03-10 22:53:23 +00006805 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006806 if (size == 1 && (unsigned char)s[0] < 128)
6807 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006808
Victor Stinner702c7342011-10-05 13:50:52 +02006809 has_error = 0;
6810 while (p < end && !has_error) {
6811 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6812 an explanation. */
6813 if (!((size_t) p & LONG_PTR_MASK)) {
6814 /* Help register allocation */
6815 register const unsigned char *_p = p;
6816 while (_p < aligned_end) {
6817 unsigned long value = *(unsigned long *) _p;
6818 if (value & ASCII_CHAR_MASK) {
6819 has_error = 1;
6820 break;
6821 }
6822 _p += SIZEOF_LONG;
6823 }
6824 if (_p == end)
6825 break;
6826 if (has_error)
6827 break;
6828 p = _p;
6829 }
6830 if (*p & 0x80) {
6831 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006832 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006833 }
6834 else {
6835 ++p;
6836 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006837 }
Victor Stinner702c7342011-10-05 13:50:52 +02006838 if (!has_error)
6839 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006840
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006841 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006842 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006843 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006844 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006845 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006846 kind = PyUnicode_KIND(v);
6847 data = PyUnicode_DATA(v);
6848 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006849 e = s + size;
6850 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006851 register unsigned char c = (unsigned char)*s;
6852 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006853 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006854 ++s;
6855 }
6856 else {
6857 startinpos = s-starts;
6858 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006859 if (unicode_decode_call_errorhandler(
6860 errors, &errorHandler,
6861 "ascii", "ordinal not in range(128)",
6862 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006863 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006864 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006865 kind = PyUnicode_KIND(v);
6866 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006867 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006868 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006869 if (unicode_resize(&v, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006870 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006871 Py_XDECREF(errorHandler);
6872 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006873 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006874 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006875
Benjamin Peterson29060642009-01-31 22:14:21 +00006876 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006877 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006878 Py_XDECREF(errorHandler);
6879 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006880 return NULL;
6881}
6882
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006883/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006884PyObject *
6885PyUnicode_EncodeASCII(const Py_UNICODE *p,
6886 Py_ssize_t size,
6887 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006888{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006889 PyObject *result;
6890 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6891 if (unicode == NULL)
6892 return NULL;
6893 result = unicode_encode_ucs1(unicode, errors, 128);
6894 Py_DECREF(unicode);
6895 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006896}
6897
Alexander Belopolsky40018472011-02-26 01:02:56 +00006898PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006899_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006900{
6901 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006902 PyErr_BadArgument();
6903 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006904 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006905 if (PyUnicode_READY(unicode) == -1)
6906 return NULL;
6907 /* Fast path: if it is an ASCII-only string, construct bytes object
6908 directly. Else defer to above function to raise the exception. */
6909 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6910 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6911 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006912 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006913}
6914
6915PyObject *
6916PyUnicode_AsASCIIString(PyObject *unicode)
6917{
6918 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006919}
6920
Victor Stinner99b95382011-07-04 14:23:54 +02006921#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006922
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006923/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006924
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006925#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006926#define NEED_RETRY
6927#endif
6928
Victor Stinner3a50e702011-10-18 21:21:00 +02006929#ifndef WC_ERR_INVALID_CHARS
6930# define WC_ERR_INVALID_CHARS 0x0080
6931#endif
6932
6933static char*
6934code_page_name(UINT code_page, PyObject **obj)
6935{
6936 *obj = NULL;
6937 if (code_page == CP_ACP)
6938 return "mbcs";
6939 if (code_page == CP_UTF7)
6940 return "CP_UTF7";
6941 if (code_page == CP_UTF8)
6942 return "CP_UTF8";
6943
6944 *obj = PyBytes_FromFormat("cp%u", code_page);
6945 if (*obj == NULL)
6946 return NULL;
6947 return PyBytes_AS_STRING(*obj);
6948}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006949
Alexander Belopolsky40018472011-02-26 01:02:56 +00006950static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006951is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006952{
6953 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006954 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006955
Victor Stinner3a50e702011-10-18 21:21:00 +02006956 if (!IsDBCSLeadByteEx(code_page, *curr))
6957 return 0;
6958
6959 prev = CharPrevExA(code_page, s, curr, 0);
6960 if (prev == curr)
6961 return 1;
6962 /* FIXME: This code is limited to "true" double-byte encodings,
6963 as it assumes an incomplete character consists of a single
6964 byte. */
6965 if (curr - prev == 2)
6966 return 1;
6967 if (!IsDBCSLeadByteEx(code_page, *prev))
6968 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006969 return 0;
6970}
6971
Victor Stinner3a50e702011-10-18 21:21:00 +02006972static DWORD
6973decode_code_page_flags(UINT code_page)
6974{
6975 if (code_page == CP_UTF7) {
6976 /* The CP_UTF7 decoder only supports flags=0 */
6977 return 0;
6978 }
6979 else
6980 return MB_ERR_INVALID_CHARS;
6981}
6982
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006983/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006984 * Decode a byte string from a Windows code page into unicode object in strict
6985 * mode.
6986 *
6987 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6988 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006989 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006990static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006991decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006992 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006993 const char *in,
6994 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006995{
Victor Stinner3a50e702011-10-18 21:21:00 +02006996 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006997 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006998 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006999
7000 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007001 assert(insize > 0);
7002 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7003 if (outsize <= 0)
7004 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007005
7006 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007007 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007008 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007009 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007010 if (*v == NULL)
7011 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007012 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007013 }
7014 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007015 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007016 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007017 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007018 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007019 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007020 }
7021
7022 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007023 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7024 if (outsize <= 0)
7025 goto error;
7026 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007027
Victor Stinner3a50e702011-10-18 21:21:00 +02007028error:
7029 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7030 return -2;
7031 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007032 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007033}
7034
Victor Stinner3a50e702011-10-18 21:21:00 +02007035/*
7036 * Decode a byte string from a code page into unicode object with an error
7037 * handler.
7038 *
7039 * Returns consumed size if succeed, or raise a WindowsError or
7040 * UnicodeDecodeError exception and returns -1 on error.
7041 */
7042static int
7043decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007044 PyObject **v,
7045 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007046 const char *errors)
7047{
7048 const char *startin = in;
7049 const char *endin = in + size;
7050 const DWORD flags = decode_code_page_flags(code_page);
7051 /* Ideally, we should get reason from FormatMessage. This is the Windows
7052 2000 English version of the message. */
7053 const char *reason = "No mapping for the Unicode character exists "
7054 "in the target code page.";
7055 /* each step cannot decode more than 1 character, but a character can be
7056 represented as a surrogate pair */
7057 wchar_t buffer[2], *startout, *out;
7058 int insize, outsize;
7059 PyObject *errorHandler = NULL;
7060 PyObject *exc = NULL;
7061 PyObject *encoding_obj = NULL;
7062 char *encoding;
7063 DWORD err;
7064 int ret = -1;
7065
7066 assert(size > 0);
7067
7068 encoding = code_page_name(code_page, &encoding_obj);
7069 if (encoding == NULL)
7070 return -1;
7071
7072 if (errors == NULL || strcmp(errors, "strict") == 0) {
7073 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7074 UnicodeDecodeError. */
7075 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7076 if (exc != NULL) {
7077 PyCodec_StrictErrors(exc);
7078 Py_CLEAR(exc);
7079 }
7080 goto error;
7081 }
7082
7083 if (*v == NULL) {
7084 /* Create unicode object */
7085 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7086 PyErr_NoMemory();
7087 goto error;
7088 }
Victor Stinnerab595942011-12-17 04:59:06 +01007089 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007090 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007091 if (*v == NULL)
7092 goto error;
7093 startout = PyUnicode_AS_UNICODE(*v);
7094 }
7095 else {
7096 /* Extend unicode object */
7097 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7098 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7099 PyErr_NoMemory();
7100 goto error;
7101 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007102 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007103 goto error;
7104 startout = PyUnicode_AS_UNICODE(*v) + n;
7105 }
7106
7107 /* Decode the byte string character per character */
7108 out = startout;
7109 while (in < endin)
7110 {
7111 /* Decode a character */
7112 insize = 1;
7113 do
7114 {
7115 outsize = MultiByteToWideChar(code_page, flags,
7116 in, insize,
7117 buffer, Py_ARRAY_LENGTH(buffer));
7118 if (outsize > 0)
7119 break;
7120 err = GetLastError();
7121 if (err != ERROR_NO_UNICODE_TRANSLATION
7122 && err != ERROR_INSUFFICIENT_BUFFER)
7123 {
7124 PyErr_SetFromWindowsErr(0);
7125 goto error;
7126 }
7127 insize++;
7128 }
7129 /* 4=maximum length of a UTF-8 sequence */
7130 while (insize <= 4 && (in + insize) <= endin);
7131
7132 if (outsize <= 0) {
7133 Py_ssize_t startinpos, endinpos, outpos;
7134
7135 startinpos = in - startin;
7136 endinpos = startinpos + 1;
7137 outpos = out - PyUnicode_AS_UNICODE(*v);
7138 if (unicode_decode_call_errorhandler(
7139 errors, &errorHandler,
7140 encoding, reason,
7141 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007142 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007143 {
7144 goto error;
7145 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007146 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007147 }
7148 else {
7149 in += insize;
7150 memcpy(out, buffer, outsize * sizeof(wchar_t));
7151 out += outsize;
7152 }
7153 }
7154
7155 /* write a NUL character at the end */
7156 *out = 0;
7157
7158 /* Extend unicode object */
7159 outsize = out - startout;
7160 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007161 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007162 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007163 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007164
7165error:
7166 Py_XDECREF(encoding_obj);
7167 Py_XDECREF(errorHandler);
7168 Py_XDECREF(exc);
7169 return ret;
7170}
7171
Victor Stinner3a50e702011-10-18 21:21:00 +02007172static PyObject *
7173decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007174 const char *s, Py_ssize_t size,
7175 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007176{
Victor Stinner76a31a62011-11-04 00:05:13 +01007177 PyObject *v = NULL;
7178 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007179
Victor Stinner3a50e702011-10-18 21:21:00 +02007180 if (code_page < 0) {
7181 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7182 return NULL;
7183 }
7184
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007185 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007186 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007187
Victor Stinner76a31a62011-11-04 00:05:13 +01007188 do
7189 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007190#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007191 if (size > INT_MAX) {
7192 chunk_size = INT_MAX;
7193 final = 0;
7194 done = 0;
7195 }
7196 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007197#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007198 {
7199 chunk_size = (int)size;
7200 final = (consumed == NULL);
7201 done = 1;
7202 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007203
Victor Stinner76a31a62011-11-04 00:05:13 +01007204 /* Skip trailing lead-byte unless 'final' is set */
7205 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7206 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007207
Victor Stinner76a31a62011-11-04 00:05:13 +01007208 if (chunk_size == 0 && done) {
7209 if (v != NULL)
7210 break;
7211 Py_INCREF(unicode_empty);
7212 return unicode_empty;
7213 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007214
Victor Stinner76a31a62011-11-04 00:05:13 +01007215
7216 converted = decode_code_page_strict(code_page, &v,
7217 s, chunk_size);
7218 if (converted == -2)
7219 converted = decode_code_page_errors(code_page, &v,
7220 s, chunk_size,
7221 errors);
7222 assert(converted != 0);
7223
7224 if (converted < 0) {
7225 Py_XDECREF(v);
7226 return NULL;
7227 }
7228
7229 if (consumed)
7230 *consumed += converted;
7231
7232 s += converted;
7233 size -= converted;
7234 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007235
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007236 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007237}
7238
Alexander Belopolsky40018472011-02-26 01:02:56 +00007239PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007240PyUnicode_DecodeCodePageStateful(int code_page,
7241 const char *s,
7242 Py_ssize_t size,
7243 const char *errors,
7244 Py_ssize_t *consumed)
7245{
7246 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7247}
7248
7249PyObject *
7250PyUnicode_DecodeMBCSStateful(const char *s,
7251 Py_ssize_t size,
7252 const char *errors,
7253 Py_ssize_t *consumed)
7254{
7255 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7256}
7257
7258PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007259PyUnicode_DecodeMBCS(const char *s,
7260 Py_ssize_t size,
7261 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007262{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007263 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7264}
7265
Victor Stinner3a50e702011-10-18 21:21:00 +02007266static DWORD
7267encode_code_page_flags(UINT code_page, const char *errors)
7268{
7269 if (code_page == CP_UTF8) {
7270 if (winver.dwMajorVersion >= 6)
7271 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7272 and later */
7273 return WC_ERR_INVALID_CHARS;
7274 else
7275 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7276 return 0;
7277 }
7278 else if (code_page == CP_UTF7) {
7279 /* CP_UTF7 only supports flags=0 */
7280 return 0;
7281 }
7282 else {
7283 if (errors != NULL && strcmp(errors, "replace") == 0)
7284 return 0;
7285 else
7286 return WC_NO_BEST_FIT_CHARS;
7287 }
7288}
7289
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007290/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007291 * Encode a Unicode string to a Windows code page into a byte string in strict
7292 * mode.
7293 *
7294 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7295 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007296 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007297static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007298encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007299 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007300 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007301{
Victor Stinner554f3f02010-06-16 23:33:54 +00007302 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007303 BOOL *pusedDefaultChar = &usedDefaultChar;
7304 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007305 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007306 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007307 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007308 const DWORD flags = encode_code_page_flags(code_page, NULL);
7309 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007310 /* Create a substring so that we can get the UTF-16 representation
7311 of just the slice under consideration. */
7312 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007313
Martin v. Löwis3d325192011-11-04 18:23:06 +01007314 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007315
Victor Stinner3a50e702011-10-18 21:21:00 +02007316 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007317 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007318 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007319 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007320
Victor Stinner2fc507f2011-11-04 20:06:39 +01007321 substring = PyUnicode_Substring(unicode, offset, offset+len);
7322 if (substring == NULL)
7323 return -1;
7324 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7325 if (p == NULL) {
7326 Py_DECREF(substring);
7327 return -1;
7328 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007329
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007330 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007331 outsize = WideCharToMultiByte(code_page, flags,
7332 p, size,
7333 NULL, 0,
7334 NULL, pusedDefaultChar);
7335 if (outsize <= 0)
7336 goto error;
7337 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007338 if (pusedDefaultChar && *pusedDefaultChar) {
7339 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007340 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007341 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007342
Victor Stinner3a50e702011-10-18 21:21:00 +02007343 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007344 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007345 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007346 if (*outbytes == NULL) {
7347 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007348 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007349 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007350 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007351 }
7352 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007353 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007354 const Py_ssize_t n = PyBytes_Size(*outbytes);
7355 if (outsize > PY_SSIZE_T_MAX - n) {
7356 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007357 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007358 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007359 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007360 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7361 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007362 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007363 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007364 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007365 }
7366
7367 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007368 outsize = WideCharToMultiByte(code_page, flags,
7369 p, size,
7370 out, outsize,
7371 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007372 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007373 if (outsize <= 0)
7374 goto error;
7375 if (pusedDefaultChar && *pusedDefaultChar)
7376 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007377 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007378
Victor Stinner3a50e702011-10-18 21:21:00 +02007379error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007380 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007381 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7382 return -2;
7383 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007384 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007385}
7386
Victor Stinner3a50e702011-10-18 21:21:00 +02007387/*
7388 * Encode a Unicode string to a Windows code page into a byte string using a
7389 * error handler.
7390 *
7391 * Returns consumed characters if succeed, or raise a WindowsError and returns
7392 * -1 on other error.
7393 */
7394static int
7395encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007396 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007397 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007398{
Victor Stinner3a50e702011-10-18 21:21:00 +02007399 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007400 Py_ssize_t pos = unicode_offset;
7401 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007402 /* Ideally, we should get reason from FormatMessage. This is the Windows
7403 2000 English version of the message. */
7404 const char *reason = "invalid character";
7405 /* 4=maximum length of a UTF-8 sequence */
7406 char buffer[4];
7407 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7408 Py_ssize_t outsize;
7409 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007410 PyObject *errorHandler = NULL;
7411 PyObject *exc = NULL;
7412 PyObject *encoding_obj = NULL;
7413 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007414 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007415 PyObject *rep;
7416 int ret = -1;
7417
7418 assert(insize > 0);
7419
7420 encoding = code_page_name(code_page, &encoding_obj);
7421 if (encoding == NULL)
7422 return -1;
7423
7424 if (errors == NULL || strcmp(errors, "strict") == 0) {
7425 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7426 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007427 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007428 if (exc != NULL) {
7429 PyCodec_StrictErrors(exc);
7430 Py_DECREF(exc);
7431 }
7432 Py_XDECREF(encoding_obj);
7433 return -1;
7434 }
7435
7436 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7437 pusedDefaultChar = &usedDefaultChar;
7438 else
7439 pusedDefaultChar = NULL;
7440
7441 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7442 PyErr_NoMemory();
7443 goto error;
7444 }
7445 outsize = insize * Py_ARRAY_LENGTH(buffer);
7446
7447 if (*outbytes == NULL) {
7448 /* Create string object */
7449 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7450 if (*outbytes == NULL)
7451 goto error;
7452 out = PyBytes_AS_STRING(*outbytes);
7453 }
7454 else {
7455 /* Extend string object */
7456 Py_ssize_t n = PyBytes_Size(*outbytes);
7457 if (n > PY_SSIZE_T_MAX - outsize) {
7458 PyErr_NoMemory();
7459 goto error;
7460 }
7461 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7462 goto error;
7463 out = PyBytes_AS_STRING(*outbytes) + n;
7464 }
7465
7466 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007467 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007468 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007469 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7470 wchar_t chars[2];
7471 int charsize;
7472 if (ch < 0x10000) {
7473 chars[0] = (wchar_t)ch;
7474 charsize = 1;
7475 }
7476 else {
7477 ch -= 0x10000;
7478 chars[0] = 0xd800 + (ch >> 10);
7479 chars[1] = 0xdc00 + (ch & 0x3ff);
7480 charsize = 2;
7481 }
7482
Victor Stinner3a50e702011-10-18 21:21:00 +02007483 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007484 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007485 buffer, Py_ARRAY_LENGTH(buffer),
7486 NULL, pusedDefaultChar);
7487 if (outsize > 0) {
7488 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7489 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007490 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007491 memcpy(out, buffer, outsize);
7492 out += outsize;
7493 continue;
7494 }
7495 }
7496 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7497 PyErr_SetFromWindowsErr(0);
7498 goto error;
7499 }
7500
Victor Stinner3a50e702011-10-18 21:21:00 +02007501 rep = unicode_encode_call_errorhandler(
7502 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007503 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007504 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007505 if (rep == NULL)
7506 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007507 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007508
7509 if (PyBytes_Check(rep)) {
7510 outsize = PyBytes_GET_SIZE(rep);
7511 if (outsize != 1) {
7512 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7513 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7514 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7515 Py_DECREF(rep);
7516 goto error;
7517 }
7518 out = PyBytes_AS_STRING(*outbytes) + offset;
7519 }
7520 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7521 out += outsize;
7522 }
7523 else {
7524 Py_ssize_t i;
7525 enum PyUnicode_Kind kind;
7526 void *data;
7527
7528 if (PyUnicode_READY(rep) < 0) {
7529 Py_DECREF(rep);
7530 goto error;
7531 }
7532
7533 outsize = PyUnicode_GET_LENGTH(rep);
7534 if (outsize != 1) {
7535 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7536 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7537 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7538 Py_DECREF(rep);
7539 goto error;
7540 }
7541 out = PyBytes_AS_STRING(*outbytes) + offset;
7542 }
7543 kind = PyUnicode_KIND(rep);
7544 data = PyUnicode_DATA(rep);
7545 for (i=0; i < outsize; i++) {
7546 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7547 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007548 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007549 encoding, unicode,
7550 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007551 "unable to encode error handler result to ASCII");
7552 Py_DECREF(rep);
7553 goto error;
7554 }
7555 *out = (unsigned char)ch;
7556 out++;
7557 }
7558 }
7559 Py_DECREF(rep);
7560 }
7561 /* write a NUL byte */
7562 *out = 0;
7563 outsize = out - PyBytes_AS_STRING(*outbytes);
7564 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7565 if (_PyBytes_Resize(outbytes, outsize) < 0)
7566 goto error;
7567 ret = 0;
7568
7569error:
7570 Py_XDECREF(encoding_obj);
7571 Py_XDECREF(errorHandler);
7572 Py_XDECREF(exc);
7573 return ret;
7574}
7575
Victor Stinner3a50e702011-10-18 21:21:00 +02007576static PyObject *
7577encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007578 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007579 const char *errors)
7580{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007581 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007582 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007583 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007584 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007585
Victor Stinner2fc507f2011-11-04 20:06:39 +01007586 if (PyUnicode_READY(unicode) < 0)
7587 return NULL;
7588 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007589
Victor Stinner3a50e702011-10-18 21:21:00 +02007590 if (code_page < 0) {
7591 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7592 return NULL;
7593 }
7594
Martin v. Löwis3d325192011-11-04 18:23:06 +01007595 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007596 return PyBytes_FromStringAndSize(NULL, 0);
7597
Victor Stinner7581cef2011-11-03 22:32:33 +01007598 offset = 0;
7599 do
7600 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007601#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007602 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007603 chunks. */
7604 if (len > INT_MAX/2) {
7605 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007606 done = 0;
7607 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007608 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007609#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007610 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007611 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007612 done = 1;
7613 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007614
Victor Stinner76a31a62011-11-04 00:05:13 +01007615 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007616 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007617 errors);
7618 if (ret == -2)
7619 ret = encode_code_page_errors(code_page, &outbytes,
7620 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007621 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007622 if (ret < 0) {
7623 Py_XDECREF(outbytes);
7624 return NULL;
7625 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007626
Victor Stinner7581cef2011-11-03 22:32:33 +01007627 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007628 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007629 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007630
Victor Stinner3a50e702011-10-18 21:21:00 +02007631 return outbytes;
7632}
7633
7634PyObject *
7635PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7636 Py_ssize_t size,
7637 const char *errors)
7638{
Victor Stinner7581cef2011-11-03 22:32:33 +01007639 PyObject *unicode, *res;
7640 unicode = PyUnicode_FromUnicode(p, size);
7641 if (unicode == NULL)
7642 return NULL;
7643 res = encode_code_page(CP_ACP, unicode, errors);
7644 Py_DECREF(unicode);
7645 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007646}
7647
7648PyObject *
7649PyUnicode_EncodeCodePage(int code_page,
7650 PyObject *unicode,
7651 const char *errors)
7652{
Victor Stinner7581cef2011-11-03 22:32:33 +01007653 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007654}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007655
Alexander Belopolsky40018472011-02-26 01:02:56 +00007656PyObject *
7657PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007658{
7659 if (!PyUnicode_Check(unicode)) {
7660 PyErr_BadArgument();
7661 return NULL;
7662 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007663 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007664}
7665
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007666#undef NEED_RETRY
7667
Victor Stinner99b95382011-07-04 14:23:54 +02007668#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007669
Guido van Rossumd57fd912000-03-10 22:53:23 +00007670/* --- Character Mapping Codec -------------------------------------------- */
7671
Alexander Belopolsky40018472011-02-26 01:02:56 +00007672PyObject *
7673PyUnicode_DecodeCharmap(const char *s,
7674 Py_ssize_t size,
7675 PyObject *mapping,
7676 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007677{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007678 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007679 Py_ssize_t startinpos;
7680 Py_ssize_t endinpos;
7681 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007682 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007683 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007684 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007685 PyObject *errorHandler = NULL;
7686 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007687
Guido van Rossumd57fd912000-03-10 22:53:23 +00007688 /* Default to Latin-1 */
7689 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007690 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007691
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007692 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007693 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007694 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007695 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007696 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007697 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007698 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007699 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007700 Py_ssize_t maplen;
7701 enum PyUnicode_Kind kind;
7702 void *data;
7703 Py_UCS4 x;
7704
7705 if (PyUnicode_READY(mapping) < 0)
7706 return NULL;
7707
7708 maplen = PyUnicode_GET_LENGTH(mapping);
7709 data = PyUnicode_DATA(mapping);
7710 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007711 while (s < e) {
7712 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007713
Benjamin Peterson29060642009-01-31 22:14:21 +00007714 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007715 x = PyUnicode_READ(kind, data, ch);
7716 else
7717 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007718
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007719 if (x == 0xfffe)
7720 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007721 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007722 startinpos = s-starts;
7723 endinpos = startinpos+1;
7724 if (unicode_decode_call_errorhandler(
7725 errors, &errorHandler,
7726 "charmap", "character maps to <undefined>",
7727 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007728 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007729 goto onError;
7730 }
7731 continue;
7732 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007733
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007734 if (unicode_putchar(&v, &outpos, x) < 0)
7735 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007736 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007737 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007738 }
7739 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007740 while (s < e) {
7741 unsigned char ch = *s;
7742 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007743
Benjamin Peterson29060642009-01-31 22:14:21 +00007744 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7745 w = PyLong_FromLong((long)ch);
7746 if (w == NULL)
7747 goto onError;
7748 x = PyObject_GetItem(mapping, w);
7749 Py_DECREF(w);
7750 if (x == NULL) {
7751 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7752 /* No mapping found means: mapping is undefined. */
7753 PyErr_Clear();
7754 x = Py_None;
7755 Py_INCREF(x);
7756 } else
7757 goto onError;
7758 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007759
Benjamin Peterson29060642009-01-31 22:14:21 +00007760 /* Apply mapping */
7761 if (PyLong_Check(x)) {
7762 long value = PyLong_AS_LONG(x);
7763 if (value < 0 || value > 65535) {
7764 PyErr_SetString(PyExc_TypeError,
7765 "character mapping must be in range(65536)");
7766 Py_DECREF(x);
7767 goto onError;
7768 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007769 if (unicode_putchar(&v, &outpos, value) < 0)
7770 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007771 }
7772 else if (x == Py_None) {
7773 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007774 startinpos = s-starts;
7775 endinpos = startinpos+1;
7776 if (unicode_decode_call_errorhandler(
7777 errors, &errorHandler,
7778 "charmap", "character maps to <undefined>",
7779 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007780 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007781 Py_DECREF(x);
7782 goto onError;
7783 }
7784 Py_DECREF(x);
7785 continue;
7786 }
7787 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007788 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007789
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007790 if (PyUnicode_READY(x) < 0)
7791 goto onError;
7792 targetsize = PyUnicode_GET_LENGTH(x);
7793
7794 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007795 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007796 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007797 PyUnicode_READ_CHAR(x, 0)) < 0)
7798 goto onError;
7799 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007800 else if (targetsize > 1) {
7801 /* 1-n mapping */
7802 if (targetsize > extrachars) {
7803 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007804 Py_ssize_t needed = (targetsize - extrachars) + \
7805 (targetsize << 2);
7806 extrachars += needed;
7807 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007808 if (unicode_resize(&v,
7809 PyUnicode_GET_LENGTH(v) + needed) < 0)
7810 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007811 Py_DECREF(x);
7812 goto onError;
7813 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007814 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007815 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7816 goto onError;
7817 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7818 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007819 extrachars -= targetsize;
7820 }
7821 /* 1-0 mapping: skip the character */
7822 }
7823 else {
7824 /* wrong return value */
7825 PyErr_SetString(PyExc_TypeError,
7826 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007827 Py_DECREF(x);
7828 goto onError;
7829 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007830 Py_DECREF(x);
7831 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007832 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007833 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007834 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007835 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007836 Py_XDECREF(errorHandler);
7837 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007838 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007839
Benjamin Peterson29060642009-01-31 22:14:21 +00007840 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007841 Py_XDECREF(errorHandler);
7842 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007843 Py_XDECREF(v);
7844 return NULL;
7845}
7846
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007847/* Charmap encoding: the lookup table */
7848
Alexander Belopolsky40018472011-02-26 01:02:56 +00007849struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007850 PyObject_HEAD
7851 unsigned char level1[32];
7852 int count2, count3;
7853 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007854};
7855
7856static PyObject*
7857encoding_map_size(PyObject *obj, PyObject* args)
7858{
7859 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007860 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007861 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007862}
7863
7864static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007865 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007866 PyDoc_STR("Return the size (in bytes) of this object") },
7867 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007868};
7869
7870static void
7871encoding_map_dealloc(PyObject* o)
7872{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007873 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007874}
7875
7876static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007877 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007878 "EncodingMap", /*tp_name*/
7879 sizeof(struct encoding_map), /*tp_basicsize*/
7880 0, /*tp_itemsize*/
7881 /* methods */
7882 encoding_map_dealloc, /*tp_dealloc*/
7883 0, /*tp_print*/
7884 0, /*tp_getattr*/
7885 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007886 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007887 0, /*tp_repr*/
7888 0, /*tp_as_number*/
7889 0, /*tp_as_sequence*/
7890 0, /*tp_as_mapping*/
7891 0, /*tp_hash*/
7892 0, /*tp_call*/
7893 0, /*tp_str*/
7894 0, /*tp_getattro*/
7895 0, /*tp_setattro*/
7896 0, /*tp_as_buffer*/
7897 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7898 0, /*tp_doc*/
7899 0, /*tp_traverse*/
7900 0, /*tp_clear*/
7901 0, /*tp_richcompare*/
7902 0, /*tp_weaklistoffset*/
7903 0, /*tp_iter*/
7904 0, /*tp_iternext*/
7905 encoding_map_methods, /*tp_methods*/
7906 0, /*tp_members*/
7907 0, /*tp_getset*/
7908 0, /*tp_base*/
7909 0, /*tp_dict*/
7910 0, /*tp_descr_get*/
7911 0, /*tp_descr_set*/
7912 0, /*tp_dictoffset*/
7913 0, /*tp_init*/
7914 0, /*tp_alloc*/
7915 0, /*tp_new*/
7916 0, /*tp_free*/
7917 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007918};
7919
7920PyObject*
7921PyUnicode_BuildEncodingMap(PyObject* string)
7922{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007923 PyObject *result;
7924 struct encoding_map *mresult;
7925 int i;
7926 int need_dict = 0;
7927 unsigned char level1[32];
7928 unsigned char level2[512];
7929 unsigned char *mlevel1, *mlevel2, *mlevel3;
7930 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007931 int kind;
7932 void *data;
7933 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007934
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007935 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007936 PyErr_BadArgument();
7937 return NULL;
7938 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007939 kind = PyUnicode_KIND(string);
7940 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007941 memset(level1, 0xFF, sizeof level1);
7942 memset(level2, 0xFF, sizeof level2);
7943
7944 /* If there isn't a one-to-one mapping of NULL to \0,
7945 or if there are non-BMP characters, we need to use
7946 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007947 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007948 need_dict = 1;
7949 for (i = 1; i < 256; i++) {
7950 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007951 ch = PyUnicode_READ(kind, data, i);
7952 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007953 need_dict = 1;
7954 break;
7955 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007956 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007957 /* unmapped character */
7958 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007959 l1 = ch >> 11;
7960 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007961 if (level1[l1] == 0xFF)
7962 level1[l1] = count2++;
7963 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007964 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007965 }
7966
7967 if (count2 >= 0xFF || count3 >= 0xFF)
7968 need_dict = 1;
7969
7970 if (need_dict) {
7971 PyObject *result = PyDict_New();
7972 PyObject *key, *value;
7973 if (!result)
7974 return NULL;
7975 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007976 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007977 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007978 if (!key || !value)
7979 goto failed1;
7980 if (PyDict_SetItem(result, key, value) == -1)
7981 goto failed1;
7982 Py_DECREF(key);
7983 Py_DECREF(value);
7984 }
7985 return result;
7986 failed1:
7987 Py_XDECREF(key);
7988 Py_XDECREF(value);
7989 Py_DECREF(result);
7990 return NULL;
7991 }
7992
7993 /* Create a three-level trie */
7994 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7995 16*count2 + 128*count3 - 1);
7996 if (!result)
7997 return PyErr_NoMemory();
7998 PyObject_Init(result, &EncodingMapType);
7999 mresult = (struct encoding_map*)result;
8000 mresult->count2 = count2;
8001 mresult->count3 = count3;
8002 mlevel1 = mresult->level1;
8003 mlevel2 = mresult->level23;
8004 mlevel3 = mresult->level23 + 16*count2;
8005 memcpy(mlevel1, level1, 32);
8006 memset(mlevel2, 0xFF, 16*count2);
8007 memset(mlevel3, 0, 128*count3);
8008 count3 = 0;
8009 for (i = 1; i < 256; i++) {
8010 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008011 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008012 /* unmapped character */
8013 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008014 o1 = PyUnicode_READ(kind, data, i)>>11;
8015 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008016 i2 = 16*mlevel1[o1] + o2;
8017 if (mlevel2[i2] == 0xFF)
8018 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008019 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008020 i3 = 128*mlevel2[i2] + o3;
8021 mlevel3[i3] = i;
8022 }
8023 return result;
8024}
8025
8026static int
Victor Stinner22168992011-11-20 17:09:18 +01008027encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008028{
8029 struct encoding_map *map = (struct encoding_map*)mapping;
8030 int l1 = c>>11;
8031 int l2 = (c>>7) & 0xF;
8032 int l3 = c & 0x7F;
8033 int i;
8034
Victor Stinner22168992011-11-20 17:09:18 +01008035 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008036 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008037 if (c == 0)
8038 return 0;
8039 /* level 1*/
8040 i = map->level1[l1];
8041 if (i == 0xFF) {
8042 return -1;
8043 }
8044 /* level 2*/
8045 i = map->level23[16*i+l2];
8046 if (i == 0xFF) {
8047 return -1;
8048 }
8049 /* level 3 */
8050 i = map->level23[16*map->count2 + 128*i + l3];
8051 if (i == 0) {
8052 return -1;
8053 }
8054 return i;
8055}
8056
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008057/* Lookup the character ch in the mapping. If the character
8058 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008059 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008060static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008061charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008062{
Christian Heimes217cfd12007-12-02 14:31:20 +00008063 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008064 PyObject *x;
8065
8066 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008067 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008068 x = PyObject_GetItem(mapping, w);
8069 Py_DECREF(w);
8070 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008071 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8072 /* No mapping found means: mapping is undefined. */
8073 PyErr_Clear();
8074 x = Py_None;
8075 Py_INCREF(x);
8076 return x;
8077 } else
8078 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008079 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008080 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008081 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008082 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008083 long value = PyLong_AS_LONG(x);
8084 if (value < 0 || value > 255) {
8085 PyErr_SetString(PyExc_TypeError,
8086 "character mapping must be in range(256)");
8087 Py_DECREF(x);
8088 return NULL;
8089 }
8090 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008091 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008092 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008093 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008094 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008095 /* wrong return value */
8096 PyErr_Format(PyExc_TypeError,
8097 "character mapping must return integer, bytes or None, not %.400s",
8098 x->ob_type->tp_name);
8099 Py_DECREF(x);
8100 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008101 }
8102}
8103
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008104static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008105charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008106{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008107 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8108 /* exponentially overallocate to minimize reallocations */
8109 if (requiredsize < 2*outsize)
8110 requiredsize = 2*outsize;
8111 if (_PyBytes_Resize(outobj, requiredsize))
8112 return -1;
8113 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008114}
8115
Benjamin Peterson14339b62009-01-31 16:36:08 +00008116typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008117 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008118} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008119/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008120 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008121 space is available. Return a new reference to the object that
8122 was put in the output buffer, or Py_None, if the mapping was undefined
8123 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008124 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008125static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008126charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008127 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008128{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008129 PyObject *rep;
8130 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008131 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008132
Christian Heimes90aa7642007-12-19 02:45:37 +00008133 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008134 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008135 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008136 if (res == -1)
8137 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008138 if (outsize<requiredsize)
8139 if (charmapencode_resize(outobj, outpos, requiredsize))
8140 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008141 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008142 outstart[(*outpos)++] = (char)res;
8143 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008144 }
8145
8146 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008147 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008148 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008149 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008150 Py_DECREF(rep);
8151 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008152 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008153 if (PyLong_Check(rep)) {
8154 Py_ssize_t requiredsize = *outpos+1;
8155 if (outsize<requiredsize)
8156 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8157 Py_DECREF(rep);
8158 return enc_EXCEPTION;
8159 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008160 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008161 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008162 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008163 else {
8164 const char *repchars = PyBytes_AS_STRING(rep);
8165 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8166 Py_ssize_t requiredsize = *outpos+repsize;
8167 if (outsize<requiredsize)
8168 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8169 Py_DECREF(rep);
8170 return enc_EXCEPTION;
8171 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008172 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008173 memcpy(outstart + *outpos, repchars, repsize);
8174 *outpos += repsize;
8175 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008176 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008177 Py_DECREF(rep);
8178 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008179}
8180
8181/* handle an error in PyUnicode_EncodeCharmap
8182 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008183static int
8184charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008185 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008186 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008187 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008188 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008189{
8190 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008191 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008192 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008193 enum PyUnicode_Kind kind;
8194 void *data;
8195 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008196 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008197 Py_ssize_t collstartpos = *inpos;
8198 Py_ssize_t collendpos = *inpos+1;
8199 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008200 char *encoding = "charmap";
8201 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008202 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008203 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008204 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008205
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008206 if (PyUnicode_READY(unicode) < 0)
8207 return -1;
8208 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008209 /* find all unencodable characters */
8210 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008211 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008212 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008213 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008214 val = encoding_map_lookup(ch, mapping);
8215 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008216 break;
8217 ++collendpos;
8218 continue;
8219 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008220
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008221 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8222 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008223 if (rep==NULL)
8224 return -1;
8225 else if (rep!=Py_None) {
8226 Py_DECREF(rep);
8227 break;
8228 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008229 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008230 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008231 }
8232 /* cache callback name lookup
8233 * (if not done yet, i.e. it's the first error) */
8234 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008235 if ((errors==NULL) || (!strcmp(errors, "strict")))
8236 *known_errorHandler = 1;
8237 else if (!strcmp(errors, "replace"))
8238 *known_errorHandler = 2;
8239 else if (!strcmp(errors, "ignore"))
8240 *known_errorHandler = 3;
8241 else if (!strcmp(errors, "xmlcharrefreplace"))
8242 *known_errorHandler = 4;
8243 else
8244 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008245 }
8246 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008247 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008248 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008249 return -1;
8250 case 2: /* replace */
8251 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008252 x = charmapencode_output('?', mapping, res, respos);
8253 if (x==enc_EXCEPTION) {
8254 return -1;
8255 }
8256 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008257 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008258 return -1;
8259 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008260 }
8261 /* fall through */
8262 case 3: /* ignore */
8263 *inpos = collendpos;
8264 break;
8265 case 4: /* xmlcharrefreplace */
8266 /* generate replacement (temporarily (mis)uses p) */
8267 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008268 char buffer[2+29+1+1];
8269 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008270 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008271 for (cp = buffer; *cp; ++cp) {
8272 x = charmapencode_output(*cp, mapping, res, respos);
8273 if (x==enc_EXCEPTION)
8274 return -1;
8275 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008276 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008277 return -1;
8278 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008279 }
8280 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008281 *inpos = collendpos;
8282 break;
8283 default:
8284 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008285 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008286 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008287 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008288 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008289 if (PyBytes_Check(repunicode)) {
8290 /* Directly copy bytes result to output. */
8291 Py_ssize_t outsize = PyBytes_Size(*res);
8292 Py_ssize_t requiredsize;
8293 repsize = PyBytes_Size(repunicode);
8294 requiredsize = *respos + repsize;
8295 if (requiredsize > outsize)
8296 /* Make room for all additional bytes. */
8297 if (charmapencode_resize(res, respos, requiredsize)) {
8298 Py_DECREF(repunicode);
8299 return -1;
8300 }
8301 memcpy(PyBytes_AsString(*res) + *respos,
8302 PyBytes_AsString(repunicode), repsize);
8303 *respos += repsize;
8304 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008305 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008306 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008307 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008308 /* generate replacement */
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008309 if (PyUnicode_READY(repunicode) < 0) {
8310 Py_DECREF(repunicode);
8311 return -1;
8312 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008313 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008314 data = PyUnicode_DATA(repunicode);
8315 kind = PyUnicode_KIND(repunicode);
8316 for (index = 0; index < repsize; index++) {
8317 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8318 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008319 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008320 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008321 return -1;
8322 }
8323 else if (x==enc_FAILED) {
8324 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008325 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008326 return -1;
8327 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008328 }
8329 *inpos = newpos;
8330 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008331 }
8332 return 0;
8333}
8334
Alexander Belopolsky40018472011-02-26 01:02:56 +00008335PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008336_PyUnicode_EncodeCharmap(PyObject *unicode,
8337 PyObject *mapping,
8338 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008339{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008340 /* output object */
8341 PyObject *res = NULL;
8342 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008343 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008344 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008345 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008346 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008347 PyObject *errorHandler = NULL;
8348 PyObject *exc = NULL;
8349 /* the following variable is used for caching string comparisons
8350 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8351 * 3=ignore, 4=xmlcharrefreplace */
8352 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008353
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008354 if (PyUnicode_READY(unicode) < 0)
8355 return NULL;
8356 size = PyUnicode_GET_LENGTH(unicode);
8357
Guido van Rossumd57fd912000-03-10 22:53:23 +00008358 /* Default to Latin-1 */
8359 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008360 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008361
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008362 /* allocate enough for a simple encoding without
8363 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008364 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008365 if (res == NULL)
8366 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008367 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008368 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008369
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008370 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008371 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008372 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008373 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008374 if (x==enc_EXCEPTION) /* error */
8375 goto onError;
8376 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008377 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008378 &exc,
8379 &known_errorHandler, &errorHandler, errors,
8380 &res, &respos)) {
8381 goto onError;
8382 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008383 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008384 else
8385 /* done with this character => adjust input position */
8386 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008387 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008388
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008389 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008390 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008391 if (_PyBytes_Resize(&res, respos) < 0)
8392 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008393
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008394 Py_XDECREF(exc);
8395 Py_XDECREF(errorHandler);
8396 return res;
8397
Benjamin Peterson29060642009-01-31 22:14:21 +00008398 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008399 Py_XDECREF(res);
8400 Py_XDECREF(exc);
8401 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008402 return NULL;
8403}
8404
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008405/* Deprecated */
8406PyObject *
8407PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8408 Py_ssize_t size,
8409 PyObject *mapping,
8410 const char *errors)
8411{
8412 PyObject *result;
8413 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8414 if (unicode == NULL)
8415 return NULL;
8416 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8417 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008418 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008419}
8420
Alexander Belopolsky40018472011-02-26 01:02:56 +00008421PyObject *
8422PyUnicode_AsCharmapString(PyObject *unicode,
8423 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008424{
8425 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 PyErr_BadArgument();
8427 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008428 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008429 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008430}
8431
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008432/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008433static void
8434make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008435 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008436 Py_ssize_t startpos, Py_ssize_t endpos,
8437 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008438{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008439 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008440 *exceptionObject = _PyUnicodeTranslateError_Create(
8441 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008442 }
8443 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008444 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8445 goto onError;
8446 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8447 goto onError;
8448 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8449 goto onError;
8450 return;
8451 onError:
8452 Py_DECREF(*exceptionObject);
8453 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008454 }
8455}
8456
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008457/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008458static void
8459raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008460 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008461 Py_ssize_t startpos, Py_ssize_t endpos,
8462 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008463{
8464 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008465 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008466 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008467 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008468}
8469
8470/* error handling callback helper:
8471 build arguments, call the callback and check the arguments,
8472 put the result into newpos and return the replacement string, which
8473 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008474static PyObject *
8475unicode_translate_call_errorhandler(const char *errors,
8476 PyObject **errorHandler,
8477 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008478 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008479 Py_ssize_t startpos, Py_ssize_t endpos,
8480 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008481{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008482 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008483
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008484 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008485 PyObject *restuple;
8486 PyObject *resunicode;
8487
8488 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008489 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008490 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008491 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008492 }
8493
8494 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008495 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008496 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008497 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008498
8499 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008500 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008501 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008503 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008504 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008505 Py_DECREF(restuple);
8506 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008507 }
8508 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008509 &resunicode, &i_newpos)) {
8510 Py_DECREF(restuple);
8511 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008512 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008513 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008514 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008515 else
8516 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008517 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008518 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8519 Py_DECREF(restuple);
8520 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008521 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008522 Py_INCREF(resunicode);
8523 Py_DECREF(restuple);
8524 return resunicode;
8525}
8526
8527/* Lookup the character ch in the mapping and put the result in result,
8528 which must be decrefed by the caller.
8529 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008530static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008531charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008532{
Christian Heimes217cfd12007-12-02 14:31:20 +00008533 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008534 PyObject *x;
8535
8536 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008537 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008538 x = PyObject_GetItem(mapping, w);
8539 Py_DECREF(w);
8540 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008541 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8542 /* No mapping found means: use 1:1 mapping. */
8543 PyErr_Clear();
8544 *result = NULL;
8545 return 0;
8546 } else
8547 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008548 }
8549 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008550 *result = x;
8551 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008552 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008553 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008554 long value = PyLong_AS_LONG(x);
8555 long max = PyUnicode_GetMax();
8556 if (value < 0 || value > max) {
8557 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008558 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008559 Py_DECREF(x);
8560 return -1;
8561 }
8562 *result = x;
8563 return 0;
8564 }
8565 else if (PyUnicode_Check(x)) {
8566 *result = x;
8567 return 0;
8568 }
8569 else {
8570 /* wrong return value */
8571 PyErr_SetString(PyExc_TypeError,
8572 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008573 Py_DECREF(x);
8574 return -1;
8575 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008576}
8577/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008578 if not reallocate and adjust various state variables.
8579 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008580static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008581charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008582 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008583{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008584 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008585 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008586 /* exponentially overallocate to minimize reallocations */
8587 if (requiredsize < 2 * oldsize)
8588 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008589 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8590 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008591 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008592 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008593 }
8594 return 0;
8595}
8596/* lookup the character, put the result in the output string and adjust
8597 various state variables. Return a new reference to the object that
8598 was put in the output buffer in *result, or Py_None, if the mapping was
8599 undefined (in which case no character was written).
8600 The called must decref result.
8601 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008602static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008603charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8604 PyObject *mapping, Py_UCS4 **output,
8605 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008606 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008607{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008608 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8609 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008610 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008611 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008612 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008613 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008614 }
8615 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008616 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008617 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008618 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008619 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008620 }
8621 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008622 Py_ssize_t repsize;
8623 if (PyUnicode_READY(*res) == -1)
8624 return -1;
8625 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008626 if (repsize==1) {
8627 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008628 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008629 }
8630 else if (repsize!=0) {
8631 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008632 Py_ssize_t requiredsize = *opos +
8633 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008634 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008635 Py_ssize_t i;
8636 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008637 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008638 for(i = 0; i < repsize; i++)
8639 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008640 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008641 }
8642 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008643 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008644 return 0;
8645}
8646
Alexander Belopolsky40018472011-02-26 01:02:56 +00008647PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008648_PyUnicode_TranslateCharmap(PyObject *input,
8649 PyObject *mapping,
8650 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008651{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008652 /* input object */
8653 char *idata;
8654 Py_ssize_t size, i;
8655 int kind;
8656 /* output buffer */
8657 Py_UCS4 *output = NULL;
8658 Py_ssize_t osize;
8659 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008660 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008661 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008662 char *reason = "character maps to <undefined>";
8663 PyObject *errorHandler = NULL;
8664 PyObject *exc = NULL;
8665 /* the following variable is used for caching string comparisons
8666 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8667 * 3=ignore, 4=xmlcharrefreplace */
8668 int known_errorHandler = -1;
8669
Guido van Rossumd57fd912000-03-10 22:53:23 +00008670 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008671 PyErr_BadArgument();
8672 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008673 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008674
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008675 if (PyUnicode_READY(input) == -1)
8676 return NULL;
8677 idata = (char*)PyUnicode_DATA(input);
8678 kind = PyUnicode_KIND(input);
8679 size = PyUnicode_GET_LENGTH(input);
8680 i = 0;
8681
8682 if (size == 0) {
8683 Py_INCREF(input);
8684 return input;
8685 }
8686
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008687 /* allocate enough for a simple 1:1 translation without
8688 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008689 osize = size;
8690 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8691 opos = 0;
8692 if (output == NULL) {
8693 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008694 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008695 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008696
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008697 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008698 /* try to encode it */
8699 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008700 if (charmaptranslate_output(input, i, mapping,
8701 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 Py_XDECREF(x);
8703 goto onError;
8704 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008705 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008706 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008707 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008708 else { /* untranslatable character */
8709 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8710 Py_ssize_t repsize;
8711 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008712 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008713 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008714 Py_ssize_t collstart = i;
8715 Py_ssize_t collend = i+1;
8716 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008717
Benjamin Peterson29060642009-01-31 22:14:21 +00008718 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008719 while (collend < size) {
8720 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008721 goto onError;
8722 Py_XDECREF(x);
8723 if (x!=Py_None)
8724 break;
8725 ++collend;
8726 }
8727 /* cache callback name lookup
8728 * (if not done yet, i.e. it's the first error) */
8729 if (known_errorHandler==-1) {
8730 if ((errors==NULL) || (!strcmp(errors, "strict")))
8731 known_errorHandler = 1;
8732 else if (!strcmp(errors, "replace"))
8733 known_errorHandler = 2;
8734 else if (!strcmp(errors, "ignore"))
8735 known_errorHandler = 3;
8736 else if (!strcmp(errors, "xmlcharrefreplace"))
8737 known_errorHandler = 4;
8738 else
8739 known_errorHandler = 0;
8740 }
8741 switch (known_errorHandler) {
8742 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008743 raise_translate_exception(&exc, input, collstart,
8744 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008745 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008746 case 2: /* replace */
8747 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008748 for (coll = collstart; coll<collend; coll++)
8749 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008750 /* fall through */
8751 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008752 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008753 break;
8754 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008755 /* generate replacement (temporarily (mis)uses i) */
8756 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008757 char buffer[2+29+1+1];
8758 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008759 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8760 if (charmaptranslate_makespace(&output, &osize,
8761 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008762 goto onError;
8763 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008764 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008765 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008766 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008767 break;
8768 default:
8769 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008770 reason, input, &exc,
8771 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008772 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008773 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008774 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008775 Py_DECREF(repunicode);
8776 goto onError;
8777 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008778 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008779 repsize = PyUnicode_GET_LENGTH(repunicode);
8780 if (charmaptranslate_makespace(&output, &osize,
8781 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008782 Py_DECREF(repunicode);
8783 goto onError;
8784 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008785 for (uni2 = 0; repsize-->0; ++uni2)
8786 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8787 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008788 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008789 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008790 }
8791 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008792 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8793 if (!res)
8794 goto onError;
8795 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008796 Py_XDECREF(exc);
8797 Py_XDECREF(errorHandler);
8798 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008799
Benjamin Peterson29060642009-01-31 22:14:21 +00008800 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008801 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008802 Py_XDECREF(exc);
8803 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008804 return NULL;
8805}
8806
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008807/* Deprecated. Use PyUnicode_Translate instead. */
8808PyObject *
8809PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8810 Py_ssize_t size,
8811 PyObject *mapping,
8812 const char *errors)
8813{
8814 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8815 if (!unicode)
8816 return NULL;
8817 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8818}
8819
Alexander Belopolsky40018472011-02-26 01:02:56 +00008820PyObject *
8821PyUnicode_Translate(PyObject *str,
8822 PyObject *mapping,
8823 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008824{
8825 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008826
Guido van Rossumd57fd912000-03-10 22:53:23 +00008827 str = PyUnicode_FromObject(str);
8828 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008829 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008830 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008831 Py_DECREF(str);
8832 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008833
Benjamin Peterson29060642009-01-31 22:14:21 +00008834 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008835 Py_XDECREF(str);
8836 return NULL;
8837}
Tim Petersced69f82003-09-16 20:30:58 +00008838
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008839static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008840fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008841{
8842 /* No need to call PyUnicode_READY(self) because this function is only
8843 called as a callback from fixup() which does it already. */
8844 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8845 const int kind = PyUnicode_KIND(self);
8846 void *data = PyUnicode_DATA(self);
8847 Py_UCS4 maxchar = 0, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008848 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008849 Py_ssize_t i;
8850
8851 for (i = 0; i < len; ++i) {
8852 ch = PyUnicode_READ(kind, data, i);
8853 fixed = 0;
8854 if (ch > 127) {
8855 if (Py_UNICODE_ISSPACE(ch))
8856 fixed = ' ';
8857 else {
8858 const int decimal = Py_UNICODE_TODECIMAL(ch);
8859 if (decimal >= 0)
8860 fixed = '0' + decimal;
8861 }
8862 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008863 modified = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008864 if (fixed > maxchar)
8865 maxchar = fixed;
8866 PyUnicode_WRITE(kind, data, i, fixed);
8867 }
8868 else if (ch > maxchar)
8869 maxchar = ch;
8870 }
8871 else if (ch > maxchar)
8872 maxchar = ch;
8873 }
8874
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008875 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008876}
8877
8878PyObject *
8879_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8880{
8881 if (!PyUnicode_Check(unicode)) {
8882 PyErr_BadInternalCall();
8883 return NULL;
8884 }
8885 if (PyUnicode_READY(unicode) == -1)
8886 return NULL;
8887 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8888 /* If the string is already ASCII, just return the same string */
8889 Py_INCREF(unicode);
8890 return unicode;
8891 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008892 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008893}
8894
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008895PyObject *
8896PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8897 Py_ssize_t length)
8898{
Victor Stinnerf0124502011-11-21 23:12:56 +01008899 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008900 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008901 Py_UCS4 maxchar;
8902 enum PyUnicode_Kind kind;
8903 void *data;
8904
8905 maxchar = 0;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008906 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008907 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008908 if (ch > 127) {
8909 int decimal = Py_UNICODE_TODECIMAL(ch);
8910 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008911 ch = '0' + decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008912 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008913 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008914 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008915
8916 /* Copy to a new string */
8917 decimal = PyUnicode_New(length, maxchar);
8918 if (decimal == NULL)
8919 return decimal;
8920 kind = PyUnicode_KIND(decimal);
8921 data = PyUnicode_DATA(decimal);
8922 /* Iterate over code points */
8923 for (i = 0; i < length; i++) {
8924 Py_UNICODE ch = s[i];
8925 if (ch > 127) {
8926 int decimal = Py_UNICODE_TODECIMAL(ch);
8927 if (decimal >= 0)
8928 ch = '0' + decimal;
8929 }
8930 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008931 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008932 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008933}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008934/* --- Decimal Encoder ---------------------------------------------------- */
8935
Alexander Belopolsky40018472011-02-26 01:02:56 +00008936int
8937PyUnicode_EncodeDecimal(Py_UNICODE *s,
8938 Py_ssize_t length,
8939 char *output,
8940 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008941{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008942 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008943 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008944 enum PyUnicode_Kind kind;
8945 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008946
8947 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008948 PyErr_BadArgument();
8949 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008950 }
8951
Victor Stinner42bf7752011-11-21 22:52:58 +01008952 unicode = PyUnicode_FromUnicode(s, length);
8953 if (unicode == NULL)
8954 return -1;
8955
Victor Stinner6345be92011-11-25 20:09:01 +01008956 if (PyUnicode_READY(unicode) < 0) {
8957 Py_DECREF(unicode);
8958 return -1;
8959 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008960 kind = PyUnicode_KIND(unicode);
8961 data = PyUnicode_DATA(unicode);
8962
Victor Stinnerb84d7232011-11-22 01:50:07 +01008963 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008964 PyObject *exc;
8965 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008966 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008967 Py_ssize_t startpos;
8968
8969 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008970
Benjamin Peterson29060642009-01-31 22:14:21 +00008971 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008972 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008973 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008974 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008975 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008976 decimal = Py_UNICODE_TODECIMAL(ch);
8977 if (decimal >= 0) {
8978 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008979 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008980 continue;
8981 }
8982 if (0 < ch && ch < 256) {
8983 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008984 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008985 continue;
8986 }
Victor Stinner6345be92011-11-25 20:09:01 +01008987
Victor Stinner42bf7752011-11-21 22:52:58 +01008988 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008989 exc = NULL;
8990 raise_encode_exception(&exc, "decimal", unicode,
8991 startpos, startpos+1,
8992 "invalid decimal Unicode string");
8993 Py_XDECREF(exc);
8994 Py_DECREF(unicode);
8995 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008996 }
8997 /* 0-terminate the output string */
8998 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008999 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009000 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009001}
9002
Guido van Rossumd57fd912000-03-10 22:53:23 +00009003/* --- Helpers ------------------------------------------------------------ */
9004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009005static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009006any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009007 Py_ssize_t start,
9008 Py_ssize_t end)
9009{
9010 int kind1, kind2, kind;
9011 void *buf1, *buf2;
9012 Py_ssize_t len1, len2, result;
9013
9014 kind1 = PyUnicode_KIND(s1);
9015 kind2 = PyUnicode_KIND(s2);
9016 kind = kind1 > kind2 ? kind1 : kind2;
9017 buf1 = PyUnicode_DATA(s1);
9018 buf2 = PyUnicode_DATA(s2);
9019 if (kind1 != kind)
9020 buf1 = _PyUnicode_AsKind(s1, kind);
9021 if (!buf1)
9022 return -2;
9023 if (kind2 != kind)
9024 buf2 = _PyUnicode_AsKind(s2, kind);
9025 if (!buf2) {
9026 if (kind1 != kind) PyMem_Free(buf1);
9027 return -2;
9028 }
9029 len1 = PyUnicode_GET_LENGTH(s1);
9030 len2 = PyUnicode_GET_LENGTH(s2);
9031
Victor Stinner794d5672011-10-10 03:21:36 +02009032 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009033 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009034 case PyUnicode_1BYTE_KIND:
9035 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9036 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9037 else
9038 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9039 break;
9040 case PyUnicode_2BYTE_KIND:
9041 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9042 break;
9043 case PyUnicode_4BYTE_KIND:
9044 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9045 break;
9046 default:
9047 assert(0); result = -2;
9048 }
9049 }
9050 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009051 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009052 case PyUnicode_1BYTE_KIND:
9053 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9054 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9055 else
9056 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9057 break;
9058 case PyUnicode_2BYTE_KIND:
9059 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9060 break;
9061 case PyUnicode_4BYTE_KIND:
9062 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9063 break;
9064 default:
9065 assert(0); result = -2;
9066 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009067 }
9068
9069 if (kind1 != kind)
9070 PyMem_Free(buf1);
9071 if (kind2 != kind)
9072 PyMem_Free(buf2);
9073
9074 return result;
9075}
9076
9077Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009078_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009079 Py_ssize_t n_buffer,
9080 void *digits, Py_ssize_t n_digits,
9081 Py_ssize_t min_width,
9082 const char *grouping,
9083 const char *thousands_sep)
9084{
Benjamin Petersonead6b532011-12-20 17:23:42 -06009085 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009086 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009087 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9088 return _PyUnicode_ascii_InsertThousandsGrouping(
9089 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9090 min_width, grouping, thousands_sep);
9091 else
9092 return _PyUnicode_ucs1_InsertThousandsGrouping(
9093 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9094 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009095 case PyUnicode_2BYTE_KIND:
9096 return _PyUnicode_ucs2_InsertThousandsGrouping(
9097 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9098 min_width, grouping, thousands_sep);
9099 case PyUnicode_4BYTE_KIND:
9100 return _PyUnicode_ucs4_InsertThousandsGrouping(
9101 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9102 min_width, grouping, thousands_sep);
9103 }
9104 assert(0);
9105 return -1;
9106}
9107
9108
Thomas Wouters477c8d52006-05-27 19:21:47 +00009109/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009110#define ADJUST_INDICES(start, end, len) \
9111 if (end > len) \
9112 end = len; \
9113 else if (end < 0) { \
9114 end += len; \
9115 if (end < 0) \
9116 end = 0; \
9117 } \
9118 if (start < 0) { \
9119 start += len; \
9120 if (start < 0) \
9121 start = 0; \
9122 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009123
Alexander Belopolsky40018472011-02-26 01:02:56 +00009124Py_ssize_t
9125PyUnicode_Count(PyObject *str,
9126 PyObject *substr,
9127 Py_ssize_t start,
9128 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009129{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009130 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009131 PyObject* str_obj;
9132 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009133 int kind1, kind2, kind;
9134 void *buf1 = NULL, *buf2 = NULL;
9135 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009136
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009137 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009138 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009139 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009140 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009141 if (!sub_obj) {
9142 Py_DECREF(str_obj);
9143 return -1;
9144 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009145 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009146 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009147 Py_DECREF(str_obj);
9148 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009149 }
Tim Petersced69f82003-09-16 20:30:58 +00009150
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009151 kind1 = PyUnicode_KIND(str_obj);
9152 kind2 = PyUnicode_KIND(sub_obj);
9153 kind = kind1 > kind2 ? kind1 : kind2;
9154 buf1 = PyUnicode_DATA(str_obj);
9155 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009156 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009157 if (!buf1)
9158 goto onError;
9159 buf2 = PyUnicode_DATA(sub_obj);
9160 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009161 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009162 if (!buf2)
9163 goto onError;
9164 len1 = PyUnicode_GET_LENGTH(str_obj);
9165 len2 = PyUnicode_GET_LENGTH(sub_obj);
9166
9167 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009168 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009169 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009170 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9171 result = asciilib_count(
9172 ((Py_UCS1*)buf1) + start, end - start,
9173 buf2, len2, PY_SSIZE_T_MAX
9174 );
9175 else
9176 result = ucs1lib_count(
9177 ((Py_UCS1*)buf1) + start, end - start,
9178 buf2, len2, PY_SSIZE_T_MAX
9179 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009180 break;
9181 case PyUnicode_2BYTE_KIND:
9182 result = ucs2lib_count(
9183 ((Py_UCS2*)buf1) + start, end - start,
9184 buf2, len2, PY_SSIZE_T_MAX
9185 );
9186 break;
9187 case PyUnicode_4BYTE_KIND:
9188 result = ucs4lib_count(
9189 ((Py_UCS4*)buf1) + start, end - start,
9190 buf2, len2, PY_SSIZE_T_MAX
9191 );
9192 break;
9193 default:
9194 assert(0); result = 0;
9195 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009196
9197 Py_DECREF(sub_obj);
9198 Py_DECREF(str_obj);
9199
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009200 if (kind1 != kind)
9201 PyMem_Free(buf1);
9202 if (kind2 != kind)
9203 PyMem_Free(buf2);
9204
Guido van Rossumd57fd912000-03-10 22:53:23 +00009205 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009206 onError:
9207 Py_DECREF(sub_obj);
9208 Py_DECREF(str_obj);
9209 if (kind1 != kind && buf1)
9210 PyMem_Free(buf1);
9211 if (kind2 != kind && buf2)
9212 PyMem_Free(buf2);
9213 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009214}
9215
Alexander Belopolsky40018472011-02-26 01:02:56 +00009216Py_ssize_t
9217PyUnicode_Find(PyObject *str,
9218 PyObject *sub,
9219 Py_ssize_t start,
9220 Py_ssize_t end,
9221 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009222{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009223 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009224
Guido van Rossumd57fd912000-03-10 22:53:23 +00009225 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009226 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009227 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009228 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009229 if (!sub) {
9230 Py_DECREF(str);
9231 return -2;
9232 }
9233 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9234 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009235 Py_DECREF(str);
9236 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009237 }
Tim Petersced69f82003-09-16 20:30:58 +00009238
Victor Stinner794d5672011-10-10 03:21:36 +02009239 result = any_find_slice(direction,
9240 str, sub, start, end
9241 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009242
Guido van Rossumd57fd912000-03-10 22:53:23 +00009243 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009244 Py_DECREF(sub);
9245
Guido van Rossumd57fd912000-03-10 22:53:23 +00009246 return result;
9247}
9248
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009249Py_ssize_t
9250PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9251 Py_ssize_t start, Py_ssize_t end,
9252 int direction)
9253{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009254 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009255 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009256 if (PyUnicode_READY(str) == -1)
9257 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009258 if (start < 0 || end < 0) {
9259 PyErr_SetString(PyExc_IndexError, "string index out of range");
9260 return -2;
9261 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009262 if (end > PyUnicode_GET_LENGTH(str))
9263 end = PyUnicode_GET_LENGTH(str);
9264 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009265 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9266 kind, end-start, ch, direction);
9267 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009268 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009269 else
9270 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009271}
9272
Alexander Belopolsky40018472011-02-26 01:02:56 +00009273static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009274tailmatch(PyObject *self,
9275 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009276 Py_ssize_t start,
9277 Py_ssize_t end,
9278 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009279{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009280 int kind_self;
9281 int kind_sub;
9282 void *data_self;
9283 void *data_sub;
9284 Py_ssize_t offset;
9285 Py_ssize_t i;
9286 Py_ssize_t end_sub;
9287
9288 if (PyUnicode_READY(self) == -1 ||
9289 PyUnicode_READY(substring) == -1)
9290 return 0;
9291
9292 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009293 return 1;
9294
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009295 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9296 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009297 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009298 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009299
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009300 kind_self = PyUnicode_KIND(self);
9301 data_self = PyUnicode_DATA(self);
9302 kind_sub = PyUnicode_KIND(substring);
9303 data_sub = PyUnicode_DATA(substring);
9304 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9305
9306 if (direction > 0)
9307 offset = end;
9308 else
9309 offset = start;
9310
9311 if (PyUnicode_READ(kind_self, data_self, offset) ==
9312 PyUnicode_READ(kind_sub, data_sub, 0) &&
9313 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9314 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9315 /* If both are of the same kind, memcmp is sufficient */
9316 if (kind_self == kind_sub) {
9317 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009318 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009319 data_sub,
9320 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009321 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009322 }
9323 /* otherwise we have to compare each character by first accesing it */
9324 else {
9325 /* We do not need to compare 0 and len(substring)-1 because
9326 the if statement above ensured already that they are equal
9327 when we end up here. */
9328 // TODO: honor direction and do a forward or backwards search
9329 for (i = 1; i < end_sub; ++i) {
9330 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9331 PyUnicode_READ(kind_sub, data_sub, i))
9332 return 0;
9333 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009334 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009335 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009336 }
9337
9338 return 0;
9339}
9340
Alexander Belopolsky40018472011-02-26 01:02:56 +00009341Py_ssize_t
9342PyUnicode_Tailmatch(PyObject *str,
9343 PyObject *substr,
9344 Py_ssize_t start,
9345 Py_ssize_t end,
9346 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009347{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009348 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009349
Guido van Rossumd57fd912000-03-10 22:53:23 +00009350 str = PyUnicode_FromObject(str);
9351 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009352 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009353 substr = PyUnicode_FromObject(substr);
9354 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009355 Py_DECREF(str);
9356 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009357 }
Tim Petersced69f82003-09-16 20:30:58 +00009358
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009359 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009360 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009361 Py_DECREF(str);
9362 Py_DECREF(substr);
9363 return result;
9364}
9365
Guido van Rossumd57fd912000-03-10 22:53:23 +00009366/* Apply fixfct filter to the Unicode object self and return a
9367 reference to the modified object */
9368
Alexander Belopolsky40018472011-02-26 01:02:56 +00009369static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009370fixup(PyObject *self,
9371 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009372{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009373 PyObject *u;
9374 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009375 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009376
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009377 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009378 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009379 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009380 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009381
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009382 /* fix functions return the new maximum character in a string,
9383 if the kind of the resulting unicode object does not change,
9384 everything is fine. Otherwise we need to change the string kind
9385 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009386 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009387
9388 if (maxchar_new == 0) {
9389 /* no changes */;
9390 if (PyUnicode_CheckExact(self)) {
9391 Py_DECREF(u);
9392 Py_INCREF(self);
9393 return self;
9394 }
9395 else
9396 return u;
9397 }
9398
9399 if (maxchar_new <= 127)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009400 maxchar_new = 127;
9401 else if (maxchar_new <= 255)
9402 maxchar_new = 255;
9403 else if (maxchar_new <= 65535)
9404 maxchar_new = 65535;
9405 else
Victor Stinner8faf8212011-12-08 22:14:11 +01009406 maxchar_new = MAX_UNICODE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009407
Victor Stinnereaab6042011-12-11 22:22:39 +01009408 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009409 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009410
9411 /* In case the maximum character changed, we need to
9412 convert the string to the new category. */
9413 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9414 if (v == NULL) {
9415 Py_DECREF(u);
9416 return NULL;
9417 }
9418 if (maxchar_new > maxchar_old) {
9419 /* If the maxchar increased so that the kind changed, not all
9420 characters are representable anymore and we need to fix the
9421 string again. This only happens in very few cases. */
9422 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
9423 maxchar_old = fixfct(v);
9424 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009425 }
9426 else {
Victor Stinnereaab6042011-12-11 22:22:39 +01009427 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009428 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009429 Py_DECREF(u);
9430 assert(_PyUnicode_CheckConsistency(v, 1));
9431 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009432}
9433
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009434static PyObject *
9435ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009436{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009437 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9438 char *resdata, *data = PyUnicode_DATA(self);
9439 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009440
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009441 res = PyUnicode_New(len, 127);
9442 if (res == NULL)
9443 return NULL;
9444 resdata = PyUnicode_DATA(res);
9445 if (lower)
9446 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009447 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009448 _Py_bytes_upper(resdata, data, len);
9449 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009450}
9451
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009452static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009453handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009454{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009455 Py_ssize_t j;
9456 int final_sigma;
9457 Py_UCS4 c;
9458 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009459
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009460 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9461
9462 where ! is a negation and \p{xxx} is a character with property xxx.
9463 */
9464 for (j = i - 1; j >= 0; j--) {
9465 c = PyUnicode_READ(kind, data, j);
9466 if (!_PyUnicode_IsCaseIgnorable(c))
9467 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009468 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009469 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9470 if (final_sigma) {
9471 for (j = i + 1; j < length; j++) {
9472 c = PyUnicode_READ(kind, data, j);
9473 if (!_PyUnicode_IsCaseIgnorable(c))
9474 break;
9475 }
9476 final_sigma = j == length || !_PyUnicode_IsCased(c);
9477 }
9478 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009479}
9480
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009481static int
9482lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9483 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009484{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009485 /* Obscure special case. */
9486 if (c == 0x3A3) {
9487 mapped[0] = handle_capital_sigma(kind, data, length, i);
9488 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009489 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009490 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009491}
9492
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009493static Py_ssize_t
9494do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009495{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009496 Py_ssize_t i, k = 0;
9497 int n_res, j;
9498 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009499
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009500 c = PyUnicode_READ(kind, data, 0);
9501 n_res = _PyUnicode_ToUpperFull(c, mapped);
9502 for (j = 0; j < n_res; j++) {
9503 if (mapped[j] > *maxchar)
9504 *maxchar = mapped[j];
9505 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009506 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009507 for (i = 1; i < length; i++) {
9508 c = PyUnicode_READ(kind, data, i);
9509 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9510 for (j = 0; j < n_res; j++) {
9511 if (mapped[j] > *maxchar)
9512 *maxchar = mapped[j];
9513 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009514 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009515 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009516 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009517}
9518
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009519static Py_ssize_t
9520do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9521 Py_ssize_t i, k = 0;
9522
9523 for (i = 0; i < length; i++) {
9524 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9525 int n_res, j;
9526 if (Py_UNICODE_ISUPPER(c)) {
9527 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9528 }
9529 else if (Py_UNICODE_ISLOWER(c)) {
9530 n_res = _PyUnicode_ToUpperFull(c, mapped);
9531 }
9532 else {
9533 n_res = 1;
9534 mapped[0] = c;
9535 }
9536 for (j = 0; j < n_res; j++) {
9537 if (mapped[j] > *maxchar)
9538 *maxchar = mapped[j];
9539 res[k++] = mapped[j];
9540 }
9541 }
9542 return k;
9543}
9544
9545static Py_ssize_t
9546do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9547 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009548{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009549 Py_ssize_t i, k = 0;
9550
9551 for (i = 0; i < length; i++) {
9552 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9553 int n_res, j;
9554 if (lower)
9555 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9556 else
9557 n_res = _PyUnicode_ToUpperFull(c, mapped);
9558 for (j = 0; j < n_res; j++) {
9559 if (mapped[j] > *maxchar)
9560 *maxchar = mapped[j];
9561 res[k++] = mapped[j];
9562 }
9563 }
9564 return k;
9565}
9566
9567static Py_ssize_t
9568do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9569{
9570 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9571}
9572
9573static Py_ssize_t
9574do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9575{
9576 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9577}
9578
Benjamin Petersone51757f2012-01-12 21:10:29 -05009579static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009580do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9581{
9582 Py_ssize_t i, k = 0;
9583
9584 for (i = 0; i < length; i++) {
9585 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9586 Py_UCS4 mapped[3];
9587 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9588 for (j = 0; j < n_res; j++) {
9589 if (mapped[j] > *maxchar)
9590 *maxchar = mapped[j];
9591 res[k++] = mapped[j];
9592 }
9593 }
9594 return k;
9595}
9596
9597static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009598do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9599{
9600 Py_ssize_t i, k = 0;
9601 int previous_is_cased;
9602
9603 previous_is_cased = 0;
9604 for (i = 0; i < length; i++) {
9605 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9606 Py_UCS4 mapped[3];
9607 int n_res, j;
9608
9609 if (previous_is_cased)
9610 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9611 else
9612 n_res = _PyUnicode_ToTitleFull(c, mapped);
9613
9614 for (j = 0; j < n_res; j++) {
9615 if (mapped[j] > *maxchar)
9616 *maxchar = mapped[j];
9617 res[k++] = mapped[j];
9618 }
9619
9620 previous_is_cased = _PyUnicode_IsCased(c);
9621 }
9622 return k;
9623}
9624
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009625static PyObject *
9626case_operation(PyObject *self,
9627 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9628{
9629 PyObject *res = NULL;
9630 Py_ssize_t length, newlength = 0;
9631 int kind, outkind;
9632 void *data, *outdata;
9633 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9634
9635 if (PyUnicode_READY(self) == -1)
9636 return NULL;
9637
9638 kind = PyUnicode_KIND(self);
9639 data = PyUnicode_DATA(self);
9640 length = PyUnicode_GET_LENGTH(self);
9641 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9642 if (tmp == NULL)
9643 return PyErr_NoMemory();
9644 newlength = perform(kind, data, length, tmp, &maxchar);
9645 res = PyUnicode_New(newlength, maxchar);
9646 if (res == NULL)
9647 goto leave;
9648 tmpend = tmp + newlength;
9649 outdata = PyUnicode_DATA(res);
9650 outkind = PyUnicode_KIND(res);
9651 switch (outkind) {
9652 case PyUnicode_1BYTE_KIND:
9653 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9654 break;
9655 case PyUnicode_2BYTE_KIND:
9656 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9657 break;
9658 case PyUnicode_4BYTE_KIND:
9659 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9660 break;
9661 default:
9662 assert(0);
9663 break;
9664 }
9665 leave:
9666 PyMem_FREE(tmp);
9667 return res;
9668}
9669
Tim Peters8ce9f162004-08-27 01:49:32 +00009670PyObject *
9671PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009672{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009673 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009674 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009675 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009676 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009677 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9678 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009679 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009680 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009681 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009682 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009683 int use_memcpy;
9684 unsigned char *res_data = NULL, *sep_data = NULL;
9685 PyObject *last_obj;
9686 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009687
Tim Peters05eba1f2004-08-27 21:32:02 +00009688 fseq = PySequence_Fast(seq, "");
9689 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009690 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009691 }
9692
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009693 /* NOTE: the following code can't call back into Python code,
9694 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009695 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009696
Tim Peters05eba1f2004-08-27 21:32:02 +00009697 seqlen = PySequence_Fast_GET_SIZE(fseq);
9698 /* If empty sequence, return u"". */
9699 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009700 Py_DECREF(fseq);
9701 Py_INCREF(unicode_empty);
9702 res = unicode_empty;
9703 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009704 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009705
Tim Peters05eba1f2004-08-27 21:32:02 +00009706 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009707 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009708 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009709 if (seqlen == 1) {
9710 if (PyUnicode_CheckExact(items[0])) {
9711 res = items[0];
9712 Py_INCREF(res);
9713 Py_DECREF(fseq);
9714 return res;
9715 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009716 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009717 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009718 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009719 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009720 /* Set up sep and seplen */
9721 if (separator == NULL) {
9722 /* fall back to a blank space separator */
9723 sep = PyUnicode_FromOrdinal(' ');
9724 if (!sep)
9725 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009726 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009727 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009728 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009729 else {
9730 if (!PyUnicode_Check(separator)) {
9731 PyErr_Format(PyExc_TypeError,
9732 "separator: expected str instance,"
9733 " %.80s found",
9734 Py_TYPE(separator)->tp_name);
9735 goto onError;
9736 }
9737 if (PyUnicode_READY(separator))
9738 goto onError;
9739 sep = separator;
9740 seplen = PyUnicode_GET_LENGTH(separator);
9741 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9742 /* inc refcount to keep this code path symmetric with the
9743 above case of a blank separator */
9744 Py_INCREF(sep);
9745 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009746 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009747 }
9748
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009749 /* There are at least two things to join, or else we have a subclass
9750 * of str in the sequence.
9751 * Do a pre-pass to figure out the total amount of space we'll
9752 * need (sz), and see whether all argument are strings.
9753 */
9754 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009755#ifdef Py_DEBUG
9756 use_memcpy = 0;
9757#else
9758 use_memcpy = 1;
9759#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009760 for (i = 0; i < seqlen; i++) {
9761 const Py_ssize_t old_sz = sz;
9762 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009763 if (!PyUnicode_Check(item)) {
9764 PyErr_Format(PyExc_TypeError,
9765 "sequence item %zd: expected str instance,"
9766 " %.80s found",
9767 i, Py_TYPE(item)->tp_name);
9768 goto onError;
9769 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009770 if (PyUnicode_READY(item) == -1)
9771 goto onError;
9772 sz += PyUnicode_GET_LENGTH(item);
9773 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009774 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009775 if (i != 0)
9776 sz += seplen;
9777 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9778 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009779 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009780 goto onError;
9781 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009782 if (use_memcpy && last_obj != NULL) {
9783 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9784 use_memcpy = 0;
9785 }
9786 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009787 }
Tim Petersced69f82003-09-16 20:30:58 +00009788
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009789 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009790 if (res == NULL)
9791 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009792
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009793 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009794#ifdef Py_DEBUG
9795 use_memcpy = 0;
9796#else
9797 if (use_memcpy) {
9798 res_data = PyUnicode_1BYTE_DATA(res);
9799 kind = PyUnicode_KIND(res);
9800 if (seplen != 0)
9801 sep_data = PyUnicode_1BYTE_DATA(sep);
9802 }
9803#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009804 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009805 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009806 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009807 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009808 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009809 if (use_memcpy) {
9810 Py_MEMCPY(res_data,
9811 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009812 kind * seplen);
9813 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009814 }
9815 else {
9816 copy_characters(res, res_offset, sep, 0, seplen);
9817 res_offset += seplen;
9818 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009819 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009820 itemlen = PyUnicode_GET_LENGTH(item);
9821 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009822 if (use_memcpy) {
9823 Py_MEMCPY(res_data,
9824 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009825 kind * itemlen);
9826 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009827 }
9828 else {
9829 copy_characters(res, res_offset, item, 0, itemlen);
9830 res_offset += itemlen;
9831 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009832 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009833 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009834 if (use_memcpy)
9835 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009836 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009837 else
9838 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009839
Tim Peters05eba1f2004-08-27 21:32:02 +00009840 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009841 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009842 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009843 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009844
Benjamin Peterson29060642009-01-31 22:14:21 +00009845 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009846 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009847 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009848 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009849 return NULL;
9850}
9851
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009852#define FILL(kind, data, value, start, length) \
9853 do { \
9854 Py_ssize_t i_ = 0; \
9855 assert(kind != PyUnicode_WCHAR_KIND); \
9856 switch ((kind)) { \
9857 case PyUnicode_1BYTE_KIND: { \
9858 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9859 memset(to_, (unsigned char)value, length); \
9860 break; \
9861 } \
9862 case PyUnicode_2BYTE_KIND: { \
9863 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9864 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9865 break; \
9866 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009867 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009868 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9869 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9870 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009871 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009872 } \
9873 } \
9874 } while (0)
9875
Victor Stinner3fe55312012-01-04 00:33:50 +01009876Py_ssize_t
9877PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9878 Py_UCS4 fill_char)
9879{
9880 Py_ssize_t maxlen;
9881 enum PyUnicode_Kind kind;
9882 void *data;
9883
9884 if (!PyUnicode_Check(unicode)) {
9885 PyErr_BadInternalCall();
9886 return -1;
9887 }
9888 if (PyUnicode_READY(unicode) == -1)
9889 return -1;
9890 if (unicode_check_modifiable(unicode))
9891 return -1;
9892
9893 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9894 PyErr_SetString(PyExc_ValueError,
9895 "fill character is bigger than "
9896 "the string maximum character");
9897 return -1;
9898 }
9899
9900 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9901 length = Py_MIN(maxlen, length);
9902 if (length <= 0)
9903 return 0;
9904
9905 kind = PyUnicode_KIND(unicode);
9906 data = PyUnicode_DATA(unicode);
9907 FILL(kind, data, fill_char, start, length);
9908 return length;
9909}
9910
Victor Stinner9310abb2011-10-05 00:59:23 +02009911static PyObject *
9912pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009913 Py_ssize_t left,
9914 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009915 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009916{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009917 PyObject *u;
9918 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009919 int kind;
9920 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009921
9922 if (left < 0)
9923 left = 0;
9924 if (right < 0)
9925 right = 0;
9926
Victor Stinnerc4b49542011-12-11 22:44:26 +01009927 if (left == 0 && right == 0)
9928 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009929
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009930 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9931 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009932 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9933 return NULL;
9934 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009935 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9936 if (fill > maxchar)
9937 maxchar = fill;
9938 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009939 if (!u)
9940 return NULL;
9941
9942 kind = PyUnicode_KIND(u);
9943 data = PyUnicode_DATA(u);
9944 if (left)
9945 FILL(kind, data, fill, 0, left);
9946 if (right)
9947 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009948 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009949 assert(_PyUnicode_CheckConsistency(u, 1));
9950 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009951}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009952#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009953
Alexander Belopolsky40018472011-02-26 01:02:56 +00009954PyObject *
9955PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009956{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009957 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009958
9959 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009960 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009961 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009962 if (PyUnicode_READY(string) == -1) {
9963 Py_DECREF(string);
9964 return NULL;
9965 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009966
Benjamin Petersonead6b532011-12-20 17:23:42 -06009967 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009968 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009969 if (PyUnicode_IS_ASCII(string))
9970 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009971 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009972 PyUnicode_GET_LENGTH(string), keepends);
9973 else
9974 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009975 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009976 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009977 break;
9978 case PyUnicode_2BYTE_KIND:
9979 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009980 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009981 PyUnicode_GET_LENGTH(string), keepends);
9982 break;
9983 case PyUnicode_4BYTE_KIND:
9984 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009985 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009986 PyUnicode_GET_LENGTH(string), keepends);
9987 break;
9988 default:
9989 assert(0);
9990 list = 0;
9991 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009992 Py_DECREF(string);
9993 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009994}
9995
Alexander Belopolsky40018472011-02-26 01:02:56 +00009996static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009997split(PyObject *self,
9998 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009999 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010000{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010001 int kind1, kind2, kind;
10002 void *buf1, *buf2;
10003 Py_ssize_t len1, len2;
10004 PyObject* out;
10005
Guido van Rossumd57fd912000-03-10 22:53:23 +000010006 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010007 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010008
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010009 if (PyUnicode_READY(self) == -1)
10010 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010011
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010012 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010013 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010014 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010015 if (PyUnicode_IS_ASCII(self))
10016 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010017 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010018 PyUnicode_GET_LENGTH(self), maxcount
10019 );
10020 else
10021 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010022 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010023 PyUnicode_GET_LENGTH(self), maxcount
10024 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010025 case PyUnicode_2BYTE_KIND:
10026 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010027 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010028 PyUnicode_GET_LENGTH(self), maxcount
10029 );
10030 case PyUnicode_4BYTE_KIND:
10031 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010032 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010033 PyUnicode_GET_LENGTH(self), maxcount
10034 );
10035 default:
10036 assert(0);
10037 return NULL;
10038 }
10039
10040 if (PyUnicode_READY(substring) == -1)
10041 return NULL;
10042
10043 kind1 = PyUnicode_KIND(self);
10044 kind2 = PyUnicode_KIND(substring);
10045 kind = kind1 > kind2 ? kind1 : kind2;
10046 buf1 = PyUnicode_DATA(self);
10047 buf2 = PyUnicode_DATA(substring);
10048 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010049 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010050 if (!buf1)
10051 return NULL;
10052 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010053 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010054 if (!buf2) {
10055 if (kind1 != kind) PyMem_Free(buf1);
10056 return NULL;
10057 }
10058 len1 = PyUnicode_GET_LENGTH(self);
10059 len2 = PyUnicode_GET_LENGTH(substring);
10060
Benjamin Petersonead6b532011-12-20 17:23:42 -060010061 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010062 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010063 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10064 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010065 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010066 else
10067 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010068 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010069 break;
10070 case PyUnicode_2BYTE_KIND:
10071 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010072 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010073 break;
10074 case PyUnicode_4BYTE_KIND:
10075 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010076 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010077 break;
10078 default:
10079 out = NULL;
10080 }
10081 if (kind1 != kind)
10082 PyMem_Free(buf1);
10083 if (kind2 != kind)
10084 PyMem_Free(buf2);
10085 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010086}
10087
Alexander Belopolsky40018472011-02-26 01:02:56 +000010088static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010089rsplit(PyObject *self,
10090 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010091 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010092{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010093 int kind1, kind2, kind;
10094 void *buf1, *buf2;
10095 Py_ssize_t len1, len2;
10096 PyObject* out;
10097
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010098 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010099 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010100
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010101 if (PyUnicode_READY(self) == -1)
10102 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010104 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010105 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010106 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010107 if (PyUnicode_IS_ASCII(self))
10108 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010109 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010110 PyUnicode_GET_LENGTH(self), maxcount
10111 );
10112 else
10113 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010114 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010115 PyUnicode_GET_LENGTH(self), maxcount
10116 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010117 case PyUnicode_2BYTE_KIND:
10118 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010119 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010120 PyUnicode_GET_LENGTH(self), maxcount
10121 );
10122 case PyUnicode_4BYTE_KIND:
10123 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010124 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010125 PyUnicode_GET_LENGTH(self), maxcount
10126 );
10127 default:
10128 assert(0);
10129 return NULL;
10130 }
10131
10132 if (PyUnicode_READY(substring) == -1)
10133 return NULL;
10134
10135 kind1 = PyUnicode_KIND(self);
10136 kind2 = PyUnicode_KIND(substring);
10137 kind = kind1 > kind2 ? kind1 : kind2;
10138 buf1 = PyUnicode_DATA(self);
10139 buf2 = PyUnicode_DATA(substring);
10140 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010141 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010142 if (!buf1)
10143 return NULL;
10144 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010145 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010146 if (!buf2) {
10147 if (kind1 != kind) PyMem_Free(buf1);
10148 return NULL;
10149 }
10150 len1 = PyUnicode_GET_LENGTH(self);
10151 len2 = PyUnicode_GET_LENGTH(substring);
10152
Benjamin Petersonead6b532011-12-20 17:23:42 -060010153 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010155 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10156 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010157 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010158 else
10159 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010160 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010161 break;
10162 case PyUnicode_2BYTE_KIND:
10163 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010164 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010165 break;
10166 case PyUnicode_4BYTE_KIND:
10167 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010168 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010169 break;
10170 default:
10171 out = NULL;
10172 }
10173 if (kind1 != kind)
10174 PyMem_Free(buf1);
10175 if (kind2 != kind)
10176 PyMem_Free(buf2);
10177 return out;
10178}
10179
10180static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010181anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10182 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010184 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010185 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010186 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10187 return asciilib_find(buf1, len1, buf2, len2, offset);
10188 else
10189 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 case PyUnicode_2BYTE_KIND:
10191 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10192 case PyUnicode_4BYTE_KIND:
10193 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10194 }
10195 assert(0);
10196 return -1;
10197}
10198
10199static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010200anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10201 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010202{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010203 switch (kind) {
10204 case PyUnicode_1BYTE_KIND:
10205 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10206 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10207 else
10208 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10209 case PyUnicode_2BYTE_KIND:
10210 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10211 case PyUnicode_4BYTE_KIND:
10212 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10213 }
10214 assert(0);
10215 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010216}
10217
Alexander Belopolsky40018472011-02-26 01:02:56 +000010218static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010219replace(PyObject *self, PyObject *str1,
10220 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010221{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010222 PyObject *u;
10223 char *sbuf = PyUnicode_DATA(self);
10224 char *buf1 = PyUnicode_DATA(str1);
10225 char *buf2 = PyUnicode_DATA(str2);
10226 int srelease = 0, release1 = 0, release2 = 0;
10227 int skind = PyUnicode_KIND(self);
10228 int kind1 = PyUnicode_KIND(str1);
10229 int kind2 = PyUnicode_KIND(str2);
10230 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10231 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10232 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010233 int mayshrink;
10234 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010235
10236 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010237 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010238 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010239 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010240
Victor Stinner59de0ee2011-10-07 10:01:28 +020010241 if (str1 == str2)
10242 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243 if (skind < kind1)
10244 /* substring too wide to be present */
10245 goto nothing;
10246
Victor Stinner49a0a212011-10-12 23:46:10 +020010247 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10248 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10249 /* Replacing str1 with str2 may cause a maxchar reduction in the
10250 result string. */
10251 mayshrink = (maxchar_str2 < maxchar);
10252 maxchar = Py_MAX(maxchar, maxchar_str2);
10253
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010254 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010255 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010256 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010257 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010258 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010259 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010260 Py_UCS4 u1, u2;
10261 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010262 Py_ssize_t index, pos;
10263 char *src;
10264
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010265 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010266 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10267 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010268 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010271 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010272 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010273 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010274 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010275
10276 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10277 index = 0;
10278 src = sbuf;
10279 while (--maxcount)
10280 {
10281 pos++;
10282 src += pos * PyUnicode_KIND(self);
10283 slen -= pos;
10284 index += pos;
10285 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10286 if (pos < 0)
10287 break;
10288 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10289 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010290 }
10291 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292 int rkind = skind;
10293 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010294 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010295
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010296 if (kind1 < rkind) {
10297 /* widen substring */
10298 buf1 = _PyUnicode_AsKind(str1, rkind);
10299 if (!buf1) goto error;
10300 release1 = 1;
10301 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010302 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010303 if (i < 0)
10304 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 if (rkind > kind2) {
10306 /* widen replacement */
10307 buf2 = _PyUnicode_AsKind(str2, rkind);
10308 if (!buf2) goto error;
10309 release2 = 1;
10310 }
10311 else if (rkind < kind2) {
10312 /* widen self and buf1 */
10313 rkind = kind2;
10314 if (release1) PyMem_Free(buf1);
10315 sbuf = _PyUnicode_AsKind(self, rkind);
10316 if (!sbuf) goto error;
10317 srelease = 1;
10318 buf1 = _PyUnicode_AsKind(str1, rkind);
10319 if (!buf1) goto error;
10320 release1 = 1;
10321 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010322 u = PyUnicode_New(slen, maxchar);
10323 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010324 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010325 assert(PyUnicode_KIND(u) == rkind);
10326 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010327
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010328 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010329 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010330 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010331 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010332 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010333 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010334
10335 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010336 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010337 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010338 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010339 if (i == -1)
10340 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010341 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010343 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010344 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010345 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010346 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010347 }
10348 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010349 Py_ssize_t n, i, j, ires;
10350 Py_ssize_t product, new_size;
10351 int rkind = skind;
10352 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010353
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010354 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010355 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010356 buf1 = _PyUnicode_AsKind(str1, rkind);
10357 if (!buf1) goto error;
10358 release1 = 1;
10359 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010360 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010361 if (n == 0)
10362 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010364 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010365 buf2 = _PyUnicode_AsKind(str2, rkind);
10366 if (!buf2) goto error;
10367 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010368 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010369 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010370 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010371 rkind = kind2;
10372 sbuf = _PyUnicode_AsKind(self, rkind);
10373 if (!sbuf) goto error;
10374 srelease = 1;
10375 if (release1) PyMem_Free(buf1);
10376 buf1 = _PyUnicode_AsKind(str1, rkind);
10377 if (!buf1) goto error;
10378 release1 = 1;
10379 }
10380 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10381 PyUnicode_GET_LENGTH(str1))); */
10382 product = n * (len2-len1);
10383 if ((product / (len2-len1)) != n) {
10384 PyErr_SetString(PyExc_OverflowError,
10385 "replace string is too long");
10386 goto error;
10387 }
10388 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010389 if (new_size == 0) {
10390 Py_INCREF(unicode_empty);
10391 u = unicode_empty;
10392 goto done;
10393 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010394 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10395 PyErr_SetString(PyExc_OverflowError,
10396 "replace string is too long");
10397 goto error;
10398 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010399 u = PyUnicode_New(new_size, maxchar);
10400 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010401 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010402 assert(PyUnicode_KIND(u) == rkind);
10403 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010404 ires = i = 0;
10405 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010406 while (n-- > 0) {
10407 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010408 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010409 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010410 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010411 if (j == -1)
10412 break;
10413 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010414 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010415 memcpy(res + rkind * ires,
10416 sbuf + rkind * i,
10417 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010418 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010419 }
10420 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010422 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010423 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010424 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010425 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010426 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010427 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010428 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010429 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010430 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010431 memcpy(res + rkind * ires,
10432 sbuf + rkind * i,
10433 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010434 }
10435 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010436 /* interleave */
10437 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010438 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010440 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010441 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010442 if (--n <= 0)
10443 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010444 memcpy(res + rkind * ires,
10445 sbuf + rkind * i,
10446 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010447 ires++;
10448 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010449 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010450 memcpy(res + rkind * ires,
10451 sbuf + rkind * i,
10452 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010453 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010454 }
10455
10456 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010457 unicode_adjust_maxchar(&u);
10458 if (u == NULL)
10459 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010460 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010461
10462 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010463 if (srelease)
10464 PyMem_FREE(sbuf);
10465 if (release1)
10466 PyMem_FREE(buf1);
10467 if (release2)
10468 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010469 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010471
Benjamin Peterson29060642009-01-31 22:14:21 +000010472 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010473 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010474 if (srelease)
10475 PyMem_FREE(sbuf);
10476 if (release1)
10477 PyMem_FREE(buf1);
10478 if (release2)
10479 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010480 return unicode_result_unchanged(self);
10481
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010482 error:
10483 if (srelease && sbuf)
10484 PyMem_FREE(sbuf);
10485 if (release1 && buf1)
10486 PyMem_FREE(buf1);
10487 if (release2 && buf2)
10488 PyMem_FREE(buf2);
10489 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010490}
10491
10492/* --- Unicode Object Methods --------------------------------------------- */
10493
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010494PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010495 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010496\n\
10497Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010498characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010499
10500static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010501unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010502{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010503 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010504}
10505
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010506PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010507 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010508\n\
10509Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010510have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010511
10512static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010513unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010514{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010515 if (PyUnicode_READY(self) == -1)
10516 return NULL;
10517 if (PyUnicode_GET_LENGTH(self) == 0)
10518 return unicode_result_unchanged(self);
10519 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010520}
10521
Benjamin Petersond5890c82012-01-14 13:23:30 -050010522PyDoc_STRVAR(casefold__doc__,
10523 "S.casefold() -> str\n\
10524\n\
10525Return a version of S suitable for caseless comparisons.");
10526
10527static PyObject *
10528unicode_casefold(PyObject *self)
10529{
10530 if (PyUnicode_READY(self) == -1)
10531 return NULL;
10532 if (PyUnicode_IS_ASCII(self))
10533 return ascii_upper_or_lower(self, 1);
10534 return case_operation(self, do_casefold);
10535}
10536
10537
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010538/* Argument converter. Coerces to a single unicode character */
10539
10540static int
10541convert_uc(PyObject *obj, void *addr)
10542{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010543 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010544 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010545
Benjamin Peterson14339b62009-01-31 16:36:08 +000010546 uniobj = PyUnicode_FromObject(obj);
10547 if (uniobj == NULL) {
10548 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010549 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010550 return 0;
10551 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010552 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010553 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010554 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010555 Py_DECREF(uniobj);
10556 return 0;
10557 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010558 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010559 Py_DECREF(uniobj);
10560 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010561}
10562
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010563PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010564 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010565\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010566Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010567done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010568
10569static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010570unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010571{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010572 Py_ssize_t marg, left;
10573 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010574 Py_UCS4 fillchar = ' ';
10575
Victor Stinnere9a29352011-10-01 02:14:59 +020010576 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010578
Victor Stinnerc4b49542011-12-11 22:44:26 +010010579 if (PyUnicode_READY(self) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010580 return NULL;
10581
Victor Stinnerc4b49542011-12-11 22:44:26 +010010582 if (PyUnicode_GET_LENGTH(self) >= width)
10583 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010584
Victor Stinnerc4b49542011-12-11 22:44:26 +010010585 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010586 left = marg / 2 + (marg & width & 1);
10587
Victor Stinner9310abb2011-10-05 00:59:23 +020010588 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010589}
10590
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010591/* This function assumes that str1 and str2 are readied by the caller. */
10592
Marc-André Lemburge5034372000-08-08 08:04:29 +000010593static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010594unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010595{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010596 int kind1, kind2;
10597 void *data1, *data2;
10598 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010599
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010600 kind1 = PyUnicode_KIND(str1);
10601 kind2 = PyUnicode_KIND(str2);
10602 data1 = PyUnicode_DATA(str1);
10603 data2 = PyUnicode_DATA(str2);
10604 len1 = PyUnicode_GET_LENGTH(str1);
10605 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010606
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010607 for (i = 0; i < len1 && i < len2; ++i) {
10608 Py_UCS4 c1, c2;
10609 c1 = PyUnicode_READ(kind1, data1, i);
10610 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010611
10612 if (c1 != c2)
10613 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010614 }
10615
10616 return (len1 < len2) ? -1 : (len1 != len2);
10617}
10618
Alexander Belopolsky40018472011-02-26 01:02:56 +000010619int
10620PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010621{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010622 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10623 if (PyUnicode_READY(left) == -1 ||
10624 PyUnicode_READY(right) == -1)
10625 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010626 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010627 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010628 PyErr_Format(PyExc_TypeError,
10629 "Can't compare %.100s and %.100s",
10630 left->ob_type->tp_name,
10631 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010632 return -1;
10633}
10634
Martin v. Löwis5b222132007-06-10 09:51:05 +000010635int
10636PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10637{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010638 Py_ssize_t i;
10639 int kind;
10640 void *data;
10641 Py_UCS4 chr;
10642
Victor Stinner910337b2011-10-03 03:20:16 +020010643 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010644 if (PyUnicode_READY(uni) == -1)
10645 return -1;
10646 kind = PyUnicode_KIND(uni);
10647 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010648 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010649 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10650 if (chr != str[i])
10651 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010652 /* This check keeps Python strings that end in '\0' from comparing equal
10653 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010654 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010655 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010656 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010657 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010658 return 0;
10659}
10660
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010661
Benjamin Peterson29060642009-01-31 22:14:21 +000010662#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010663 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010664
Alexander Belopolsky40018472011-02-26 01:02:56 +000010665PyObject *
10666PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010667{
10668 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010669
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010670 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10671 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010672 if (PyUnicode_READY(left) == -1 ||
10673 PyUnicode_READY(right) == -1)
10674 return NULL;
10675 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10676 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010677 if (op == Py_EQ) {
10678 Py_INCREF(Py_False);
10679 return Py_False;
10680 }
10681 if (op == Py_NE) {
10682 Py_INCREF(Py_True);
10683 return Py_True;
10684 }
10685 }
10686 if (left == right)
10687 result = 0;
10688 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010689 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010690
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010691 /* Convert the return value to a Boolean */
10692 switch (op) {
10693 case Py_EQ:
10694 v = TEST_COND(result == 0);
10695 break;
10696 case Py_NE:
10697 v = TEST_COND(result != 0);
10698 break;
10699 case Py_LE:
10700 v = TEST_COND(result <= 0);
10701 break;
10702 case Py_GE:
10703 v = TEST_COND(result >= 0);
10704 break;
10705 case Py_LT:
10706 v = TEST_COND(result == -1);
10707 break;
10708 case Py_GT:
10709 v = TEST_COND(result == 1);
10710 break;
10711 default:
10712 PyErr_BadArgument();
10713 return NULL;
10714 }
10715 Py_INCREF(v);
10716 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010717 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010718
Brian Curtindfc80e32011-08-10 20:28:54 -050010719 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010720}
10721
Alexander Belopolsky40018472011-02-26 01:02:56 +000010722int
10723PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010724{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010725 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010726 int kind1, kind2, kind;
10727 void *buf1, *buf2;
10728 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010729 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010730
10731 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010732 sub = PyUnicode_FromObject(element);
10733 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010734 PyErr_Format(PyExc_TypeError,
10735 "'in <string>' requires string as left operand, not %s",
10736 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010737 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010738 }
10739
Thomas Wouters477c8d52006-05-27 19:21:47 +000010740 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010741 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010742 Py_DECREF(sub);
10743 return -1;
10744 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010745 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10746 Py_DECREF(sub);
10747 Py_DECREF(str);
10748 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010749
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010750 kind1 = PyUnicode_KIND(str);
10751 kind2 = PyUnicode_KIND(sub);
10752 kind = kind1 > kind2 ? kind1 : kind2;
10753 buf1 = PyUnicode_DATA(str);
10754 buf2 = PyUnicode_DATA(sub);
10755 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010756 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010757 if (!buf1) {
10758 Py_DECREF(sub);
10759 return -1;
10760 }
10761 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010762 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010763 if (!buf2) {
10764 Py_DECREF(sub);
10765 if (kind1 != kind) PyMem_Free(buf1);
10766 return -1;
10767 }
10768 len1 = PyUnicode_GET_LENGTH(str);
10769 len2 = PyUnicode_GET_LENGTH(sub);
10770
Benjamin Petersonead6b532011-12-20 17:23:42 -060010771 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010772 case PyUnicode_1BYTE_KIND:
10773 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10774 break;
10775 case PyUnicode_2BYTE_KIND:
10776 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10777 break;
10778 case PyUnicode_4BYTE_KIND:
10779 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10780 break;
10781 default:
10782 result = -1;
10783 assert(0);
10784 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010785
10786 Py_DECREF(str);
10787 Py_DECREF(sub);
10788
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010789 if (kind1 != kind)
10790 PyMem_Free(buf1);
10791 if (kind2 != kind)
10792 PyMem_Free(buf2);
10793
Guido van Rossum403d68b2000-03-13 15:55:09 +000010794 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010795}
10796
Guido van Rossumd57fd912000-03-10 22:53:23 +000010797/* Concat to string or Unicode object giving a new Unicode object. */
10798
Alexander Belopolsky40018472011-02-26 01:02:56 +000010799PyObject *
10800PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010801{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010802 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010803 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010804 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010805
10806 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010807 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010808 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010809 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010810 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010811 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010812 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010813
10814 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010815 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010816 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010817 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010818 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010819 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010820 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010821 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010822 }
10823
Victor Stinner488fa492011-12-12 00:01:39 +010010824 u_len = PyUnicode_GET_LENGTH(u);
10825 v_len = PyUnicode_GET_LENGTH(v);
10826 if (u_len > PY_SSIZE_T_MAX - v_len) {
10827 PyErr_SetString(PyExc_OverflowError,
10828 "strings are too large to concat");
10829 goto onError;
10830 }
10831 new_len = u_len + v_len;
10832
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010833 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010834 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10835 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010836
Guido van Rossumd57fd912000-03-10 22:53:23 +000010837 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010838 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010839 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010840 goto onError;
Victor Stinner488fa492011-12-12 00:01:39 +010010841 copy_characters(w, 0, u, 0, u_len);
10842 copy_characters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010843 Py_DECREF(u);
10844 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010845 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010846 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010847
Benjamin Peterson29060642009-01-31 22:14:21 +000010848 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010849 Py_XDECREF(u);
10850 Py_XDECREF(v);
10851 return NULL;
10852}
10853
Walter Dörwald1ab83302007-05-18 17:15:44 +000010854void
Victor Stinner23e56682011-10-03 03:54:37 +020010855PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010856{
Victor Stinner23e56682011-10-03 03:54:37 +020010857 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010858 Py_UCS4 maxchar, maxchar2;
10859 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010860
10861 if (p_left == NULL) {
10862 if (!PyErr_Occurred())
10863 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010864 return;
10865 }
Victor Stinner23e56682011-10-03 03:54:37 +020010866 left = *p_left;
10867 if (right == NULL || !PyUnicode_Check(left)) {
10868 if (!PyErr_Occurred())
10869 PyErr_BadInternalCall();
10870 goto error;
10871 }
10872
Victor Stinnere1335c72011-10-04 20:53:03 +020010873 if (PyUnicode_READY(left))
10874 goto error;
10875 if (PyUnicode_READY(right))
10876 goto error;
10877
Victor Stinner488fa492011-12-12 00:01:39 +010010878 /* Shortcuts */
10879 if (left == unicode_empty) {
10880 Py_DECREF(left);
10881 Py_INCREF(right);
10882 *p_left = right;
10883 return;
10884 }
10885 if (right == unicode_empty)
10886 return;
10887
10888 left_len = PyUnicode_GET_LENGTH(left);
10889 right_len = PyUnicode_GET_LENGTH(right);
10890 if (left_len > PY_SSIZE_T_MAX - right_len) {
10891 PyErr_SetString(PyExc_OverflowError,
10892 "strings are too large to concat");
10893 goto error;
10894 }
10895 new_len = left_len + right_len;
10896
10897 if (unicode_modifiable(left)
10898 && PyUnicode_CheckExact(right)
10899 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010900 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10901 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010902 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010903 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010904 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10905 {
10906 /* append inplace */
10907 if (unicode_resize(p_left, new_len) != 0) {
10908 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10909 * deallocated so it cannot be put back into
10910 * 'variable'. The MemoryError is raised when there
10911 * is no value in 'variable', which might (very
10912 * remotely) be a cause of incompatibilities.
10913 */
10914 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010915 }
Victor Stinner488fa492011-12-12 00:01:39 +010010916 /* copy 'right' into the newly allocated area of 'left' */
10917 copy_characters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010918 }
Victor Stinner488fa492011-12-12 00:01:39 +010010919 else {
10920 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10921 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
10922 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010923
Victor Stinner488fa492011-12-12 00:01:39 +010010924 /* Concat the two Unicode strings */
10925 res = PyUnicode_New(new_len, maxchar);
10926 if (res == NULL)
10927 goto error;
10928 copy_characters(res, 0, left, 0, left_len);
10929 copy_characters(res, left_len, right, 0, right_len);
10930 Py_DECREF(left);
10931 *p_left = res;
10932 }
10933 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010934 return;
10935
10936error:
Victor Stinner488fa492011-12-12 00:01:39 +010010937 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010938}
10939
10940void
10941PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10942{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010943 PyUnicode_Append(pleft, right);
10944 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010945}
10946
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010947PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010948 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010949\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010950Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010951string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010952interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010953
10954static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010955unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010956{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010957 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010958 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010959 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010960 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010961 int kind1, kind2, kind;
10962 void *buf1, *buf2;
10963 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010964
Jesus Ceaac451502011-04-20 17:09:23 +020010965 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10966 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010967 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010969 kind1 = PyUnicode_KIND(self);
10970 kind2 = PyUnicode_KIND(substring);
10971 kind = kind1 > kind2 ? kind1 : kind2;
10972 buf1 = PyUnicode_DATA(self);
10973 buf2 = PyUnicode_DATA(substring);
10974 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010975 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010976 if (!buf1) {
10977 Py_DECREF(substring);
10978 return NULL;
10979 }
10980 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010981 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010982 if (!buf2) {
10983 Py_DECREF(substring);
10984 if (kind1 != kind) PyMem_Free(buf1);
10985 return NULL;
10986 }
10987 len1 = PyUnicode_GET_LENGTH(self);
10988 len2 = PyUnicode_GET_LENGTH(substring);
10989
10990 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010991 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010992 case PyUnicode_1BYTE_KIND:
10993 iresult = ucs1lib_count(
10994 ((Py_UCS1*)buf1) + start, end - start,
10995 buf2, len2, PY_SSIZE_T_MAX
10996 );
10997 break;
10998 case PyUnicode_2BYTE_KIND:
10999 iresult = ucs2lib_count(
11000 ((Py_UCS2*)buf1) + start, end - start,
11001 buf2, len2, PY_SSIZE_T_MAX
11002 );
11003 break;
11004 case PyUnicode_4BYTE_KIND:
11005 iresult = ucs4lib_count(
11006 ((Py_UCS4*)buf1) + start, end - start,
11007 buf2, len2, PY_SSIZE_T_MAX
11008 );
11009 break;
11010 default:
11011 assert(0); iresult = 0;
11012 }
11013
11014 result = PyLong_FromSsize_t(iresult);
11015
11016 if (kind1 != kind)
11017 PyMem_Free(buf1);
11018 if (kind2 != kind)
11019 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011020
11021 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011022
Guido van Rossumd57fd912000-03-10 22:53:23 +000011023 return result;
11024}
11025
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011026PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011027 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011028\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011029Encode S using the codec registered for encoding. Default encoding\n\
11030is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011031handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011032a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11033'xmlcharrefreplace' as well as any other name registered with\n\
11034codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011035
11036static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011037unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011038{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011039 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011040 char *encoding = NULL;
11041 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011042
Benjamin Peterson308d6372009-09-18 21:42:35 +000011043 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11044 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011045 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011046 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011047}
11048
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011049PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011050 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011051\n\
11052Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011053If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011054
11055static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011056unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011057{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011058 Py_ssize_t i, j, line_pos, src_len, incr;
11059 Py_UCS4 ch;
11060 PyObject *u;
11061 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011062 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011063 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011064 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011065
11066 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011067 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011068
Antoine Pitrou22425222011-10-04 19:10:51 +020011069 if (PyUnicode_READY(self) == -1)
11070 return NULL;
11071
Thomas Wouters7e474022000-07-16 12:04:32 +000011072 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011073 src_len = PyUnicode_GET_LENGTH(self);
11074 i = j = line_pos = 0;
11075 kind = PyUnicode_KIND(self);
11076 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011077 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011078 for (; i < src_len; i++) {
11079 ch = PyUnicode_READ(kind, src_data, i);
11080 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011081 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011082 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011083 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011084 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011085 goto overflow;
11086 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011087 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011088 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011089 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011090 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011091 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011092 goto overflow;
11093 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011094 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011095 if (ch == '\n' || ch == '\r')
11096 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011097 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011098 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011099 if (!found)
11100 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011101
Guido van Rossumd57fd912000-03-10 22:53:23 +000011102 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011103 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011104 if (!u)
11105 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011106 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011107
Antoine Pitroue71d5742011-10-04 15:55:09 +020011108 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011109
Antoine Pitroue71d5742011-10-04 15:55:09 +020011110 for (; i < src_len; i++) {
11111 ch = PyUnicode_READ(kind, src_data, i);
11112 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011113 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011114 incr = tabsize - (line_pos % tabsize);
11115 line_pos += incr;
11116 while (incr--) {
11117 PyUnicode_WRITE(kind, dest_data, j, ' ');
11118 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011119 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011120 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011121 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011122 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011123 line_pos++;
11124 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011125 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011126 if (ch == '\n' || ch == '\r')
11127 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011128 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011129 }
11130 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011131 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011132
Antoine Pitroue71d5742011-10-04 15:55:09 +020011133 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011134 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11135 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011136}
11137
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011138PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011139 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011140\n\
11141Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011142such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011143arguments start and end are interpreted as in slice notation.\n\
11144\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011145Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011146
11147static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011148unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011149{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011150 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011151 Py_ssize_t start;
11152 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011153 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011154
Jesus Ceaac451502011-04-20 17:09:23 +020011155 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11156 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011157 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011158
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011159 if (PyUnicode_READY(self) == -1)
11160 return NULL;
11161 if (PyUnicode_READY(substring) == -1)
11162 return NULL;
11163
Victor Stinner7931d9a2011-11-04 00:22:48 +010011164 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011165
11166 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011167
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011168 if (result == -2)
11169 return NULL;
11170
Christian Heimes217cfd12007-12-02 14:31:20 +000011171 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011172}
11173
11174static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011175unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011176{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011177 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11178 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011179 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011180 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011181}
11182
Guido van Rossumc2504932007-09-18 19:42:40 +000011183/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011184 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011185static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011186unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011187{
Guido van Rossumc2504932007-09-18 19:42:40 +000011188 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011189 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011190
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011191 if (_PyUnicode_HASH(self) != -1)
11192 return _PyUnicode_HASH(self);
11193 if (PyUnicode_READY(self) == -1)
11194 return -1;
11195 len = PyUnicode_GET_LENGTH(self);
11196
11197 /* The hash function as a macro, gets expanded three times below. */
11198#define HASH(P) \
11199 x = (Py_uhash_t)*P << 7; \
11200 while (--len >= 0) \
11201 x = (1000003*x) ^ (Py_uhash_t)*P++;
11202
11203 switch (PyUnicode_KIND(self)) {
11204 case PyUnicode_1BYTE_KIND: {
11205 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11206 HASH(c);
11207 break;
11208 }
11209 case PyUnicode_2BYTE_KIND: {
11210 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11211 HASH(s);
11212 break;
11213 }
11214 default: {
11215 Py_UCS4 *l;
11216 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11217 "Impossible switch case in unicode_hash");
11218 l = PyUnicode_4BYTE_DATA(self);
11219 HASH(l);
11220 break;
11221 }
11222 }
11223 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11224
Guido van Rossumc2504932007-09-18 19:42:40 +000011225 if (x == -1)
11226 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011227 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011228 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011229}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011230#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011231
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011232PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011233 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011234\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011235Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236
11237static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011238unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011239{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011240 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011241 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011242 Py_ssize_t start;
11243 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011244
Jesus Ceaac451502011-04-20 17:09:23 +020011245 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11246 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011247 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011248
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011249 if (PyUnicode_READY(self) == -1)
11250 return NULL;
11251 if (PyUnicode_READY(substring) == -1)
11252 return NULL;
11253
Victor Stinner7931d9a2011-11-04 00:22:48 +010011254 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011255
11256 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011257
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011258 if (result == -2)
11259 return NULL;
11260
Guido van Rossumd57fd912000-03-10 22:53:23 +000011261 if (result < 0) {
11262 PyErr_SetString(PyExc_ValueError, "substring not found");
11263 return NULL;
11264 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011265
Christian Heimes217cfd12007-12-02 14:31:20 +000011266 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011267}
11268
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011269PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011270 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011271\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011272Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011273at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011274
11275static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011276unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011277{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011278 Py_ssize_t i, length;
11279 int kind;
11280 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011281 int cased;
11282
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011283 if (PyUnicode_READY(self) == -1)
11284 return NULL;
11285 length = PyUnicode_GET_LENGTH(self);
11286 kind = PyUnicode_KIND(self);
11287 data = PyUnicode_DATA(self);
11288
Guido van Rossumd57fd912000-03-10 22:53:23 +000011289 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011290 if (length == 1)
11291 return PyBool_FromLong(
11292 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011293
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011294 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011295 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011296 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011297
Guido van Rossumd57fd912000-03-10 22:53:23 +000011298 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011299 for (i = 0; i < length; i++) {
11300 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011301
Benjamin Peterson29060642009-01-31 22:14:21 +000011302 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11303 return PyBool_FromLong(0);
11304 else if (!cased && Py_UNICODE_ISLOWER(ch))
11305 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011306 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011307 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011308}
11309
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011310PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011311 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011312\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011313Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011314at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011315
11316static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011317unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011318{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011319 Py_ssize_t i, length;
11320 int kind;
11321 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011322 int cased;
11323
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011324 if (PyUnicode_READY(self) == -1)
11325 return NULL;
11326 length = PyUnicode_GET_LENGTH(self);
11327 kind = PyUnicode_KIND(self);
11328 data = PyUnicode_DATA(self);
11329
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011331 if (length == 1)
11332 return PyBool_FromLong(
11333 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011334
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011335 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011336 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011337 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011338
Guido van Rossumd57fd912000-03-10 22:53:23 +000011339 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011340 for (i = 0; i < length; i++) {
11341 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011342
Benjamin Peterson29060642009-01-31 22:14:21 +000011343 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11344 return PyBool_FromLong(0);
11345 else if (!cased && Py_UNICODE_ISUPPER(ch))
11346 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011347 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011348 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011349}
11350
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011351PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011352 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011353\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011354Return True if S is a titlecased string and there is at least one\n\
11355character in S, i.e. upper- and titlecase characters may only\n\
11356follow uncased characters and lowercase characters only cased ones.\n\
11357Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011358
11359static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011360unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011361{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011362 Py_ssize_t i, length;
11363 int kind;
11364 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011365 int cased, previous_is_cased;
11366
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011367 if (PyUnicode_READY(self) == -1)
11368 return NULL;
11369 length = PyUnicode_GET_LENGTH(self);
11370 kind = PyUnicode_KIND(self);
11371 data = PyUnicode_DATA(self);
11372
Guido van Rossumd57fd912000-03-10 22:53:23 +000011373 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011374 if (length == 1) {
11375 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11376 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11377 (Py_UNICODE_ISUPPER(ch) != 0));
11378 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011379
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011380 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011381 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011382 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011383
Guido van Rossumd57fd912000-03-10 22:53:23 +000011384 cased = 0;
11385 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011386 for (i = 0; i < length; i++) {
11387 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011388
Benjamin Peterson29060642009-01-31 22:14:21 +000011389 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11390 if (previous_is_cased)
11391 return PyBool_FromLong(0);
11392 previous_is_cased = 1;
11393 cased = 1;
11394 }
11395 else if (Py_UNICODE_ISLOWER(ch)) {
11396 if (!previous_is_cased)
11397 return PyBool_FromLong(0);
11398 previous_is_cased = 1;
11399 cased = 1;
11400 }
11401 else
11402 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011403 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011404 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011405}
11406
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011407PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011408 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011410Return True if all characters in S are whitespace\n\
11411and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011412
11413static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011414unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011416 Py_ssize_t i, length;
11417 int kind;
11418 void *data;
11419
11420 if (PyUnicode_READY(self) == -1)
11421 return NULL;
11422 length = PyUnicode_GET_LENGTH(self);
11423 kind = PyUnicode_KIND(self);
11424 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011425
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011427 if (length == 1)
11428 return PyBool_FromLong(
11429 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011430
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011431 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011432 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011433 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011434
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011435 for (i = 0; i < length; i++) {
11436 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011437 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011438 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011440 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011441}
11442
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011443PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011444 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011445\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011446Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011447and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011448
11449static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011450unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011451{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011452 Py_ssize_t i, length;
11453 int kind;
11454 void *data;
11455
11456 if (PyUnicode_READY(self) == -1)
11457 return NULL;
11458 length = PyUnicode_GET_LENGTH(self);
11459 kind = PyUnicode_KIND(self);
11460 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011461
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011462 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011463 if (length == 1)
11464 return PyBool_FromLong(
11465 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011466
11467 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011468 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011469 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011470
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011471 for (i = 0; i < length; i++) {
11472 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011473 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011474 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011475 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011476}
11477
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011478PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011479 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011480\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011481Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011482and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011483
11484static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011485unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011486{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011487 int kind;
11488 void *data;
11489 Py_ssize_t len, i;
11490
11491 if (PyUnicode_READY(self) == -1)
11492 return NULL;
11493
11494 kind = PyUnicode_KIND(self);
11495 data = PyUnicode_DATA(self);
11496 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011497
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011498 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011499 if (len == 1) {
11500 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11501 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11502 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011503
11504 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011505 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011506 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011507
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011508 for (i = 0; i < len; i++) {
11509 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011510 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011511 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011512 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011513 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011514}
11515
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011516PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011517 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011518\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011519Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011520False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521
11522static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011523unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011525 Py_ssize_t i, length;
11526 int kind;
11527 void *data;
11528
11529 if (PyUnicode_READY(self) == -1)
11530 return NULL;
11531 length = PyUnicode_GET_LENGTH(self);
11532 kind = PyUnicode_KIND(self);
11533 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011534
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011536 if (length == 1)
11537 return PyBool_FromLong(
11538 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011539
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011540 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011541 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011542 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011544 for (i = 0; i < length; i++) {
11545 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011546 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011548 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549}
11550
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011551PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011552 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011554Return True if all characters in S are digits\n\
11555and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011556
11557static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011558unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011559{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011560 Py_ssize_t i, length;
11561 int kind;
11562 void *data;
11563
11564 if (PyUnicode_READY(self) == -1)
11565 return NULL;
11566 length = PyUnicode_GET_LENGTH(self);
11567 kind = PyUnicode_KIND(self);
11568 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011571 if (length == 1) {
11572 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11573 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11574 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011575
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011576 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011577 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011578 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011579
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011580 for (i = 0; i < length; i++) {
11581 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011582 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011583 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011584 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585}
11586
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011587PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011588 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011590Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011591False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011592
11593static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011594unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011596 Py_ssize_t i, length;
11597 int kind;
11598 void *data;
11599
11600 if (PyUnicode_READY(self) == -1)
11601 return NULL;
11602 length = PyUnicode_GET_LENGTH(self);
11603 kind = PyUnicode_KIND(self);
11604 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011605
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011607 if (length == 1)
11608 return PyBool_FromLong(
11609 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011611 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011612 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011613 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011614
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011615 for (i = 0; i < length; i++) {
11616 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011617 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011618 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011619 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011620}
11621
Martin v. Löwis47383402007-08-15 07:32:56 +000011622int
11623PyUnicode_IsIdentifier(PyObject *self)
11624{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011625 int kind;
11626 void *data;
11627 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011628 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011629
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011630 if (PyUnicode_READY(self) == -1) {
11631 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011632 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011633 }
11634
11635 /* Special case for empty strings */
11636 if (PyUnicode_GET_LENGTH(self) == 0)
11637 return 0;
11638 kind = PyUnicode_KIND(self);
11639 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011640
11641 /* PEP 3131 says that the first character must be in
11642 XID_Start and subsequent characters in XID_Continue,
11643 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011644 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011645 letters, digits, underscore). However, given the current
11646 definition of XID_Start and XID_Continue, it is sufficient
11647 to check just for these, except that _ must be allowed
11648 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011649 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011650 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011651 return 0;
11652
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011653 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011654 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011655 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011656 return 1;
11657}
11658
11659PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011660 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011661\n\
11662Return True if S is a valid identifier according\n\
11663to the language definition.");
11664
11665static PyObject*
11666unicode_isidentifier(PyObject *self)
11667{
11668 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11669}
11670
Georg Brandl559e5d72008-06-11 18:37:52 +000011671PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011672 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011673\n\
11674Return True if all characters in S are considered\n\
11675printable in repr() or S is empty, False otherwise.");
11676
11677static PyObject*
11678unicode_isprintable(PyObject *self)
11679{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011680 Py_ssize_t i, length;
11681 int kind;
11682 void *data;
11683
11684 if (PyUnicode_READY(self) == -1)
11685 return NULL;
11686 length = PyUnicode_GET_LENGTH(self);
11687 kind = PyUnicode_KIND(self);
11688 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011689
11690 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011691 if (length == 1)
11692 return PyBool_FromLong(
11693 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011694
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011695 for (i = 0; i < length; i++) {
11696 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011697 Py_RETURN_FALSE;
11698 }
11699 }
11700 Py_RETURN_TRUE;
11701}
11702
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011703PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011704 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011705\n\
11706Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011707iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011708
11709static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011710unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011711{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011712 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011713}
11714
Martin v. Löwis18e16552006-02-15 17:27:45 +000011715static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011716unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011717{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011718 if (PyUnicode_READY(self) == -1)
11719 return -1;
11720 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721}
11722
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011723PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011724 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011725\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011726Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011727done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011728
11729static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011730unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011731{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011732 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011733 Py_UCS4 fillchar = ' ';
11734
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011735 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011736 return NULL;
11737
Victor Stinnerc4b49542011-12-11 22:44:26 +010011738 if (PyUnicode_READY(self) < 0)
11739 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011740
Victor Stinnerc4b49542011-12-11 22:44:26 +010011741 if (PyUnicode_GET_LENGTH(self) >= width)
11742 return unicode_result_unchanged(self);
11743
11744 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011745}
11746
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011747PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011748 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011749\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011750Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011751
11752static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011753unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011754{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011755 if (PyUnicode_READY(self) == -1)
11756 return NULL;
11757 if (PyUnicode_IS_ASCII(self))
11758 return ascii_upper_or_lower(self, 1);
11759 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011760}
11761
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011762#define LEFTSTRIP 0
11763#define RIGHTSTRIP 1
11764#define BOTHSTRIP 2
11765
11766/* Arrays indexed by above */
11767static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11768
11769#define STRIPNAME(i) (stripformat[i]+3)
11770
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011771/* externally visible for str.strip(unicode) */
11772PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011773_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011774{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011775 void *data;
11776 int kind;
11777 Py_ssize_t i, j, len;
11778 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011779
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011780 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11781 return NULL;
11782
11783 kind = PyUnicode_KIND(self);
11784 data = PyUnicode_DATA(self);
11785 len = PyUnicode_GET_LENGTH(self);
11786 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11787 PyUnicode_DATA(sepobj),
11788 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011789
Benjamin Peterson14339b62009-01-31 16:36:08 +000011790 i = 0;
11791 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011792 while (i < len &&
11793 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011794 i++;
11795 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011796 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011797
Benjamin Peterson14339b62009-01-31 16:36:08 +000011798 j = len;
11799 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011800 do {
11801 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011802 } while (j >= i &&
11803 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011804 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011805 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011806
Victor Stinner7931d9a2011-11-04 00:22:48 +010011807 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011808}
11809
11810PyObject*
11811PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11812{
11813 unsigned char *data;
11814 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011815 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011816
Victor Stinnerde636f32011-10-01 03:55:54 +020011817 if (PyUnicode_READY(self) == -1)
11818 return NULL;
11819
11820 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11821
Victor Stinner12bab6d2011-10-01 01:53:49 +020011822 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Victor Stinnerc4b49542011-12-11 22:44:26 +010011823 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011824
Victor Stinner12bab6d2011-10-01 01:53:49 +020011825 length = end - start;
11826 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011827 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011828
Victor Stinnerde636f32011-10-01 03:55:54 +020011829 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011830 PyErr_SetString(PyExc_IndexError, "string index out of range");
11831 return NULL;
11832 }
11833
Victor Stinnerb9275c12011-10-05 14:01:42 +020011834 if (PyUnicode_IS_ASCII(self)) {
11835 kind = PyUnicode_KIND(self);
11836 data = PyUnicode_1BYTE_DATA(self);
11837 return unicode_fromascii(data + start, length);
11838 }
11839 else {
11840 kind = PyUnicode_KIND(self);
11841 data = PyUnicode_1BYTE_DATA(self);
11842 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011843 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011844 length);
11845 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011846}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011847
11848static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011849do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011850{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011851 int kind;
11852 void *data;
11853 Py_ssize_t len, i, j;
11854
11855 if (PyUnicode_READY(self) == -1)
11856 return NULL;
11857
11858 kind = PyUnicode_KIND(self);
11859 data = PyUnicode_DATA(self);
11860 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011861
Benjamin Peterson14339b62009-01-31 16:36:08 +000011862 i = 0;
11863 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011864 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011865 i++;
11866 }
11867 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011868
Benjamin Peterson14339b62009-01-31 16:36:08 +000011869 j = len;
11870 if (striptype != LEFTSTRIP) {
11871 do {
11872 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011873 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011874 j++;
11875 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011876
Victor Stinner7931d9a2011-11-04 00:22:48 +010011877 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011878}
11879
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011880
11881static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011882do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011883{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011884 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011885
Benjamin Peterson14339b62009-01-31 16:36:08 +000011886 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11887 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011888
Benjamin Peterson14339b62009-01-31 16:36:08 +000011889 if (sep != NULL && sep != Py_None) {
11890 if (PyUnicode_Check(sep))
11891 return _PyUnicode_XStrip(self, striptype, sep);
11892 else {
11893 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011894 "%s arg must be None or str",
11895 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011896 return NULL;
11897 }
11898 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011899
Benjamin Peterson14339b62009-01-31 16:36:08 +000011900 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011901}
11902
11903
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011904PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011905 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011906\n\
11907Return a copy of the string S with leading and trailing\n\
11908whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011909If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011910
11911static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011912unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011913{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011914 if (PyTuple_GET_SIZE(args) == 0)
11915 return do_strip(self, BOTHSTRIP); /* Common case */
11916 else
11917 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011918}
11919
11920
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011921PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011922 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011923\n\
11924Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011925If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011926
11927static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011928unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011929{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011930 if (PyTuple_GET_SIZE(args) == 0)
11931 return do_strip(self, LEFTSTRIP); /* Common case */
11932 else
11933 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011934}
11935
11936
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011937PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011938 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011939\n\
11940Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011941If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011942
11943static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011944unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011945{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011946 if (PyTuple_GET_SIZE(args) == 0)
11947 return do_strip(self, RIGHTSTRIP); /* Common case */
11948 else
11949 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011950}
11951
11952
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011954unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011955{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011956 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011957 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011958
Georg Brandl222de0f2009-04-12 12:01:50 +000011959 if (len < 1) {
11960 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011961 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011962 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011963
Victor Stinnerc4b49542011-12-11 22:44:26 +010011964 /* no repeat, return original string */
11965 if (len == 1)
11966 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011967
Victor Stinnerc4b49542011-12-11 22:44:26 +010011968 if (PyUnicode_READY(str) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011969 return NULL;
11970
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011971 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011972 PyErr_SetString(PyExc_OverflowError,
11973 "repeated string is too long");
11974 return NULL;
11975 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011976 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011977
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011978 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011979 if (!u)
11980 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011981 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011983 if (PyUnicode_GET_LENGTH(str) == 1) {
11984 const int kind = PyUnicode_KIND(str);
11985 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011986 if (kind == PyUnicode_1BYTE_KIND) {
11987 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011988 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011989 }
11990 else if (kind == PyUnicode_2BYTE_KIND) {
11991 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011992 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011993 ucs2[n] = fill_char;
11994 } else {
11995 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11996 assert(kind == PyUnicode_4BYTE_KIND);
11997 for (n = 0; n < len; ++n)
11998 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011999 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012000 }
12001 else {
12002 /* number of characters copied this far */
12003 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012004 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012005 char *to = (char *) PyUnicode_DATA(u);
12006 Py_MEMCPY(to, PyUnicode_DATA(str),
12007 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012008 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012009 n = (done <= nchars-done) ? done : nchars-done;
12010 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012011 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012012 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012013 }
12014
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012015 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012016 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012017}
12018
Alexander Belopolsky40018472011-02-26 01:02:56 +000012019PyObject *
12020PyUnicode_Replace(PyObject *obj,
12021 PyObject *subobj,
12022 PyObject *replobj,
12023 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012024{
12025 PyObject *self;
12026 PyObject *str1;
12027 PyObject *str2;
12028 PyObject *result;
12029
12030 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012031 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012032 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012033 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012034 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012035 Py_DECREF(self);
12036 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012037 }
12038 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012039 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012040 Py_DECREF(self);
12041 Py_DECREF(str1);
12042 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012043 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012044 if (PyUnicode_READY(self) == -1 ||
12045 PyUnicode_READY(str1) == -1 ||
12046 PyUnicode_READY(str2) == -1)
12047 result = NULL;
12048 else
12049 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012050 Py_DECREF(self);
12051 Py_DECREF(str1);
12052 Py_DECREF(str2);
12053 return result;
12054}
12055
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012056PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012057 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012058\n\
12059Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012060old replaced by new. If the optional argument count is\n\
12061given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012062
12063static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012064unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012065{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012066 PyObject *str1;
12067 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012068 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012069 PyObject *result;
12070
Martin v. Löwis18e16552006-02-15 17:27:45 +000012071 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012072 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012073 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012074 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012075 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012076 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012077 return NULL;
12078 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012079 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012080 Py_DECREF(str1);
12081 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012082 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012083 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12084 result = NULL;
12085 else
12086 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012087
12088 Py_DECREF(str1);
12089 Py_DECREF(str2);
12090 return result;
12091}
12092
Alexander Belopolsky40018472011-02-26 01:02:56 +000012093static PyObject *
12094unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012095{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012096 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012097 Py_ssize_t isize;
12098 Py_ssize_t osize, squote, dquote, i, o;
12099 Py_UCS4 max, quote;
12100 int ikind, okind;
12101 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012102
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012103 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012104 return NULL;
12105
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012106 isize = PyUnicode_GET_LENGTH(unicode);
12107 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012108
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012109 /* Compute length of output, quote characters, and
12110 maximum character */
12111 osize = 2; /* quotes */
12112 max = 127;
12113 squote = dquote = 0;
12114 ikind = PyUnicode_KIND(unicode);
12115 for (i = 0; i < isize; i++) {
12116 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12117 switch (ch) {
12118 case '\'': squote++; osize++; break;
12119 case '"': dquote++; osize++; break;
12120 case '\\': case '\t': case '\r': case '\n':
12121 osize += 2; break;
12122 default:
12123 /* Fast-path ASCII */
12124 if (ch < ' ' || ch == 0x7f)
12125 osize += 4; /* \xHH */
12126 else if (ch < 0x7f)
12127 osize++;
12128 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12129 osize++;
12130 max = ch > max ? ch : max;
12131 }
12132 else if (ch < 0x100)
12133 osize += 4; /* \xHH */
12134 else if (ch < 0x10000)
12135 osize += 6; /* \uHHHH */
12136 else
12137 osize += 10; /* \uHHHHHHHH */
12138 }
12139 }
12140
12141 quote = '\'';
12142 if (squote) {
12143 if (dquote)
12144 /* Both squote and dquote present. Use squote,
12145 and escape them */
12146 osize += squote;
12147 else
12148 quote = '"';
12149 }
12150
12151 repr = PyUnicode_New(osize, max);
12152 if (repr == NULL)
12153 return NULL;
12154 okind = PyUnicode_KIND(repr);
12155 odata = PyUnicode_DATA(repr);
12156
12157 PyUnicode_WRITE(okind, odata, 0, quote);
12158 PyUnicode_WRITE(okind, odata, osize-1, quote);
12159
12160 for (i = 0, o = 1; i < isize; i++) {
12161 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012162
12163 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012164 if ((ch == quote) || (ch == '\\')) {
12165 PyUnicode_WRITE(okind, odata, o++, '\\');
12166 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012167 continue;
12168 }
12169
Benjamin Peterson29060642009-01-31 22:14:21 +000012170 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012171 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012172 PyUnicode_WRITE(okind, odata, o++, '\\');
12173 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012174 }
12175 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012176 PyUnicode_WRITE(okind, odata, o++, '\\');
12177 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012178 }
12179 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012180 PyUnicode_WRITE(okind, odata, o++, '\\');
12181 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012182 }
12183
12184 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012185 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012186 PyUnicode_WRITE(okind, odata, o++, '\\');
12187 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012188 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12189 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012190 }
12191
Georg Brandl559e5d72008-06-11 18:37:52 +000012192 /* Copy ASCII characters as-is */
12193 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012194 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012195 }
12196
Benjamin Peterson29060642009-01-31 22:14:21 +000012197 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012198 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012199 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012200 (categories Z* and C* except ASCII space)
12201 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012202 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012203 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012204 if (ch <= 0xff) {
12205 PyUnicode_WRITE(okind, odata, o++, '\\');
12206 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012207 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12208 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012209 }
12210 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012211 else if (ch >= 0x10000) {
12212 PyUnicode_WRITE(okind, odata, o++, '\\');
12213 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012214 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12215 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12216 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12217 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12218 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12219 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12220 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12221 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012222 }
12223 /* Map 16-bit characters to '\uxxxx' */
12224 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012225 PyUnicode_WRITE(okind, odata, o++, '\\');
12226 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012227 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12228 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12229 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12230 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012231 }
12232 }
12233 /* Copy characters as-is */
12234 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012235 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012236 }
12237 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012238 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012239 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012240 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012241 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012242}
12243
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012244PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012245 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012246\n\
12247Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012248such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012249arguments start and end are interpreted as in slice notation.\n\
12250\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012251Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012252
12253static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012254unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012255{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012256 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012257 Py_ssize_t start;
12258 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012259 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012260
Jesus Ceaac451502011-04-20 17:09:23 +020012261 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12262 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012263 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012264
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012265 if (PyUnicode_READY(self) == -1)
12266 return NULL;
12267 if (PyUnicode_READY(substring) == -1)
12268 return NULL;
12269
Victor Stinner7931d9a2011-11-04 00:22:48 +010012270 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012271
12272 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012273
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012274 if (result == -2)
12275 return NULL;
12276
Christian Heimes217cfd12007-12-02 14:31:20 +000012277 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012278}
12279
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012280PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012281 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012282\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012283Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012284
12285static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012286unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012287{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012288 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012289 Py_ssize_t start;
12290 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012291 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012292
Jesus Ceaac451502011-04-20 17:09:23 +020012293 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12294 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012295 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012296
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012297 if (PyUnicode_READY(self) == -1)
12298 return NULL;
12299 if (PyUnicode_READY(substring) == -1)
12300 return NULL;
12301
Victor Stinner7931d9a2011-11-04 00:22:48 +010012302 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012303
12304 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012305
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012306 if (result == -2)
12307 return NULL;
12308
Guido van Rossumd57fd912000-03-10 22:53:23 +000012309 if (result < 0) {
12310 PyErr_SetString(PyExc_ValueError, "substring not found");
12311 return NULL;
12312 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012313
Christian Heimes217cfd12007-12-02 14:31:20 +000012314 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012315}
12316
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012317PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012318 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012319\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012320Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012321done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012322
12323static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012324unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012325{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012326 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012327 Py_UCS4 fillchar = ' ';
12328
Victor Stinnere9a29352011-10-01 02:14:59 +020012329 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012330 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012331
Victor Stinnerc4b49542011-12-11 22:44:26 +010012332 if (PyUnicode_READY(self) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012333 return NULL;
12334
Victor Stinnerc4b49542011-12-11 22:44:26 +010012335 if (PyUnicode_GET_LENGTH(self) >= width)
12336 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012337
Victor Stinnerc4b49542011-12-11 22:44:26 +010012338 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012339}
12340
Alexander Belopolsky40018472011-02-26 01:02:56 +000012341PyObject *
12342PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012343{
12344 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012345
Guido van Rossumd57fd912000-03-10 22:53:23 +000012346 s = PyUnicode_FromObject(s);
12347 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012348 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012349 if (sep != NULL) {
12350 sep = PyUnicode_FromObject(sep);
12351 if (sep == NULL) {
12352 Py_DECREF(s);
12353 return NULL;
12354 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012355 }
12356
Victor Stinner9310abb2011-10-05 00:59:23 +020012357 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012358
12359 Py_DECREF(s);
12360 Py_XDECREF(sep);
12361 return result;
12362}
12363
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012364PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012365 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012366\n\
12367Return a list of the words in S, using sep as the\n\
12368delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012369splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012370whitespace string is a separator and empty strings are\n\
12371removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012372
12373static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012374unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012375{
12376 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012377 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012378
Martin v. Löwis18e16552006-02-15 17:27:45 +000012379 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012380 return NULL;
12381
12382 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012383 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012384 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012385 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012386 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012387 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012388}
12389
Thomas Wouters477c8d52006-05-27 19:21:47 +000012390PyObject *
12391PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12392{
12393 PyObject* str_obj;
12394 PyObject* sep_obj;
12395 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012396 int kind1, kind2, kind;
12397 void *buf1 = NULL, *buf2 = NULL;
12398 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012399
12400 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012401 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012402 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012403 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012404 if (!sep_obj) {
12405 Py_DECREF(str_obj);
12406 return NULL;
12407 }
12408 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12409 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012410 Py_DECREF(str_obj);
12411 return NULL;
12412 }
12413
Victor Stinner14f8f022011-10-05 20:58:25 +020012414 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012415 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012416 kind = Py_MAX(kind1, kind2);
12417 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012418 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012419 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012420 if (!buf1)
12421 goto onError;
12422 buf2 = PyUnicode_DATA(sep_obj);
12423 if (kind2 != kind)
12424 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12425 if (!buf2)
12426 goto onError;
12427 len1 = PyUnicode_GET_LENGTH(str_obj);
12428 len2 = PyUnicode_GET_LENGTH(sep_obj);
12429
Benjamin Petersonead6b532011-12-20 17:23:42 -060012430 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012431 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012432 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12433 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12434 else
12435 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012436 break;
12437 case PyUnicode_2BYTE_KIND:
12438 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12439 break;
12440 case PyUnicode_4BYTE_KIND:
12441 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12442 break;
12443 default:
12444 assert(0);
12445 out = 0;
12446 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012447
12448 Py_DECREF(sep_obj);
12449 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012450 if (kind1 != kind)
12451 PyMem_Free(buf1);
12452 if (kind2 != kind)
12453 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012454
12455 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012456 onError:
12457 Py_DECREF(sep_obj);
12458 Py_DECREF(str_obj);
12459 if (kind1 != kind && buf1)
12460 PyMem_Free(buf1);
12461 if (kind2 != kind && buf2)
12462 PyMem_Free(buf2);
12463 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012464}
12465
12466
12467PyObject *
12468PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12469{
12470 PyObject* str_obj;
12471 PyObject* sep_obj;
12472 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012473 int kind1, kind2, kind;
12474 void *buf1 = NULL, *buf2 = NULL;
12475 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012476
12477 str_obj = PyUnicode_FromObject(str_in);
12478 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012479 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012480 sep_obj = PyUnicode_FromObject(sep_in);
12481 if (!sep_obj) {
12482 Py_DECREF(str_obj);
12483 return NULL;
12484 }
12485
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012486 kind1 = PyUnicode_KIND(str_in);
12487 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012488 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012489 buf1 = PyUnicode_DATA(str_in);
12490 if (kind1 != kind)
12491 buf1 = _PyUnicode_AsKind(str_in, kind);
12492 if (!buf1)
12493 goto onError;
12494 buf2 = PyUnicode_DATA(sep_obj);
12495 if (kind2 != kind)
12496 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12497 if (!buf2)
12498 goto onError;
12499 len1 = PyUnicode_GET_LENGTH(str_obj);
12500 len2 = PyUnicode_GET_LENGTH(sep_obj);
12501
Benjamin Petersonead6b532011-12-20 17:23:42 -060012502 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012503 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012504 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12505 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12506 else
12507 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012508 break;
12509 case PyUnicode_2BYTE_KIND:
12510 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12511 break;
12512 case PyUnicode_4BYTE_KIND:
12513 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12514 break;
12515 default:
12516 assert(0);
12517 out = 0;
12518 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012519
12520 Py_DECREF(sep_obj);
12521 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012522 if (kind1 != kind)
12523 PyMem_Free(buf1);
12524 if (kind2 != kind)
12525 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012526
12527 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012528 onError:
12529 Py_DECREF(sep_obj);
12530 Py_DECREF(str_obj);
12531 if (kind1 != kind && buf1)
12532 PyMem_Free(buf1);
12533 if (kind2 != kind && buf2)
12534 PyMem_Free(buf2);
12535 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012536}
12537
12538PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012539 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012540\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012541Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012542the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012543found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012544
12545static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012546unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012547{
Victor Stinner9310abb2011-10-05 00:59:23 +020012548 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012549}
12550
12551PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012552 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012553\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012554Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012555the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012556separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012557
12558static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012559unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012560{
Victor Stinner9310abb2011-10-05 00:59:23 +020012561 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012562}
12563
Alexander Belopolsky40018472011-02-26 01:02:56 +000012564PyObject *
12565PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012566{
12567 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012568
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012569 s = PyUnicode_FromObject(s);
12570 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012571 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012572 if (sep != NULL) {
12573 sep = PyUnicode_FromObject(sep);
12574 if (sep == NULL) {
12575 Py_DECREF(s);
12576 return NULL;
12577 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012578 }
12579
Victor Stinner9310abb2011-10-05 00:59:23 +020012580 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012581
12582 Py_DECREF(s);
12583 Py_XDECREF(sep);
12584 return result;
12585}
12586
12587PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012588 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012589\n\
12590Return a list of the words in S, using sep as the\n\
12591delimiter string, starting at the end of the string and\n\
12592working to the front. If maxsplit is given, at most maxsplit\n\
12593splits are done. If sep is not specified, any whitespace string\n\
12594is a separator.");
12595
12596static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012597unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012598{
12599 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012600 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012601
Martin v. Löwis18e16552006-02-15 17:27:45 +000012602 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012603 return NULL;
12604
12605 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012606 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012607 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012608 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012609 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012610 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012611}
12612
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012613PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012614 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012615\n\
12616Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012617Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012618is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012619
12620static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012621unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012622{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012623 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012624 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012625
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012626 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12627 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012628 return NULL;
12629
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012630 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012631}
12632
12633static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012634PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012635{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012636 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012637}
12638
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012639PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012640 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012641\n\
12642Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012643and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012644
12645static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012646unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012647{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012648 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012649}
12650
Georg Brandlceee0772007-11-27 23:48:05 +000012651PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012652 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012653\n\
12654Return a translation table usable for str.translate().\n\
12655If there is only one argument, it must be a dictionary mapping Unicode\n\
12656ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012657Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012658If there are two arguments, they must be strings of equal length, and\n\
12659in the resulting dictionary, each character in x will be mapped to the\n\
12660character at the same position in y. If there is a third argument, it\n\
12661must be a string, whose characters will be mapped to None in the result.");
12662
12663static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012664unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012665{
12666 PyObject *x, *y = NULL, *z = NULL;
12667 PyObject *new = NULL, *key, *value;
12668 Py_ssize_t i = 0;
12669 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012670
Georg Brandlceee0772007-11-27 23:48:05 +000012671 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12672 return NULL;
12673 new = PyDict_New();
12674 if (!new)
12675 return NULL;
12676 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012677 int x_kind, y_kind, z_kind;
12678 void *x_data, *y_data, *z_data;
12679
Georg Brandlceee0772007-11-27 23:48:05 +000012680 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012681 if (!PyUnicode_Check(x)) {
12682 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12683 "be a string if there is a second argument");
12684 goto err;
12685 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012686 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012687 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12688 "arguments must have equal length");
12689 goto err;
12690 }
12691 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012692 x_kind = PyUnicode_KIND(x);
12693 y_kind = PyUnicode_KIND(y);
12694 x_data = PyUnicode_DATA(x);
12695 y_data = PyUnicode_DATA(y);
12696 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12697 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012698 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012699 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012700 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012701 if (!value) {
12702 Py_DECREF(key);
12703 goto err;
12704 }
Georg Brandlceee0772007-11-27 23:48:05 +000012705 res = PyDict_SetItem(new, key, value);
12706 Py_DECREF(key);
12707 Py_DECREF(value);
12708 if (res < 0)
12709 goto err;
12710 }
12711 /* create entries for deleting chars in z */
12712 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012713 z_kind = PyUnicode_KIND(z);
12714 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012715 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012716 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012717 if (!key)
12718 goto err;
12719 res = PyDict_SetItem(new, key, Py_None);
12720 Py_DECREF(key);
12721 if (res < 0)
12722 goto err;
12723 }
12724 }
12725 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012726 int kind;
12727 void *data;
12728
Georg Brandlceee0772007-11-27 23:48:05 +000012729 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012730 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012731 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12732 "to maketrans it must be a dict");
12733 goto err;
12734 }
12735 /* copy entries into the new dict, converting string keys to int keys */
12736 while (PyDict_Next(x, &i, &key, &value)) {
12737 if (PyUnicode_Check(key)) {
12738 /* convert string keys to integer keys */
12739 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012740 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012741 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12742 "table must be of length 1");
12743 goto err;
12744 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012745 kind = PyUnicode_KIND(key);
12746 data = PyUnicode_DATA(key);
12747 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012748 if (!newkey)
12749 goto err;
12750 res = PyDict_SetItem(new, newkey, value);
12751 Py_DECREF(newkey);
12752 if (res < 0)
12753 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012754 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012755 /* just keep integer keys */
12756 if (PyDict_SetItem(new, key, value) < 0)
12757 goto err;
12758 } else {
12759 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12760 "be strings or integers");
12761 goto err;
12762 }
12763 }
12764 }
12765 return new;
12766 err:
12767 Py_DECREF(new);
12768 return NULL;
12769}
12770
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012771PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012772 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012773\n\
12774Return a copy of the string S, where all characters have been mapped\n\
12775through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012776Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012777Unmapped characters are left untouched. Characters mapped to None\n\
12778are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012779
12780static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012781unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012782{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012783 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012784}
12785
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012786PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012787 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012788\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012789Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012790
12791static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012792unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012793{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012794 if (PyUnicode_READY(self) == -1)
12795 return NULL;
12796 if (PyUnicode_IS_ASCII(self))
12797 return ascii_upper_or_lower(self, 0);
12798 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012799}
12800
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012801PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012802 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012803\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012804Pad a numeric string S with zeros on the left, to fill a field\n\
12805of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012806
12807static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012808unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012809{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012810 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012811 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012812 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012813 int kind;
12814 void *data;
12815 Py_UCS4 chr;
12816
Martin v. Löwis18e16552006-02-15 17:27:45 +000012817 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012818 return NULL;
12819
Victor Stinnerc4b49542011-12-11 22:44:26 +010012820 if (PyUnicode_READY(self) < 0)
12821 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012822
Victor Stinnerc4b49542011-12-11 22:44:26 +010012823 if (PyUnicode_GET_LENGTH(self) >= width)
12824 return unicode_result_unchanged(self);
12825
12826 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012827
12828 u = pad(self, fill, 0, '0');
12829
Walter Dörwald068325e2002-04-15 13:36:47 +000012830 if (u == NULL)
12831 return NULL;
12832
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012833 kind = PyUnicode_KIND(u);
12834 data = PyUnicode_DATA(u);
12835 chr = PyUnicode_READ(kind, data, fill);
12836
12837 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012838 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012839 PyUnicode_WRITE(kind, data, 0, chr);
12840 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012841 }
12842
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012843 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012844 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012845}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012846
12847#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012848static PyObject *
12849unicode__decimal2ascii(PyObject *self)
12850{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012851 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012852}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012853#endif
12854
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012855PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012856 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012857\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012858Return True if S starts with the specified prefix, False otherwise.\n\
12859With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012860With optional end, stop comparing S at that position.\n\
12861prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012862
12863static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012864unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012865 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012866{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012867 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012868 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012869 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012870 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012871 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012872
Jesus Ceaac451502011-04-20 17:09:23 +020012873 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012874 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012875 if (PyTuple_Check(subobj)) {
12876 Py_ssize_t i;
12877 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012878 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012879 if (substring == NULL)
12880 return NULL;
12881 result = tailmatch(self, substring, start, end, -1);
12882 Py_DECREF(substring);
12883 if (result) {
12884 Py_RETURN_TRUE;
12885 }
12886 }
12887 /* nothing matched */
12888 Py_RETURN_FALSE;
12889 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012890 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012891 if (substring == NULL) {
12892 if (PyErr_ExceptionMatches(PyExc_TypeError))
12893 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12894 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012895 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012896 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012897 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012898 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012899 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012900}
12901
12902
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012903PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012904 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012905\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012906Return True if S ends with the specified suffix, False otherwise.\n\
12907With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012908With optional end, stop comparing S at that position.\n\
12909suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012910
12911static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012912unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012913 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012914{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012915 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012916 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012917 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012918 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012919 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012920
Jesus Ceaac451502011-04-20 17:09:23 +020012921 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012922 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012923 if (PyTuple_Check(subobj)) {
12924 Py_ssize_t i;
12925 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012926 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012927 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012928 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012929 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012930 result = tailmatch(self, substring, start, end, +1);
12931 Py_DECREF(substring);
12932 if (result) {
12933 Py_RETURN_TRUE;
12934 }
12935 }
12936 Py_RETURN_FALSE;
12937 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012938 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012939 if (substring == NULL) {
12940 if (PyErr_ExceptionMatches(PyExc_TypeError))
12941 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12942 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012943 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012944 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012945 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012946 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012947 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012948}
12949
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012950#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012951
12952PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012953 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012954\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012955Return a formatted version of S, using substitutions from args and kwargs.\n\
12956The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012957
Eric Smith27bbca62010-11-04 17:06:58 +000012958PyDoc_STRVAR(format_map__doc__,
12959 "S.format_map(mapping) -> str\n\
12960\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012961Return a formatted version of S, using substitutions from mapping.\n\
12962The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012963
Eric Smith4a7d76d2008-05-30 18:10:19 +000012964static PyObject *
12965unicode__format__(PyObject* self, PyObject* args)
12966{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012967 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012968
12969 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12970 return NULL;
12971
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012972 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012973 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012974 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012975}
12976
Eric Smith8c663262007-08-25 02:26:07 +000012977PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012978 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012979\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012980Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012981
12982static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012983unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012984{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012985 Py_ssize_t size;
12986
12987 /* If it's a compact object, account for base structure +
12988 character data. */
12989 if (PyUnicode_IS_COMPACT_ASCII(v))
12990 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12991 else if (PyUnicode_IS_COMPACT(v))
12992 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012993 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012994 else {
12995 /* If it is a two-block object, account for base object, and
12996 for character block if present. */
12997 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012998 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012999 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013000 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013001 }
13002 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013003 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013004 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013005 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013006 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013007 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013008
13009 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013010}
13011
13012PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013013 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013014
13015static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013016unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013017{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013018 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013019 if (!copy)
13020 return NULL;
13021 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013022}
13023
Guido van Rossumd57fd912000-03-10 22:53:23 +000013024static PyMethodDef unicode_methods[] = {
13025
13026 /* Order is according to common usage: often used methods should
13027 appear first, since lookup is done sequentially. */
13028
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013029 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013030 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
13031 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013032 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013033 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13034 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013035 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013036 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13037 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13038 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13039 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13040 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013041 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013042 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13043 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13044 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013045 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013046 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13047 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13048 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013049 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013050 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013051 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013052 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013053 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13054 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13055 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13056 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13057 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13058 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13059 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13060 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13061 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13062 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13063 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13064 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13065 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13066 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013067 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013068 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013069 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013070 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013071 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013072 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013073 {"maketrans", (PyCFunction) unicode_maketrans,
13074 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013075 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013076#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013077 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013078 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013079#endif
13080
Benjamin Peterson14339b62009-01-31 16:36:08 +000013081 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013082 {NULL, NULL}
13083};
13084
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013085static PyObject *
13086unicode_mod(PyObject *v, PyObject *w)
13087{
Brian Curtindfc80e32011-08-10 20:28:54 -050013088 if (!PyUnicode_Check(v))
13089 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013090 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013091}
13092
13093static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013094 0, /*nb_add*/
13095 0, /*nb_subtract*/
13096 0, /*nb_multiply*/
13097 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013098};
13099
Guido van Rossumd57fd912000-03-10 22:53:23 +000013100static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013101 (lenfunc) unicode_length, /* sq_length */
13102 PyUnicode_Concat, /* sq_concat */
13103 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13104 (ssizeargfunc) unicode_getitem, /* sq_item */
13105 0, /* sq_slice */
13106 0, /* sq_ass_item */
13107 0, /* sq_ass_slice */
13108 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013109};
13110
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013111static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013112unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013113{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013114 if (PyUnicode_READY(self) == -1)
13115 return NULL;
13116
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013117 if (PyIndex_Check(item)) {
13118 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013119 if (i == -1 && PyErr_Occurred())
13120 return NULL;
13121 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013122 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013123 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013124 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013125 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013126 PyObject *result;
13127 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013128 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013129 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013130
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013131 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013132 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013133 return NULL;
13134 }
13135
13136 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013137 Py_INCREF(unicode_empty);
13138 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013139 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013140 slicelength == PyUnicode_GET_LENGTH(self)) {
13141 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013142 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013143 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013144 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013145 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013146 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013147 src_kind = PyUnicode_KIND(self);
13148 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013149 if (!PyUnicode_IS_ASCII(self)) {
13150 kind_limit = kind_maxchar_limit(src_kind);
13151 max_char = 0;
13152 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13153 ch = PyUnicode_READ(src_kind, src_data, cur);
13154 if (ch > max_char) {
13155 max_char = ch;
13156 if (max_char >= kind_limit)
13157 break;
13158 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013159 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013160 }
Victor Stinner55c99112011-10-13 01:17:06 +020013161 else
13162 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013163 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013164 if (result == NULL)
13165 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013166 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013167 dest_data = PyUnicode_DATA(result);
13168
13169 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013170 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13171 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013172 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013173 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013174 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013175 } else {
13176 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13177 return NULL;
13178 }
13179}
13180
13181static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013182 (lenfunc)unicode_length, /* mp_length */
13183 (binaryfunc)unicode_subscript, /* mp_subscript */
13184 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013185};
13186
Guido van Rossumd57fd912000-03-10 22:53:23 +000013187
Guido van Rossumd57fd912000-03-10 22:53:23 +000013188/* Helpers for PyUnicode_Format() */
13189
13190static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013191getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013192{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013193 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013194 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013195 (*p_argidx)++;
13196 if (arglen < 0)
13197 return args;
13198 else
13199 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013200 }
13201 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013202 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013203 return NULL;
13204}
13205
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013206/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013207
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013208static PyObject *
13209formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013210{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013211 char *p;
13212 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013213 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013214
Guido van Rossumd57fd912000-03-10 22:53:23 +000013215 x = PyFloat_AsDouble(v);
13216 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013217 return NULL;
13218
Guido van Rossumd57fd912000-03-10 22:53:23 +000013219 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013220 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013221
Eric Smith0923d1d2009-04-16 20:16:10 +000013222 p = PyOS_double_to_string(x, type, prec,
13223 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013224 if (p == NULL)
13225 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013226 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013227 PyMem_Free(p);
13228 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013229}
13230
Tim Peters38fd5b62000-09-21 05:43:11 +000013231static PyObject*
13232formatlong(PyObject *val, int flags, int prec, int type)
13233{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013234 char *buf;
13235 int len;
13236 PyObject *str; /* temporary string object. */
13237 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013238
Benjamin Peterson14339b62009-01-31 16:36:08 +000013239 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13240 if (!str)
13241 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013242 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013243 Py_DECREF(str);
13244 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013245}
13246
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013247static Py_UCS4
13248formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013249{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013250 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013251 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013252 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013253 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013254 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013255 goto onError;
13256 }
13257 else {
13258 /* Integer input truncated to a character */
13259 long x;
13260 x = PyLong_AsLong(v);
13261 if (x == -1 && PyErr_Occurred())
13262 goto onError;
13263
Victor Stinner8faf8212011-12-08 22:14:11 +010013264 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013265 PyErr_SetString(PyExc_OverflowError,
13266 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013267 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013268 }
13269
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013270 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013271 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013272
Benjamin Peterson29060642009-01-31 22:14:21 +000013273 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013274 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013275 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013276 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013277}
13278
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013279static int
13280repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13281{
13282 int r;
13283 assert(count > 0);
13284 assert(PyUnicode_Check(obj));
13285 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013286 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013287 if (repeated == NULL)
13288 return -1;
13289 r = _PyAccu_Accumulate(acc, repeated);
13290 Py_DECREF(repeated);
13291 return r;
13292 }
13293 else {
13294 do {
13295 if (_PyAccu_Accumulate(acc, obj))
13296 return -1;
13297 } while (--count);
13298 return 0;
13299 }
13300}
13301
Alexander Belopolsky40018472011-02-26 01:02:56 +000013302PyObject *
13303PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013304{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013305 void *fmt;
13306 int fmtkind;
13307 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013308 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013309 int r;
13310 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013311 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013312 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013313 PyObject *temp = NULL;
13314 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013315 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013316 _PyAccu acc;
13317 static PyObject *plus, *minus, *blank, *zero, *percent;
13318
13319 if (!plus && !(plus = get_latin1_char('+')))
13320 return NULL;
13321 if (!minus && !(minus = get_latin1_char('-')))
13322 return NULL;
13323 if (!blank && !(blank = get_latin1_char(' ')))
13324 return NULL;
13325 if (!zero && !(zero = get_latin1_char('0')))
13326 return NULL;
13327 if (!percent && !(percent = get_latin1_char('%')))
13328 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013329
Guido van Rossumd57fd912000-03-10 22:53:23 +000013330 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013331 PyErr_BadInternalCall();
13332 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013333 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013334 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013335 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013336 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013337 if (PyUnicode_READY(uformat) == -1)
13338 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013339 if (_PyAccu_Init(&acc))
13340 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013341 fmt = PyUnicode_DATA(uformat);
13342 fmtkind = PyUnicode_KIND(uformat);
13343 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13344 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013345
Guido van Rossumd57fd912000-03-10 22:53:23 +000013346 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013347 arglen = PyTuple_Size(args);
13348 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013349 }
13350 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013351 arglen = -1;
13352 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013353 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013354 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013355 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013356 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013357
13358 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013359 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013360 PyObject *nonfmt;
13361 Py_ssize_t nonfmtpos;
13362 nonfmtpos = fmtpos++;
13363 while (fmtcnt >= 0 &&
13364 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13365 fmtpos++;
13366 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013367 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013368 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013369 if (nonfmt == NULL)
13370 goto onError;
13371 r = _PyAccu_Accumulate(&acc, nonfmt);
13372 Py_DECREF(nonfmt);
13373 if (r)
13374 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013375 }
13376 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013377 /* Got a format specifier */
13378 int flags = 0;
13379 Py_ssize_t width = -1;
13380 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013381 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013382 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013383 int isnumok;
13384 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013385 void *pbuf = NULL;
13386 Py_ssize_t pindex, len;
13387 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013388
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013389 fmtpos++;
13390 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13391 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013392 Py_ssize_t keylen;
13393 PyObject *key;
13394 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013395
Benjamin Peterson29060642009-01-31 22:14:21 +000013396 if (dict == NULL) {
13397 PyErr_SetString(PyExc_TypeError,
13398 "format requires a mapping");
13399 goto onError;
13400 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013401 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013402 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013403 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013404 /* Skip over balanced parentheses */
13405 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013406 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013407 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013408 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013409 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013410 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013411 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013412 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013413 if (fmtcnt < 0 || pcount > 0) {
13414 PyErr_SetString(PyExc_ValueError,
13415 "incomplete format key");
13416 goto onError;
13417 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013418 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013419 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013420 if (key == NULL)
13421 goto onError;
13422 if (args_owned) {
13423 Py_DECREF(args);
13424 args_owned = 0;
13425 }
13426 args = PyObject_GetItem(dict, key);
13427 Py_DECREF(key);
13428 if (args == NULL) {
13429 goto onError;
13430 }
13431 args_owned = 1;
13432 arglen = -1;
13433 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013434 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013435 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013436 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013437 case '-': flags |= F_LJUST; continue;
13438 case '+': flags |= F_SIGN; continue;
13439 case ' ': flags |= F_BLANK; continue;
13440 case '#': flags |= F_ALT; continue;
13441 case '0': flags |= F_ZERO; continue;
13442 }
13443 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013444 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013445 if (c == '*') {
13446 v = getnextarg(args, arglen, &argidx);
13447 if (v == NULL)
13448 goto onError;
13449 if (!PyLong_Check(v)) {
13450 PyErr_SetString(PyExc_TypeError,
13451 "* wants int");
13452 goto onError;
13453 }
13454 width = PyLong_AsLong(v);
13455 if (width == -1 && PyErr_Occurred())
13456 goto onError;
13457 if (width < 0) {
13458 flags |= F_LJUST;
13459 width = -width;
13460 }
13461 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013462 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013463 }
13464 else if (c >= '0' && c <= '9') {
13465 width = c - '0';
13466 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013467 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013468 if (c < '0' || c > '9')
13469 break;
13470 if ((width*10) / 10 != width) {
13471 PyErr_SetString(PyExc_ValueError,
13472 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013473 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013474 }
13475 width = width*10 + (c - '0');
13476 }
13477 }
13478 if (c == '.') {
13479 prec = 0;
13480 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013481 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013482 if (c == '*') {
13483 v = getnextarg(args, arglen, &argidx);
13484 if (v == NULL)
13485 goto onError;
13486 if (!PyLong_Check(v)) {
13487 PyErr_SetString(PyExc_TypeError,
13488 "* wants int");
13489 goto onError;
13490 }
13491 prec = PyLong_AsLong(v);
13492 if (prec == -1 && PyErr_Occurred())
13493 goto onError;
13494 if (prec < 0)
13495 prec = 0;
13496 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013497 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013498 }
13499 else if (c >= '0' && c <= '9') {
13500 prec = c - '0';
13501 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013502 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013503 if (c < '0' || c > '9')
13504 break;
13505 if ((prec*10) / 10 != prec) {
13506 PyErr_SetString(PyExc_ValueError,
13507 "prec too big");
13508 goto onError;
13509 }
13510 prec = prec*10 + (c - '0');
13511 }
13512 }
13513 } /* prec */
13514 if (fmtcnt >= 0) {
13515 if (c == 'h' || c == 'l' || c == 'L') {
13516 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013517 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013518 }
13519 }
13520 if (fmtcnt < 0) {
13521 PyErr_SetString(PyExc_ValueError,
13522 "incomplete format");
13523 goto onError;
13524 }
13525 if (c != '%') {
13526 v = getnextarg(args, arglen, &argidx);
13527 if (v == NULL)
13528 goto onError;
13529 }
13530 sign = 0;
13531 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013532 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013533 switch (c) {
13534
13535 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013536 _PyAccu_Accumulate(&acc, percent);
13537 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013538
13539 case 's':
13540 case 'r':
13541 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013542 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013543 temp = v;
13544 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013545 }
13546 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013547 if (c == 's')
13548 temp = PyObject_Str(v);
13549 else if (c == 'r')
13550 temp = PyObject_Repr(v);
13551 else
13552 temp = PyObject_ASCII(v);
13553 if (temp == NULL)
13554 goto onError;
13555 if (PyUnicode_Check(temp))
13556 /* nothing to do */;
13557 else {
13558 Py_DECREF(temp);
13559 PyErr_SetString(PyExc_TypeError,
13560 "%s argument has non-string str()");
13561 goto onError;
13562 }
13563 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013564 if (PyUnicode_READY(temp) == -1) {
13565 Py_CLEAR(temp);
13566 goto onError;
13567 }
13568 pbuf = PyUnicode_DATA(temp);
13569 kind = PyUnicode_KIND(temp);
13570 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013571 if (prec >= 0 && len > prec)
13572 len = prec;
13573 break;
13574
13575 case 'i':
13576 case 'd':
13577 case 'u':
13578 case 'o':
13579 case 'x':
13580 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013581 isnumok = 0;
13582 if (PyNumber_Check(v)) {
13583 PyObject *iobj=NULL;
13584
13585 if (PyLong_Check(v)) {
13586 iobj = v;
13587 Py_INCREF(iobj);
13588 }
13589 else {
13590 iobj = PyNumber_Long(v);
13591 }
13592 if (iobj!=NULL) {
13593 if (PyLong_Check(iobj)) {
13594 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013595 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013596 Py_DECREF(iobj);
13597 if (!temp)
13598 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013599 if (PyUnicode_READY(temp) == -1) {
13600 Py_CLEAR(temp);
13601 goto onError;
13602 }
13603 pbuf = PyUnicode_DATA(temp);
13604 kind = PyUnicode_KIND(temp);
13605 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013606 sign = 1;
13607 }
13608 else {
13609 Py_DECREF(iobj);
13610 }
13611 }
13612 }
13613 if (!isnumok) {
13614 PyErr_Format(PyExc_TypeError,
13615 "%%%c format: a number is required, "
13616 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13617 goto onError;
13618 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013619 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013620 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013621 fillobj = zero;
13622 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013623 break;
13624
13625 case 'e':
13626 case 'E':
13627 case 'f':
13628 case 'F':
13629 case 'g':
13630 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013631 temp = formatfloat(v, flags, prec, c);
13632 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013633 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013634 if (PyUnicode_READY(temp) == -1) {
13635 Py_CLEAR(temp);
13636 goto onError;
13637 }
13638 pbuf = PyUnicode_DATA(temp);
13639 kind = PyUnicode_KIND(temp);
13640 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013641 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013642 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013643 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013644 fillobj = zero;
13645 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013646 break;
13647
13648 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013649 {
13650 Py_UCS4 ch = formatchar(v);
13651 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013652 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013653 temp = _PyUnicode_FromUCS4(&ch, 1);
13654 if (temp == NULL)
13655 goto onError;
13656 pbuf = PyUnicode_DATA(temp);
13657 kind = PyUnicode_KIND(temp);
13658 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013659 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013660 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013661
13662 default:
13663 PyErr_Format(PyExc_ValueError,
13664 "unsupported format character '%c' (0x%x) "
13665 "at index %zd",
13666 (31<=c && c<=126) ? (char)c : '?',
13667 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013668 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013669 goto onError;
13670 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013671 /* pbuf is initialized here. */
13672 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013673 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013674 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13675 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013676 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013677 pindex++;
13678 }
13679 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13680 signobj = plus;
13681 len--;
13682 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013683 }
13684 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013685 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013686 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013687 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013688 else
13689 sign = 0;
13690 }
13691 if (width < len)
13692 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013693 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013694 if (fill != ' ') {
13695 assert(signobj != NULL);
13696 if (_PyAccu_Accumulate(&acc, signobj))
13697 goto onError;
13698 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013699 if (width > len)
13700 width--;
13701 }
13702 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013703 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013704 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013705 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013706 second = get_latin1_char(
13707 PyUnicode_READ(kind, pbuf, pindex + 1));
13708 pindex += 2;
13709 if (second == NULL ||
13710 _PyAccu_Accumulate(&acc, zero) ||
13711 _PyAccu_Accumulate(&acc, second))
13712 goto onError;
13713 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013714 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013715 width -= 2;
13716 if (width < 0)
13717 width = 0;
13718 len -= 2;
13719 }
13720 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013721 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013722 if (repeat_accumulate(&acc, fillobj, width - len))
13723 goto onError;
13724 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013725 }
13726 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013727 if (sign) {
13728 assert(signobj != NULL);
13729 if (_PyAccu_Accumulate(&acc, signobj))
13730 goto onError;
13731 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013732 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013733 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13734 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013735 second = get_latin1_char(
13736 PyUnicode_READ(kind, pbuf, pindex + 1));
13737 pindex += 2;
13738 if (second == NULL ||
13739 _PyAccu_Accumulate(&acc, zero) ||
13740 _PyAccu_Accumulate(&acc, second))
13741 goto onError;
13742 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013743 }
13744 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013745 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013746 if (temp != NULL) {
13747 assert(pbuf == PyUnicode_DATA(temp));
13748 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013749 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013750 else {
13751 const char *p = (const char *) pbuf;
13752 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013753 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013754 v = PyUnicode_FromKindAndData(kind, p, len);
13755 }
13756 if (v == NULL)
13757 goto onError;
13758 r = _PyAccu_Accumulate(&acc, v);
13759 Py_DECREF(v);
13760 if (r)
13761 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013762 if (width > len && repeat_accumulate(&acc, blank, width - len))
13763 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013764 if (dict && (argidx < arglen) && c != '%') {
13765 PyErr_SetString(PyExc_TypeError,
13766 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013767 goto onError;
13768 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013769 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013770 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013771 } /* until end */
13772 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013773 PyErr_SetString(PyExc_TypeError,
13774 "not all arguments converted during string formatting");
13775 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013776 }
13777
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013778 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013779 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013780 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013781 }
13782 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013783 Py_XDECREF(temp);
13784 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013785 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013786
Benjamin Peterson29060642009-01-31 22:14:21 +000013787 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013788 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013789 Py_XDECREF(temp);
13790 Py_XDECREF(second);
13791 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013792 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013793 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013794 }
13795 return NULL;
13796}
13797
Jeremy Hylton938ace62002-07-17 16:30:39 +000013798static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013799unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13800
Tim Peters6d6c1a32001-08-02 04:15:00 +000013801static PyObject *
13802unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13803{
Benjamin Peterson29060642009-01-31 22:14:21 +000013804 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013805 static char *kwlist[] = {"object", "encoding", "errors", 0};
13806 char *encoding = NULL;
13807 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013808
Benjamin Peterson14339b62009-01-31 16:36:08 +000013809 if (type != &PyUnicode_Type)
13810 return unicode_subtype_new(type, args, kwds);
13811 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013812 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013813 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013814 if (x == NULL) {
13815 Py_INCREF(unicode_empty);
13816 return unicode_empty;
13817 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013818 if (encoding == NULL && errors == NULL)
13819 return PyObject_Str(x);
13820 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013821 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013822}
13823
Guido van Rossume023fe02001-08-30 03:12:59 +000013824static PyObject *
13825unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13826{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013827 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013828 Py_ssize_t length, char_size;
13829 int share_wstr, share_utf8;
13830 unsigned int kind;
13831 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013832
Benjamin Peterson14339b62009-01-31 16:36:08 +000013833 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013834
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013835 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013836 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013837 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013838 assert(_PyUnicode_CHECK(unicode));
Benjamin Peterson22a29702012-01-02 09:00:30 -060013839 if (PyUnicode_READY(unicode)) {
13840 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013841 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013842 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013843
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013844 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013845 if (self == NULL) {
13846 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013847 return NULL;
13848 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013849 kind = PyUnicode_KIND(unicode);
13850 length = PyUnicode_GET_LENGTH(unicode);
13851
13852 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013853#ifdef Py_DEBUG
13854 _PyUnicode_HASH(self) = -1;
13855#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013856 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013857#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013858 _PyUnicode_STATE(self).interned = 0;
13859 _PyUnicode_STATE(self).kind = kind;
13860 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013861 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013862 _PyUnicode_STATE(self).ready = 1;
13863 _PyUnicode_WSTR(self) = NULL;
13864 _PyUnicode_UTF8_LENGTH(self) = 0;
13865 _PyUnicode_UTF8(self) = NULL;
13866 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013867 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013868
13869 share_utf8 = 0;
13870 share_wstr = 0;
13871 if (kind == PyUnicode_1BYTE_KIND) {
13872 char_size = 1;
13873 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13874 share_utf8 = 1;
13875 }
13876 else if (kind == PyUnicode_2BYTE_KIND) {
13877 char_size = 2;
13878 if (sizeof(wchar_t) == 2)
13879 share_wstr = 1;
13880 }
13881 else {
13882 assert(kind == PyUnicode_4BYTE_KIND);
13883 char_size = 4;
13884 if (sizeof(wchar_t) == 4)
13885 share_wstr = 1;
13886 }
13887
13888 /* Ensure we won't overflow the length. */
13889 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13890 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013891 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013892 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013893 data = PyObject_MALLOC((length + 1) * char_size);
13894 if (data == NULL) {
13895 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013896 goto onError;
13897 }
13898
Victor Stinnerc3c74152011-10-02 20:39:55 +020013899 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013900 if (share_utf8) {
13901 _PyUnicode_UTF8_LENGTH(self) = length;
13902 _PyUnicode_UTF8(self) = data;
13903 }
13904 if (share_wstr) {
13905 _PyUnicode_WSTR_LENGTH(self) = length;
13906 _PyUnicode_WSTR(self) = (wchar_t *)data;
13907 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013908
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013909 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013910 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013911 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013912#ifdef Py_DEBUG
13913 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13914#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013915 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013916 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013917
13918onError:
13919 Py_DECREF(unicode);
13920 Py_DECREF(self);
13921 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013922}
13923
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013924PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013925 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013926\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013927Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013928encoding defaults to the current default string encoding.\n\
13929errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013930
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013931static PyObject *unicode_iter(PyObject *seq);
13932
Guido van Rossumd57fd912000-03-10 22:53:23 +000013933PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013934 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013935 "str", /* tp_name */
13936 sizeof(PyUnicodeObject), /* tp_size */
13937 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013938 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013939 (destructor)unicode_dealloc, /* tp_dealloc */
13940 0, /* tp_print */
13941 0, /* tp_getattr */
13942 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013943 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013944 unicode_repr, /* tp_repr */
13945 &unicode_as_number, /* tp_as_number */
13946 &unicode_as_sequence, /* tp_as_sequence */
13947 &unicode_as_mapping, /* tp_as_mapping */
13948 (hashfunc) unicode_hash, /* tp_hash*/
13949 0, /* tp_call*/
13950 (reprfunc) unicode_str, /* tp_str */
13951 PyObject_GenericGetAttr, /* tp_getattro */
13952 0, /* tp_setattro */
13953 0, /* tp_as_buffer */
13954 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013955 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013956 unicode_doc, /* tp_doc */
13957 0, /* tp_traverse */
13958 0, /* tp_clear */
13959 PyUnicode_RichCompare, /* tp_richcompare */
13960 0, /* tp_weaklistoffset */
13961 unicode_iter, /* tp_iter */
13962 0, /* tp_iternext */
13963 unicode_methods, /* tp_methods */
13964 0, /* tp_members */
13965 0, /* tp_getset */
13966 &PyBaseObject_Type, /* tp_base */
13967 0, /* tp_dict */
13968 0, /* tp_descr_get */
13969 0, /* tp_descr_set */
13970 0, /* tp_dictoffset */
13971 0, /* tp_init */
13972 0, /* tp_alloc */
13973 unicode_new, /* tp_new */
13974 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013975};
13976
13977/* Initialize the Unicode implementation */
13978
Victor Stinner3a50e702011-10-18 21:21:00 +020013979int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013980{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013981 int i;
13982
Thomas Wouters477c8d52006-05-27 19:21:47 +000013983 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013984 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013985 0x000A, /* LINE FEED */
13986 0x000D, /* CARRIAGE RETURN */
13987 0x001C, /* FILE SEPARATOR */
13988 0x001D, /* GROUP SEPARATOR */
13989 0x001E, /* RECORD SEPARATOR */
13990 0x0085, /* NEXT LINE */
13991 0x2028, /* LINE SEPARATOR */
13992 0x2029, /* PARAGRAPH SEPARATOR */
13993 };
13994
Fred Drakee4315f52000-05-09 19:53:39 +000013995 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013996 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013997 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013998 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010013999 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014000
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014001 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014002 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014003 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014004 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014005
14006 /* initialize the linebreak bloom filter */
14007 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014008 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014009 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014010
14011 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014012
14013#ifdef HAVE_MBCS
14014 winver.dwOSVersionInfoSize = sizeof(winver);
14015 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14016 PyErr_SetFromWindowsErr(0);
14017 return -1;
14018 }
14019#endif
14020 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014021}
14022
14023/* Finalize the Unicode implementation */
14024
Christian Heimesa156e092008-02-16 07:38:31 +000014025int
14026PyUnicode_ClearFreeList(void)
14027{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014028 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014029}
14030
Guido van Rossumd57fd912000-03-10 22:53:23 +000014031void
Thomas Wouters78890102000-07-22 19:25:51 +000014032_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014033{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014034 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014035
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014036 Py_XDECREF(unicode_empty);
14037 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014038
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014039 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014040 if (unicode_latin1[i]) {
14041 Py_DECREF(unicode_latin1[i]);
14042 unicode_latin1[i] = NULL;
14043 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014044 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014045 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014046 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014047}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014048
Walter Dörwald16807132007-05-25 13:52:07 +000014049void
14050PyUnicode_InternInPlace(PyObject **p)
14051{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014052 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014053 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014054#ifdef Py_DEBUG
14055 assert(s != NULL);
14056 assert(_PyUnicode_CHECK(s));
14057#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014058 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014059 return;
14060#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014061 /* If it's a subclass, we don't really know what putting
14062 it in the interned dict might do. */
14063 if (!PyUnicode_CheckExact(s))
14064 return;
14065 if (PyUnicode_CHECK_INTERNED(s))
14066 return;
14067 if (interned == NULL) {
14068 interned = PyDict_New();
14069 if (interned == NULL) {
14070 PyErr_Clear(); /* Don't leave an exception */
14071 return;
14072 }
14073 }
14074 /* It might be that the GetItem call fails even
14075 though the key is present in the dictionary,
14076 namely when this happens during a stack overflow. */
14077 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014078 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014079 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014080
Benjamin Peterson29060642009-01-31 22:14:21 +000014081 if (t) {
14082 Py_INCREF(t);
14083 Py_DECREF(*p);
14084 *p = t;
14085 return;
14086 }
Walter Dörwald16807132007-05-25 13:52:07 +000014087
Benjamin Peterson14339b62009-01-31 16:36:08 +000014088 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014089 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014090 PyErr_Clear();
14091 PyThreadState_GET()->recursion_critical = 0;
14092 return;
14093 }
14094 PyThreadState_GET()->recursion_critical = 0;
14095 /* The two references in interned are not counted by refcnt.
14096 The deallocator will take care of this */
14097 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014098 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014099}
14100
14101void
14102PyUnicode_InternImmortal(PyObject **p)
14103{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014104 PyUnicode_InternInPlace(p);
14105 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014106 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014107 Py_INCREF(*p);
14108 }
Walter Dörwald16807132007-05-25 13:52:07 +000014109}
14110
14111PyObject *
14112PyUnicode_InternFromString(const char *cp)
14113{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014114 PyObject *s = PyUnicode_FromString(cp);
14115 if (s == NULL)
14116 return NULL;
14117 PyUnicode_InternInPlace(&s);
14118 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014119}
14120
Alexander Belopolsky40018472011-02-26 01:02:56 +000014121void
14122_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014123{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014124 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014125 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014126 Py_ssize_t i, n;
14127 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014128
Benjamin Peterson14339b62009-01-31 16:36:08 +000014129 if (interned == NULL || !PyDict_Check(interned))
14130 return;
14131 keys = PyDict_Keys(interned);
14132 if (keys == NULL || !PyList_Check(keys)) {
14133 PyErr_Clear();
14134 return;
14135 }
Walter Dörwald16807132007-05-25 13:52:07 +000014136
Benjamin Peterson14339b62009-01-31 16:36:08 +000014137 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14138 detector, interned unicode strings are not forcibly deallocated;
14139 rather, we give them their stolen references back, and then clear
14140 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014141
Benjamin Peterson14339b62009-01-31 16:36:08 +000014142 n = PyList_GET_SIZE(keys);
14143 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014144 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014145 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014146 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014147 if (PyUnicode_READY(s) == -1) {
14148 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014149 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014150 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014151 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014152 case SSTATE_NOT_INTERNED:
14153 /* XXX Shouldn't happen */
14154 break;
14155 case SSTATE_INTERNED_IMMORTAL:
14156 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014157 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014158 break;
14159 case SSTATE_INTERNED_MORTAL:
14160 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014161 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014162 break;
14163 default:
14164 Py_FatalError("Inconsistent interned string state.");
14165 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014166 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014167 }
14168 fprintf(stderr, "total size of all interned strings: "
14169 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14170 "mortal/immortal\n", mortal_size, immortal_size);
14171 Py_DECREF(keys);
14172 PyDict_Clear(interned);
14173 Py_DECREF(interned);
14174 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014175}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014176
14177
14178/********************* Unicode Iterator **************************/
14179
14180typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014181 PyObject_HEAD
14182 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014183 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014184} unicodeiterobject;
14185
14186static void
14187unicodeiter_dealloc(unicodeiterobject *it)
14188{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014189 _PyObject_GC_UNTRACK(it);
14190 Py_XDECREF(it->it_seq);
14191 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014192}
14193
14194static int
14195unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14196{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014197 Py_VISIT(it->it_seq);
14198 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014199}
14200
14201static PyObject *
14202unicodeiter_next(unicodeiterobject *it)
14203{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014204 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014205
Benjamin Peterson14339b62009-01-31 16:36:08 +000014206 assert(it != NULL);
14207 seq = it->it_seq;
14208 if (seq == NULL)
14209 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014210 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014211
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014212 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14213 int kind = PyUnicode_KIND(seq);
14214 void *data = PyUnicode_DATA(seq);
14215 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14216 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014217 if (item != NULL)
14218 ++it->it_index;
14219 return item;
14220 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014221
Benjamin Peterson14339b62009-01-31 16:36:08 +000014222 Py_DECREF(seq);
14223 it->it_seq = NULL;
14224 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014225}
14226
14227static PyObject *
14228unicodeiter_len(unicodeiterobject *it)
14229{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014230 Py_ssize_t len = 0;
14231 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014232 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014233 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014234}
14235
14236PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14237
14238static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014239 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014240 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014241 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014242};
14243
14244PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014245 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14246 "str_iterator", /* tp_name */
14247 sizeof(unicodeiterobject), /* tp_basicsize */
14248 0, /* tp_itemsize */
14249 /* methods */
14250 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14251 0, /* tp_print */
14252 0, /* tp_getattr */
14253 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014254 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014255 0, /* tp_repr */
14256 0, /* tp_as_number */
14257 0, /* tp_as_sequence */
14258 0, /* tp_as_mapping */
14259 0, /* tp_hash */
14260 0, /* tp_call */
14261 0, /* tp_str */
14262 PyObject_GenericGetAttr, /* tp_getattro */
14263 0, /* tp_setattro */
14264 0, /* tp_as_buffer */
14265 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14266 0, /* tp_doc */
14267 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14268 0, /* tp_clear */
14269 0, /* tp_richcompare */
14270 0, /* tp_weaklistoffset */
14271 PyObject_SelfIter, /* tp_iter */
14272 (iternextfunc)unicodeiter_next, /* tp_iternext */
14273 unicodeiter_methods, /* tp_methods */
14274 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014275};
14276
14277static PyObject *
14278unicode_iter(PyObject *seq)
14279{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014280 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014281
Benjamin Peterson14339b62009-01-31 16:36:08 +000014282 if (!PyUnicode_Check(seq)) {
14283 PyErr_BadInternalCall();
14284 return NULL;
14285 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014286 if (PyUnicode_READY(seq) == -1)
14287 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014288 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14289 if (it == NULL)
14290 return NULL;
14291 it->it_index = 0;
14292 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014293 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014294 _PyObject_GC_TRACK(it);
14295 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014296}
14297
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014298
14299size_t
14300Py_UNICODE_strlen(const Py_UNICODE *u)
14301{
14302 int res = 0;
14303 while(*u++)
14304 res++;
14305 return res;
14306}
14307
14308Py_UNICODE*
14309Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14310{
14311 Py_UNICODE *u = s1;
14312 while ((*u++ = *s2++));
14313 return s1;
14314}
14315
14316Py_UNICODE*
14317Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14318{
14319 Py_UNICODE *u = s1;
14320 while ((*u++ = *s2++))
14321 if (n-- == 0)
14322 break;
14323 return s1;
14324}
14325
14326Py_UNICODE*
14327Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14328{
14329 Py_UNICODE *u1 = s1;
14330 u1 += Py_UNICODE_strlen(u1);
14331 Py_UNICODE_strcpy(u1, s2);
14332 return s1;
14333}
14334
14335int
14336Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14337{
14338 while (*s1 && *s2 && *s1 == *s2)
14339 s1++, s2++;
14340 if (*s1 && *s2)
14341 return (*s1 < *s2) ? -1 : +1;
14342 if (*s1)
14343 return 1;
14344 if (*s2)
14345 return -1;
14346 return 0;
14347}
14348
14349int
14350Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14351{
14352 register Py_UNICODE u1, u2;
14353 for (; n != 0; n--) {
14354 u1 = *s1;
14355 u2 = *s2;
14356 if (u1 != u2)
14357 return (u1 < u2) ? -1 : +1;
14358 if (u1 == '\0')
14359 return 0;
14360 s1++;
14361 s2++;
14362 }
14363 return 0;
14364}
14365
14366Py_UNICODE*
14367Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14368{
14369 const Py_UNICODE *p;
14370 for (p = s; *p; p++)
14371 if (*p == c)
14372 return (Py_UNICODE*)p;
14373 return NULL;
14374}
14375
14376Py_UNICODE*
14377Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14378{
14379 const Py_UNICODE *p;
14380 p = s + Py_UNICODE_strlen(s);
14381 while (p != s) {
14382 p--;
14383 if (*p == c)
14384 return (Py_UNICODE*)p;
14385 }
14386 return NULL;
14387}
Victor Stinner331ea922010-08-10 16:37:20 +000014388
Victor Stinner71133ff2010-09-01 23:43:53 +000014389Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014390PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014391{
Victor Stinner577db2c2011-10-11 22:12:48 +020014392 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014393 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014394
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014395 if (!PyUnicode_Check(unicode)) {
14396 PyErr_BadArgument();
14397 return NULL;
14398 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014399 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014400 if (u == NULL)
14401 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014402 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014403 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014404 PyErr_NoMemory();
14405 return NULL;
14406 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014407 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014408 size *= sizeof(Py_UNICODE);
14409 copy = PyMem_Malloc(size);
14410 if (copy == NULL) {
14411 PyErr_NoMemory();
14412 return NULL;
14413 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014414 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014415 return copy;
14416}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014417
Georg Brandl66c221e2010-10-14 07:04:07 +000014418/* A _string module, to export formatter_parser and formatter_field_name_split
14419 to the string.Formatter class implemented in Python. */
14420
14421static PyMethodDef _string_methods[] = {
14422 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14423 METH_O, PyDoc_STR("split the argument as a field name")},
14424 {"formatter_parser", (PyCFunction) formatter_parser,
14425 METH_O, PyDoc_STR("parse the argument as a format string")},
14426 {NULL, NULL}
14427};
14428
14429static struct PyModuleDef _string_module = {
14430 PyModuleDef_HEAD_INIT,
14431 "_string",
14432 PyDoc_STR("string helper module"),
14433 0,
14434 _string_methods,
14435 NULL,
14436 NULL,
14437 NULL,
14438 NULL
14439};
14440
14441PyMODINIT_FUNC
14442PyInit__string(void)
14443{
14444 return PyModule_Create(&_string_module);
14445}
14446
14447
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014448#ifdef __cplusplus
14449}
14450#endif