blob: 2b90cfad726a0d081eda0beb02cb0d8cd14c5636 [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)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500494 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100495 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
Benjamin Petersonbac79492012-01-14 13:34:47 -0500767 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100768 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 {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001001 if (maxchar > MAX_UNICODE) {
1002 PyErr_SetString(PyExc_SystemError,
1003 "invalid maximum character passed to PyUnicode_New");
1004 return NULL;
1005 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001006 kind_state = PyUnicode_4BYTE_KIND;
1007 char_size = 4;
1008 if (sizeof(wchar_t) == 4)
1009 is_sharing = 1;
1010 }
1011
1012 /* Ensure we won't overflow the size. */
1013 if (size < 0) {
1014 PyErr_SetString(PyExc_SystemError,
1015 "Negative size passed to PyUnicode_New");
1016 return NULL;
1017 }
1018 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1019 return PyErr_NoMemory();
1020
1021 /* Duplicated allocation code from _PyObject_New() instead of a call to
1022 * PyObject_New() so we are able to allocate space for the object and
1023 * it's data buffer.
1024 */
1025 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1026 if (obj == NULL)
1027 return PyErr_NoMemory();
1028 obj = PyObject_INIT(obj, &PyUnicode_Type);
1029 if (obj == NULL)
1030 return NULL;
1031
1032 unicode = (PyCompactUnicodeObject *)obj;
1033 if (is_ascii)
1034 data = ((PyASCIIObject*)obj) + 1;
1035 else
1036 data = unicode + 1;
1037 _PyUnicode_LENGTH(unicode) = size;
1038 _PyUnicode_HASH(unicode) = -1;
1039 _PyUnicode_STATE(unicode).interned = 0;
1040 _PyUnicode_STATE(unicode).kind = kind_state;
1041 _PyUnicode_STATE(unicode).compact = 1;
1042 _PyUnicode_STATE(unicode).ready = 1;
1043 _PyUnicode_STATE(unicode).ascii = is_ascii;
1044 if (is_ascii) {
1045 ((char*)data)[size] = 0;
1046 _PyUnicode_WSTR(unicode) = NULL;
1047 }
1048 else if (kind_state == PyUnicode_1BYTE_KIND) {
1049 ((char*)data)[size] = 0;
1050 _PyUnicode_WSTR(unicode) = NULL;
1051 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001053 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054 }
1055 else {
1056 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001057 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001058 if (kind_state == PyUnicode_2BYTE_KIND)
1059 ((Py_UCS2*)data)[size] = 0;
1060 else /* kind_state == PyUnicode_4BYTE_KIND */
1061 ((Py_UCS4*)data)[size] = 0;
1062 if (is_sharing) {
1063 _PyUnicode_WSTR_LENGTH(unicode) = size;
1064 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1065 }
1066 else {
1067 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1068 _PyUnicode_WSTR(unicode) = NULL;
1069 }
1070 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01001071 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001072 return obj;
1073}
1074
1075#if SIZEOF_WCHAR_T == 2
1076/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1077 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001078 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001079
1080 This function assumes that unicode can hold one more code point than wstr
1081 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001082static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001083unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001084 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001085{
1086 const wchar_t *iter;
1087 Py_UCS4 *ucs4_out;
1088
Victor Stinner910337b2011-10-03 03:20:16 +02001089 assert(unicode != NULL);
1090 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001091 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1092 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1093
1094 for (iter = begin; iter < end; ) {
1095 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1096 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001097 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1098 && (iter+1) < end
1099 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001100 {
Victor Stinner551ac952011-11-29 22:58:13 +01001101 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001102 iter += 2;
1103 }
1104 else {
1105 *ucs4_out++ = *iter;
1106 iter++;
1107 }
1108 }
1109 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1110 _PyUnicode_GET_LENGTH(unicode)));
1111
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001112}
1113#endif
1114
Victor Stinnercd9950f2011-10-02 00:34:53 +02001115static int
Victor Stinner488fa492011-12-12 00:01:39 +01001116unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001117{
Victor Stinner488fa492011-12-12 00:01:39 +01001118 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001119 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001120 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001121 return -1;
1122 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001123 return 0;
1124}
1125
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001126static int
1127_copy_characters(PyObject *to, Py_ssize_t to_start,
1128 PyObject *from, Py_ssize_t from_start,
1129 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001130{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001131 unsigned int from_kind, to_kind;
1132 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001133 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001134
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001135 assert(PyUnicode_Check(from));
1136 assert(PyUnicode_Check(to));
1137 assert(PyUnicode_IS_READY(from));
1138 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001139
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001140 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1141 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1142 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001143
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001144 if (how_many == 0)
1145 return 0;
1146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001147 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001148 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001149 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001150 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001151
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001152#ifdef Py_DEBUG
1153 if (!check_maxchar
1154 && (from_kind > to_kind
1155 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001156 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001157 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1158 Py_UCS4 ch;
1159 Py_ssize_t i;
1160 for (i=0; i < how_many; i++) {
1161 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1162 assert(ch <= to_maxchar);
1163 }
1164 }
1165#endif
1166 fast = (from_kind == to_kind);
1167 if (check_maxchar
1168 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1169 {
1170 /* deny latin1 => ascii */
1171 fast = 0;
1172 }
1173
1174 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001175 Py_MEMCPY((char*)to_data + to_kind * to_start,
1176 (char*)from_data + from_kind * from_start,
1177 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001178 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001179 else if (from_kind == PyUnicode_1BYTE_KIND
1180 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001181 {
1182 _PyUnicode_CONVERT_BYTES(
1183 Py_UCS1, Py_UCS2,
1184 PyUnicode_1BYTE_DATA(from) + from_start,
1185 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1186 PyUnicode_2BYTE_DATA(to) + to_start
1187 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001188 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001189 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001190 && to_kind == PyUnicode_4BYTE_KIND)
1191 {
1192 _PyUnicode_CONVERT_BYTES(
1193 Py_UCS1, Py_UCS4,
1194 PyUnicode_1BYTE_DATA(from) + from_start,
1195 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1196 PyUnicode_4BYTE_DATA(to) + to_start
1197 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001198 }
1199 else if (from_kind == PyUnicode_2BYTE_KIND
1200 && to_kind == PyUnicode_4BYTE_KIND)
1201 {
1202 _PyUnicode_CONVERT_BYTES(
1203 Py_UCS2, Py_UCS4,
1204 PyUnicode_2BYTE_DATA(from) + from_start,
1205 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1206 PyUnicode_4BYTE_DATA(to) + to_start
1207 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001208 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001209 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001210 /* check if max_char(from substring) <= max_char(to) */
1211 if (from_kind > to_kind
1212 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001213 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001214 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001215 /* slow path to check for character overflow */
1216 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001217 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001218 Py_ssize_t i;
1219
Victor Stinner56c161a2011-10-06 02:47:11 +02001220#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001221 for (i=0; i < how_many; i++) {
1222 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001223 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001224 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1225 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001226#else
1227 if (!check_maxchar) {
1228 for (i=0; i < how_many; i++) {
1229 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1230 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1231 }
1232 }
1233 else {
1234 for (i=0; i < how_many; i++) {
1235 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1236 if (ch > to_maxchar)
1237 return 1;
1238 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1239 }
1240 }
1241#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001242 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001243 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001244 assert(0 && "inconsistent state");
1245 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001246 }
1247 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001248 return 0;
1249}
1250
1251static void
1252copy_characters(PyObject *to, Py_ssize_t to_start,
1253 PyObject *from, Py_ssize_t from_start,
1254 Py_ssize_t how_many)
1255{
1256 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1257}
1258
1259Py_ssize_t
1260PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1261 PyObject *from, Py_ssize_t from_start,
1262 Py_ssize_t how_many)
1263{
1264 int err;
1265
1266 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1267 PyErr_BadInternalCall();
1268 return -1;
1269 }
1270
Benjamin Petersonbac79492012-01-14 13:34:47 -05001271 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001272 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001273 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001274 return -1;
1275
1276 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1277 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1278 PyErr_Format(PyExc_SystemError,
1279 "Cannot write %zi characters at %zi "
1280 "in a string of %zi characters",
1281 how_many, to_start, PyUnicode_GET_LENGTH(to));
1282 return -1;
1283 }
1284
1285 if (how_many == 0)
1286 return 0;
1287
Victor Stinner488fa492011-12-12 00:01:39 +01001288 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001289 return -1;
1290
1291 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1292 if (err) {
1293 PyErr_Format(PyExc_SystemError,
1294 "Cannot copy %s characters "
1295 "into a string of %s characters",
1296 unicode_kind_name(from),
1297 unicode_kind_name(to));
1298 return -1;
1299 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001300 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001301}
1302
Victor Stinner17222162011-09-28 22:15:37 +02001303/* Find the maximum code point and count the number of surrogate pairs so a
1304 correct string length can be computed before converting a string to UCS4.
1305 This function counts single surrogates as a character and not as a pair.
1306
1307 Return 0 on success, or -1 on error. */
1308static int
1309find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1310 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001311{
1312 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001313 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001314
Victor Stinnerc53be962011-10-02 21:33:54 +02001315 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316 *num_surrogates = 0;
1317 *maxchar = 0;
1318
1319 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001321 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1322 && (iter+1) < end
1323 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001325 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001326 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001327 iter += 2;
1328 }
1329 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001330#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001331 {
1332 ch = *iter;
1333 iter++;
1334 }
1335 if (ch > *maxchar) {
1336 *maxchar = ch;
1337 if (*maxchar > MAX_UNICODE) {
1338 PyErr_Format(PyExc_ValueError,
1339 "character U+%x is not in range [U+0000; U+10ffff]",
1340 ch);
1341 return -1;
1342 }
1343 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001344 }
1345 return 0;
1346}
1347
1348#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001349static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350#endif
1351
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001352int
1353_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001354{
1355 wchar_t *end;
1356 Py_UCS4 maxchar = 0;
1357 Py_ssize_t num_surrogates;
1358#if SIZEOF_WCHAR_T == 2
1359 Py_ssize_t length_wo_surrogates;
1360#endif
1361
Georg Brandl7597add2011-10-05 16:36:47 +02001362 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001363 strings were created using _PyObject_New() and where no canonical
1364 representation (the str field) has been set yet aka strings
1365 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001366 assert(_PyUnicode_CHECK(unicode));
1367 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001368 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001369 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001370 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001371 /* Actually, it should neither be interned nor be anything else: */
1372 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001373
1374#ifdef Py_DEBUG
1375 ++unicode_ready_calls;
1376#endif
1377
1378 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001379 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001380 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001381 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001382
1383 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001384 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1385 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001386 PyErr_NoMemory();
1387 return -1;
1388 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001389 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001390 _PyUnicode_WSTR(unicode), end,
1391 PyUnicode_1BYTE_DATA(unicode));
1392 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1393 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1394 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1395 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001396 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001397 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001398 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001399 }
1400 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001401 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001402 _PyUnicode_UTF8(unicode) = NULL;
1403 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001404 }
1405 PyObject_FREE(_PyUnicode_WSTR(unicode));
1406 _PyUnicode_WSTR(unicode) = NULL;
1407 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1408 }
1409 /* In this case we might have to convert down from 4-byte native
1410 wchar_t to 2-byte unicode. */
1411 else if (maxchar < 65536) {
1412 assert(num_surrogates == 0 &&
1413 "FindMaxCharAndNumSurrogatePairs() messed up");
1414
Victor Stinner506f5922011-09-28 22:34:18 +02001415#if SIZEOF_WCHAR_T == 2
1416 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001417 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001418 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1419 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1420 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001421 _PyUnicode_UTF8(unicode) = NULL;
1422 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001423#else
1424 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001425 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001426 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001427 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001428 PyErr_NoMemory();
1429 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001430 }
Victor Stinner506f5922011-09-28 22:34:18 +02001431 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1432 _PyUnicode_WSTR(unicode), end,
1433 PyUnicode_2BYTE_DATA(unicode));
1434 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1435 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1436 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001437 _PyUnicode_UTF8(unicode) = NULL;
1438 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001439 PyObject_FREE(_PyUnicode_WSTR(unicode));
1440 _PyUnicode_WSTR(unicode) = NULL;
1441 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1442#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001443 }
1444 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1445 else {
1446#if SIZEOF_WCHAR_T == 2
1447 /* in case the native representation is 2-bytes, we need to allocate a
1448 new normalized 4-byte version. */
1449 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001450 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1451 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001452 PyErr_NoMemory();
1453 return -1;
1454 }
1455 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1456 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001457 _PyUnicode_UTF8(unicode) = NULL;
1458 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001459 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1460 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001461 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001462 PyObject_FREE(_PyUnicode_WSTR(unicode));
1463 _PyUnicode_WSTR(unicode) = NULL;
1464 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1465#else
1466 assert(num_surrogates == 0);
1467
Victor Stinnerc3c74152011-10-02 20:39:55 +02001468 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001469 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001470 _PyUnicode_UTF8(unicode) = NULL;
1471 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001472 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1473#endif
1474 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1475 }
1476 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001477 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001478 return 0;
1479}
1480
Alexander Belopolsky40018472011-02-26 01:02:56 +00001481static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001482unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001483{
Walter Dörwald16807132007-05-25 13:52:07 +00001484 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001485 case SSTATE_NOT_INTERNED:
1486 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001487
Benjamin Peterson29060642009-01-31 22:14:21 +00001488 case SSTATE_INTERNED_MORTAL:
1489 /* revive dead object temporarily for DelItem */
1490 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001491 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001492 Py_FatalError(
1493 "deletion of interned string failed");
1494 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001495
Benjamin Peterson29060642009-01-31 22:14:21 +00001496 case SSTATE_INTERNED_IMMORTAL:
1497 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001498
Benjamin Peterson29060642009-01-31 22:14:21 +00001499 default:
1500 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001501 }
1502
Victor Stinner03490912011-10-03 23:45:12 +02001503 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001504 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001505 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001506 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001507 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1508 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001509
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001510 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001511}
1512
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001513#ifdef Py_DEBUG
1514static int
1515unicode_is_singleton(PyObject *unicode)
1516{
1517 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1518 if (unicode == unicode_empty)
1519 return 1;
1520 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1521 {
1522 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1523 if (ch < 256 && unicode_latin1[ch] == unicode)
1524 return 1;
1525 }
1526 return 0;
1527}
1528#endif
1529
Alexander Belopolsky40018472011-02-26 01:02:56 +00001530static int
Victor Stinner488fa492011-12-12 00:01:39 +01001531unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001532{
Victor Stinner488fa492011-12-12 00:01:39 +01001533 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001534 if (Py_REFCNT(unicode) != 1)
1535 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001536 if (_PyUnicode_HASH(unicode) != -1)
1537 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001538 if (PyUnicode_CHECK_INTERNED(unicode))
1539 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001540 if (!PyUnicode_CheckExact(unicode))
1541 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001542#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001543 /* singleton refcount is greater than 1 */
1544 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001545#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001546 return 1;
1547}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001548
Victor Stinnerfe226c02011-10-03 03:52:20 +02001549static int
1550unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1551{
1552 PyObject *unicode;
1553 Py_ssize_t old_length;
1554
1555 assert(p_unicode != NULL);
1556 unicode = *p_unicode;
1557
1558 assert(unicode != NULL);
1559 assert(PyUnicode_Check(unicode));
1560 assert(0 <= length);
1561
Victor Stinner910337b2011-10-03 03:20:16 +02001562 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001563 old_length = PyUnicode_WSTR_LENGTH(unicode);
1564 else
1565 old_length = PyUnicode_GET_LENGTH(unicode);
1566 if (old_length == length)
1567 return 0;
1568
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001569 if (length == 0) {
1570 Py_DECREF(*p_unicode);
1571 *p_unicode = unicode_empty;
1572 Py_INCREF(*p_unicode);
1573 return 0;
1574 }
1575
Victor Stinner488fa492011-12-12 00:01:39 +01001576 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001577 PyObject *copy = resize_copy(unicode, length);
1578 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001579 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001580 Py_DECREF(*p_unicode);
1581 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001582 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001583 }
1584
Victor Stinnerfe226c02011-10-03 03:52:20 +02001585 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001586 PyObject *new_unicode = resize_compact(unicode, length);
1587 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001588 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001589 *p_unicode = new_unicode;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001590 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001591 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001592 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001593 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001594}
1595
Alexander Belopolsky40018472011-02-26 01:02:56 +00001596int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001597PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001598{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001599 PyObject *unicode;
1600 if (p_unicode == NULL) {
1601 PyErr_BadInternalCall();
1602 return -1;
1603 }
1604 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001605 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001606 {
1607 PyErr_BadInternalCall();
1608 return -1;
1609 }
1610 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001611}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001612
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001613static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001614unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001615{
1616 PyObject *result;
1617 assert(PyUnicode_IS_READY(*p_unicode));
1618 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1619 return 0;
1620 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1621 maxchar);
1622 if (result == NULL)
1623 return -1;
1624 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1625 PyUnicode_GET_LENGTH(*p_unicode));
1626 Py_DECREF(*p_unicode);
1627 *p_unicode = result;
1628 return 0;
1629}
1630
1631static int
1632unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1633 Py_UCS4 ch)
1634{
Victor Stinner15e9ed22012-02-22 13:36:20 +01001635 assert(ch <= MAX_UNICODE);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001636 if (unicode_widen(p_unicode, ch) < 0)
1637 return -1;
1638 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1639 PyUnicode_DATA(*p_unicode),
1640 (*pos)++, ch);
1641 return 0;
1642}
1643
Victor Stinnerc5166102012-02-22 13:55:02 +01001644/* Copy a ASCII or latin1 char* string into a Python Unicode string.
1645 Return the length of the input string.
1646
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001647 WARNING: The function doesn't copy the terminating null character and
1648 doesn't check the maximum character (may write a latin1 character in an
1649 ASCII string). */
Victor Stinnerc5166102012-02-22 13:55:02 +01001650static Py_ssize_t
1651unicode_write_cstr(PyObject *unicode, Py_ssize_t index, const char *str)
1652{
1653 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1654 void *data = PyUnicode_DATA(unicode);
1655
1656 switch (kind) {
1657 case PyUnicode_1BYTE_KIND: {
1658 Py_ssize_t len = strlen(str);
1659 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001660 memcpy((char *) data + index, str, len);
Victor Stinnerc5166102012-02-22 13:55:02 +01001661 return len;
1662 }
1663 case PyUnicode_2BYTE_KIND: {
1664 Py_UCS2 *start = (Py_UCS2 *)data + index;
1665 Py_UCS2 *ucs2 = start;
1666 assert(index <= PyUnicode_GET_LENGTH(unicode));
1667
1668 for (; *str; ++ucs2, ++str)
1669 *ucs2 = (Py_UCS2)*str;
1670
1671 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
1672 return ucs2 - start;
1673 }
1674 default: {
1675 Py_UCS4 *start = (Py_UCS4 *)data + index;
1676 Py_UCS4 *ucs4 = start;
1677 assert(kind == PyUnicode_4BYTE_KIND);
1678 assert(index <= PyUnicode_GET_LENGTH(unicode));
1679
1680 for (; *str; ++ucs4, ++str)
1681 *ucs4 = (Py_UCS4)*str;
1682
1683 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
1684 return ucs4 - start;
1685 }
1686 }
1687}
1688
1689
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001690static PyObject*
1691get_latin1_char(unsigned char ch)
1692{
Victor Stinnera464fc12011-10-02 20:39:30 +02001693 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001694 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001695 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001696 if (!unicode)
1697 return NULL;
1698 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001699 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001700 unicode_latin1[ch] = unicode;
1701 }
1702 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001703 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001704}
1705
Alexander Belopolsky40018472011-02-26 01:02:56 +00001706PyObject *
1707PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001708{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001709 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001710 Py_UCS4 maxchar = 0;
1711 Py_ssize_t num_surrogates;
1712
1713 if (u == NULL)
1714 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001715
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001716 /* If the Unicode data is known at construction time, we can apply
1717 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001718
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001719 /* Optimization for empty strings */
1720 if (size == 0 && unicode_empty != NULL) {
1721 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001722 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001723 }
Tim Petersced69f82003-09-16 20:30:58 +00001724
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001725 /* Single character Unicode objects in the Latin-1 range are
1726 shared when using this constructor */
1727 if (size == 1 && *u < 256)
1728 return get_latin1_char((unsigned char)*u);
1729
1730 /* If not empty and not single character, copy the Unicode data
1731 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001732 if (find_maxchar_surrogates(u, u + size,
1733 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001734 return NULL;
1735
Victor Stinner8faf8212011-12-08 22:14:11 +01001736 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001737 if (!unicode)
1738 return NULL;
1739
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001740 switch (PyUnicode_KIND(unicode)) {
1741 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001742 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001743 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1744 break;
1745 case PyUnicode_2BYTE_KIND:
1746#if Py_UNICODE_SIZE == 2
1747 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1748#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001749 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001750 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1751#endif
1752 break;
1753 case PyUnicode_4BYTE_KIND:
1754#if SIZEOF_WCHAR_T == 2
1755 /* This is the only case which has to process surrogates, thus
1756 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001757 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758#else
1759 assert(num_surrogates == 0);
1760 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1761#endif
1762 break;
1763 default:
1764 assert(0 && "Impossible state");
1765 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001766
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001767 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001768}
1769
Alexander Belopolsky40018472011-02-26 01:02:56 +00001770PyObject *
1771PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001772{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001773 if (size < 0) {
1774 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001775 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001776 return NULL;
1777 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001778 if (u != NULL)
1779 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1780 else
1781 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001782}
1783
Alexander Belopolsky40018472011-02-26 01:02:56 +00001784PyObject *
1785PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001786{
1787 size_t size = strlen(u);
1788 if (size > PY_SSIZE_T_MAX) {
1789 PyErr_SetString(PyExc_OverflowError, "input too long");
1790 return NULL;
1791 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001792 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001793}
1794
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001795PyObject *
1796_PyUnicode_FromId(_Py_Identifier *id)
1797{
1798 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001799 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1800 strlen(id->string),
1801 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001802 if (!id->object)
1803 return NULL;
1804 PyUnicode_InternInPlace(&id->object);
1805 assert(!id->next);
1806 id->next = static_strings;
1807 static_strings = id;
1808 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001809 return id->object;
1810}
1811
1812void
1813_PyUnicode_ClearStaticStrings()
1814{
1815 _Py_Identifier *i;
1816 for (i = static_strings; i; i = i->next) {
1817 Py_DECREF(i->object);
1818 i->object = NULL;
1819 i->next = NULL;
1820 }
1821}
1822
Benjamin Peterson0df54292012-03-26 14:50:32 -04001823/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001824
Victor Stinnere57b1c02011-09-28 22:20:48 +02001825static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001826unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001827{
Victor Stinner785938e2011-12-11 20:09:03 +01001828 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001829 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001830#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001831 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001832#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001833 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001834 }
Victor Stinner785938e2011-12-11 20:09:03 +01001835 unicode = PyUnicode_New(size, 127);
1836 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001837 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001838 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1839 assert(_PyUnicode_CheckConsistency(unicode, 1));
1840 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001841}
1842
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001843static Py_UCS4
1844kind_maxchar_limit(unsigned int kind)
1845{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001846 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001847 case PyUnicode_1BYTE_KIND:
1848 return 0x80;
1849 case PyUnicode_2BYTE_KIND:
1850 return 0x100;
1851 case PyUnicode_4BYTE_KIND:
1852 return 0x10000;
1853 default:
1854 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001855 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001856 }
1857}
1858
Victor Stinner702c7342011-10-05 13:50:52 +02001859static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001860_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001861{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001862 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001863 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001864
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001865 if (size == 0) {
1866 Py_INCREF(unicode_empty);
1867 return unicode_empty;
1868 }
1869 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001870 if (size == 1)
1871 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001872
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001873 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001874 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001875 if (!res)
1876 return NULL;
1877 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001878 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001879 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001880}
1881
Victor Stinnere57b1c02011-09-28 22:20:48 +02001882static PyObject*
1883_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001884{
1885 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001886 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001887
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001888 if (size == 0) {
1889 Py_INCREF(unicode_empty);
1890 return unicode_empty;
1891 }
1892 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001893 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001894 return get_latin1_char((unsigned char)u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001895
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001896 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001897 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001898 if (!res)
1899 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001900 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001901 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001902 else {
1903 _PyUnicode_CONVERT_BYTES(
1904 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1905 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001906 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001907 return res;
1908}
1909
Victor Stinnere57b1c02011-09-28 22:20:48 +02001910static PyObject*
1911_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001912{
1913 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001914 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001915
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001916 if (size == 0) {
1917 Py_INCREF(unicode_empty);
1918 return unicode_empty;
1919 }
1920 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001921 if (size == 1 && u[0] < 256)
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001922 return get_latin1_char((unsigned char)u[0]);
1923
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001924 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001925 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001926 if (!res)
1927 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001928 if (max_char < 256)
1929 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1930 PyUnicode_1BYTE_DATA(res));
1931 else if (max_char < 0x10000)
1932 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1933 PyUnicode_2BYTE_DATA(res));
1934 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001935 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001936 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001937 return res;
1938}
1939
1940PyObject*
1941PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1942{
Victor Stinnercfed46e2011-11-22 01:29:14 +01001943 if (size < 0) {
1944 PyErr_SetString(PyExc_ValueError, "size must be positive");
1945 return NULL;
1946 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06001947 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001948 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001949 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001950 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001951 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001952 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001953 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001954 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02001955 PyErr_SetString(PyExc_SystemError, "invalid kind");
1956 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001957 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001958}
1959
Victor Stinnerece58de2012-04-23 23:36:38 +02001960Py_UCS4
1961_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
1962{
1963 enum PyUnicode_Kind kind;
1964 void *startptr, *endptr;
1965
1966 assert(PyUnicode_IS_READY(unicode));
1967 assert(0 <= start);
1968 assert(end <= PyUnicode_GET_LENGTH(unicode));
1969 assert(start <= end);
1970
1971 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
1972 return PyUnicode_MAX_CHAR_VALUE(unicode);
1973
1974 if (start == end)
1975 return 127;
1976
1977 kind = PyUnicode_KIND(unicode);
1978 startptr = PyUnicode_DATA(unicode);
1979 endptr = (char*)startptr + end * kind;
1980 if (start)
1981 startptr = (char*)startptr + start * kind;
1982 switch(kind)
1983 {
1984 case PyUnicode_1BYTE_KIND: return ucs1lib_find_max_char(startptr, endptr);
1985 case PyUnicode_2BYTE_KIND: return ucs2lib_find_max_char(startptr, endptr);
1986 default:
1987 case PyUnicode_4BYTE_KIND: return ucs4lib_find_max_char(startptr, endptr);
1988 }
1989}
1990
Victor Stinner25a4b292011-10-06 12:31:55 +02001991/* Ensure that a string uses the most efficient storage, if it is not the
1992 case: create a new string with of the right kind. Write NULL into *p_unicode
1993 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001994static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001995unicode_adjust_maxchar(PyObject **p_unicode)
1996{
1997 PyObject *unicode, *copy;
1998 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001999 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002000 unsigned int kind;
2001
2002 assert(p_unicode != NULL);
2003 unicode = *p_unicode;
2004 assert(PyUnicode_IS_READY(unicode));
2005 if (PyUnicode_IS_ASCII(unicode))
2006 return;
2007
2008 len = PyUnicode_GET_LENGTH(unicode);
2009 kind = PyUnicode_KIND(unicode);
2010 if (kind == PyUnicode_1BYTE_KIND) {
2011 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002012 max_char = ucs1lib_find_max_char(u, u + len);
2013 if (max_char >= 128)
2014 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002015 }
2016 else if (kind == PyUnicode_2BYTE_KIND) {
2017 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002018 max_char = ucs2lib_find_max_char(u, u + len);
2019 if (max_char >= 256)
2020 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002021 }
2022 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002023 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002024 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002025 max_char = ucs4lib_find_max_char(u, u + len);
2026 if (max_char >= 0x10000)
2027 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002028 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002029 copy = PyUnicode_New(len, max_char);
2030 copy_characters(copy, 0, unicode, 0, len);
2031 Py_DECREF(unicode);
2032 *p_unicode = copy;
2033}
2034
Victor Stinner034f6cf2011-09-30 02:26:44 +02002035PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002036_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002037{
Victor Stinner87af4f22011-11-21 23:03:47 +01002038 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002039 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002040
Victor Stinner034f6cf2011-09-30 02:26:44 +02002041 if (!PyUnicode_Check(unicode)) {
2042 PyErr_BadInternalCall();
2043 return NULL;
2044 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002045 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002046 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002047
Victor Stinner87af4f22011-11-21 23:03:47 +01002048 length = PyUnicode_GET_LENGTH(unicode);
2049 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002050 if (!copy)
2051 return NULL;
2052 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2053
Victor Stinner87af4f22011-11-21 23:03:47 +01002054 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2055 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002056 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002057 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002058}
2059
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002060
Victor Stinnerbc603d12011-10-02 01:00:40 +02002061/* Widen Unicode objects to larger buffers. Don't write terminating null
2062 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002063
2064void*
2065_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2066{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002067 Py_ssize_t len;
2068 void *result;
2069 unsigned int skind;
2070
Benjamin Petersonbac79492012-01-14 13:34:47 -05002071 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002072 return NULL;
2073
2074 len = PyUnicode_GET_LENGTH(s);
2075 skind = PyUnicode_KIND(s);
2076 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002077 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002078 return NULL;
2079 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002080 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002081 case PyUnicode_2BYTE_KIND:
2082 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2083 if (!result)
2084 return PyErr_NoMemory();
2085 assert(skind == PyUnicode_1BYTE_KIND);
2086 _PyUnicode_CONVERT_BYTES(
2087 Py_UCS1, Py_UCS2,
2088 PyUnicode_1BYTE_DATA(s),
2089 PyUnicode_1BYTE_DATA(s) + len,
2090 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002091 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002092 case PyUnicode_4BYTE_KIND:
2093 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2094 if (!result)
2095 return PyErr_NoMemory();
2096 if (skind == PyUnicode_2BYTE_KIND) {
2097 _PyUnicode_CONVERT_BYTES(
2098 Py_UCS2, Py_UCS4,
2099 PyUnicode_2BYTE_DATA(s),
2100 PyUnicode_2BYTE_DATA(s) + len,
2101 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002102 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002103 else {
2104 assert(skind == PyUnicode_1BYTE_KIND);
2105 _PyUnicode_CONVERT_BYTES(
2106 Py_UCS1, Py_UCS4,
2107 PyUnicode_1BYTE_DATA(s),
2108 PyUnicode_1BYTE_DATA(s) + len,
2109 result);
2110 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002111 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002112 default:
2113 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002114 }
Victor Stinner01698042011-10-04 00:04:26 +02002115 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002116 return NULL;
2117}
2118
2119static Py_UCS4*
2120as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2121 int copy_null)
2122{
2123 int kind;
2124 void *data;
2125 Py_ssize_t len, targetlen;
2126 if (PyUnicode_READY(string) == -1)
2127 return NULL;
2128 kind = PyUnicode_KIND(string);
2129 data = PyUnicode_DATA(string);
2130 len = PyUnicode_GET_LENGTH(string);
2131 targetlen = len;
2132 if (copy_null)
2133 targetlen++;
2134 if (!target) {
2135 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2136 PyErr_NoMemory();
2137 return NULL;
2138 }
2139 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2140 if (!target) {
2141 PyErr_NoMemory();
2142 return NULL;
2143 }
2144 }
2145 else {
2146 if (targetsize < targetlen) {
2147 PyErr_Format(PyExc_SystemError,
2148 "string is longer than the buffer");
2149 if (copy_null && 0 < targetsize)
2150 target[0] = 0;
2151 return NULL;
2152 }
2153 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002154 if (kind == PyUnicode_1BYTE_KIND) {
2155 Py_UCS1 *start = (Py_UCS1 *) data;
2156 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002157 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002158 else if (kind == PyUnicode_2BYTE_KIND) {
2159 Py_UCS2 *start = (Py_UCS2 *) data;
2160 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2161 }
2162 else {
2163 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002164 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002165 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002166 if (copy_null)
2167 target[len] = 0;
2168 return target;
2169}
2170
2171Py_UCS4*
2172PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2173 int copy_null)
2174{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002175 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002176 PyErr_BadInternalCall();
2177 return NULL;
2178 }
2179 return as_ucs4(string, target, targetsize, copy_null);
2180}
2181
2182Py_UCS4*
2183PyUnicode_AsUCS4Copy(PyObject *string)
2184{
2185 return as_ucs4(string, NULL, 0, 1);
2186}
2187
2188#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002189
Alexander Belopolsky40018472011-02-26 01:02:56 +00002190PyObject *
2191PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002192{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002193 if (w == NULL) {
Victor Stinner382955f2011-12-11 21:44:00 +01002194 if (size == 0) {
2195 Py_INCREF(unicode_empty);
2196 return unicode_empty;
2197 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002198 PyErr_BadInternalCall();
2199 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002200 }
2201
Martin v. Löwis790465f2008-04-05 20:41:37 +00002202 if (size == -1) {
2203 size = wcslen(w);
2204 }
2205
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002206 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002207}
2208
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002209#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002210
Walter Dörwald346737f2007-05-31 10:44:43 +00002211static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002212makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2213 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002214{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002215 *fmt++ = '%';
2216 if (width) {
2217 if (zeropad)
2218 *fmt++ = '0';
2219 fmt += sprintf(fmt, "%d", width);
2220 }
2221 if (precision)
2222 fmt += sprintf(fmt, ".%d", precision);
2223 if (longflag)
2224 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002225 else if (longlongflag) {
2226 /* longlongflag should only ever be nonzero on machines with
2227 HAVE_LONG_LONG defined */
2228#ifdef HAVE_LONG_LONG
2229 char *f = PY_FORMAT_LONG_LONG;
2230 while (*f)
2231 *fmt++ = *f++;
2232#else
2233 /* we shouldn't ever get here */
2234 assert(0);
2235 *fmt++ = 'l';
2236#endif
2237 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002238 else if (size_tflag) {
2239 char *f = PY_FORMAT_SIZE_T;
2240 while (*f)
2241 *fmt++ = *f++;
2242 }
2243 *fmt++ = c;
2244 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002245}
2246
Victor Stinner96865452011-03-01 23:44:09 +00002247/* helper for PyUnicode_FromFormatV() */
2248
2249static const char*
2250parse_format_flags(const char *f,
2251 int *p_width, int *p_precision,
2252 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2253{
2254 int width, precision, longflag, longlongflag, size_tflag;
2255
2256 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2257 f++;
2258 width = 0;
2259 while (Py_ISDIGIT((unsigned)*f))
2260 width = (width*10) + *f++ - '0';
2261 precision = 0;
2262 if (*f == '.') {
2263 f++;
2264 while (Py_ISDIGIT((unsigned)*f))
2265 precision = (precision*10) + *f++ - '0';
2266 if (*f == '%') {
2267 /* "%.3%s" => f points to "3" */
2268 f--;
2269 }
2270 }
2271 if (*f == '\0') {
2272 /* bogus format "%.1" => go backward, f points to "1" */
2273 f--;
2274 }
2275 if (p_width != NULL)
2276 *p_width = width;
2277 if (p_precision != NULL)
2278 *p_precision = precision;
2279
2280 /* Handle %ld, %lu, %lld and %llu. */
2281 longflag = 0;
2282 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002283 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002284
2285 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002286 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002287 longflag = 1;
2288 ++f;
2289 }
2290#ifdef HAVE_LONG_LONG
2291 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002292 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002293 longlongflag = 1;
2294 f += 2;
2295 }
2296#endif
2297 }
2298 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002299 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002300 size_tflag = 1;
2301 ++f;
2302 }
2303 if (p_longflag != NULL)
2304 *p_longflag = longflag;
2305 if (p_longlongflag != NULL)
2306 *p_longlongflag = longlongflag;
2307 if (p_size_tflag != NULL)
2308 *p_size_tflag = size_tflag;
2309 return f;
2310}
2311
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002312/* maximum number of characters required for output of %ld. 21 characters
2313 allows for 64-bit integers (in decimal) and an optional sign. */
2314#define MAX_LONG_CHARS 21
2315/* maximum number of characters required for output of %lld.
2316 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2317 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2318#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2319
Walter Dörwaldd2034312007-05-18 16:29:38 +00002320PyObject *
2321PyUnicode_FromFormatV(const char *format, va_list vargs)
2322{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002323 va_list count;
2324 Py_ssize_t callcount = 0;
2325 PyObject **callresults = NULL;
2326 PyObject **callresult = NULL;
2327 Py_ssize_t n = 0;
2328 int width = 0;
2329 int precision = 0;
2330 int zeropad;
2331 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002332 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002333 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002334 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002335 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2336 Py_UCS4 argmaxchar;
2337 Py_ssize_t numbersize = 0;
2338 char *numberresults = NULL;
2339 char *numberresult = NULL;
2340 Py_ssize_t i;
2341 int kind;
2342 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002343
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002344 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002345 /* step 1: count the number of %S/%R/%A/%s format specifications
2346 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2347 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002348 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002349 * also estimate a upper bound for all the number formats in the string,
2350 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002351 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002352 for (f = format; *f; f++) {
2353 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002354 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002355 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2356 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2357 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2358 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002359
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002360 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002361#ifdef HAVE_LONG_LONG
2362 if (longlongflag) {
2363 if (width < MAX_LONG_LONG_CHARS)
2364 width = MAX_LONG_LONG_CHARS;
2365 }
2366 else
2367#endif
2368 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2369 including sign. Decimal takes the most space. This
2370 isn't enough for octal. If a width is specified we
2371 need more (which we allocate later). */
2372 if (width < MAX_LONG_CHARS)
2373 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002374
2375 /* account for the size + '\0' to separate numbers
2376 inside of the numberresults buffer */
2377 numbersize += (width + 1);
2378 }
2379 }
2380 else if ((unsigned char)*f > 127) {
2381 PyErr_Format(PyExc_ValueError,
2382 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2383 "string, got a non-ASCII byte: 0x%02x",
2384 (unsigned char)*f);
2385 return NULL;
2386 }
2387 }
2388 /* step 2: allocate memory for the results of
2389 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2390 if (callcount) {
2391 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2392 if (!callresults) {
2393 PyErr_NoMemory();
2394 return NULL;
2395 }
2396 callresult = callresults;
2397 }
2398 /* step 2.5: allocate memory for the results of formating numbers */
2399 if (numbersize) {
2400 numberresults = PyObject_Malloc(numbersize);
2401 if (!numberresults) {
2402 PyErr_NoMemory();
2403 goto fail;
2404 }
2405 numberresult = numberresults;
2406 }
2407
2408 /* step 3: format numbers and figure out how large a buffer we need */
2409 for (f = format; *f; f++) {
2410 if (*f == '%') {
2411 const char* p;
2412 int longflag;
2413 int longlongflag;
2414 int size_tflag;
2415 int numprinted;
2416
2417 p = f;
2418 zeropad = (f[1] == '0');
2419 f = parse_format_flags(f, &width, &precision,
2420 &longflag, &longlongflag, &size_tflag);
2421 switch (*f) {
2422 case 'c':
2423 {
2424 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002425 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002426 n++;
2427 break;
2428 }
2429 case '%':
2430 n++;
2431 break;
2432 case 'i':
2433 case 'd':
2434 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2435 width, precision, *f);
2436 if (longflag)
2437 numprinted = sprintf(numberresult, fmt,
2438 va_arg(count, long));
2439#ifdef HAVE_LONG_LONG
2440 else if (longlongflag)
2441 numprinted = sprintf(numberresult, fmt,
2442 va_arg(count, PY_LONG_LONG));
2443#endif
2444 else if (size_tflag)
2445 numprinted = sprintf(numberresult, fmt,
2446 va_arg(count, Py_ssize_t));
2447 else
2448 numprinted = sprintf(numberresult, fmt,
2449 va_arg(count, int));
2450 n += numprinted;
2451 /* advance by +1 to skip over the '\0' */
2452 numberresult += (numprinted + 1);
2453 assert(*(numberresult - 1) == '\0');
2454 assert(*(numberresult - 2) != '\0');
2455 assert(numprinted >= 0);
2456 assert(numberresult <= numberresults + numbersize);
2457 break;
2458 case 'u':
2459 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2460 width, precision, 'u');
2461 if (longflag)
2462 numprinted = sprintf(numberresult, fmt,
2463 va_arg(count, unsigned long));
2464#ifdef HAVE_LONG_LONG
2465 else if (longlongflag)
2466 numprinted = sprintf(numberresult, fmt,
2467 va_arg(count, unsigned PY_LONG_LONG));
2468#endif
2469 else if (size_tflag)
2470 numprinted = sprintf(numberresult, fmt,
2471 va_arg(count, size_t));
2472 else
2473 numprinted = sprintf(numberresult, fmt,
2474 va_arg(count, unsigned int));
2475 n += numprinted;
2476 numberresult += (numprinted + 1);
2477 assert(*(numberresult - 1) == '\0');
2478 assert(*(numberresult - 2) != '\0');
2479 assert(numprinted >= 0);
2480 assert(numberresult <= numberresults + numbersize);
2481 break;
2482 case 'x':
2483 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2484 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2485 n += numprinted;
2486 numberresult += (numprinted + 1);
2487 assert(*(numberresult - 1) == '\0');
2488 assert(*(numberresult - 2) != '\0');
2489 assert(numprinted >= 0);
2490 assert(numberresult <= numberresults + numbersize);
2491 break;
2492 case 'p':
2493 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2494 /* %p is ill-defined: ensure leading 0x. */
2495 if (numberresult[1] == 'X')
2496 numberresult[1] = 'x';
2497 else if (numberresult[1] != 'x') {
2498 memmove(numberresult + 2, numberresult,
2499 strlen(numberresult) + 1);
2500 numberresult[0] = '0';
2501 numberresult[1] = 'x';
2502 numprinted += 2;
2503 }
2504 n += numprinted;
2505 numberresult += (numprinted + 1);
2506 assert(*(numberresult - 1) == '\0');
2507 assert(*(numberresult - 2) != '\0');
2508 assert(numprinted >= 0);
2509 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002510 break;
2511 case 's':
2512 {
2513 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002514 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002515 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002516 if (!str)
2517 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002518 /* since PyUnicode_DecodeUTF8 returns already flexible
2519 unicode objects, there is no need to call ready on them */
2520 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002521 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002522 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002523 /* Remember the str and switch to the next slot */
2524 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002525 break;
2526 }
2527 case 'U':
2528 {
2529 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002530 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002531 if (PyUnicode_READY(obj) == -1)
2532 goto fail;
2533 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002534 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002535 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002536 break;
2537 }
2538 case 'V':
2539 {
2540 PyObject *obj = va_arg(count, PyObject *);
2541 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002542 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002543 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002544 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002545 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002546 if (PyUnicode_READY(obj) == -1)
2547 goto fail;
2548 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002549 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002550 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002551 *callresult++ = NULL;
2552 }
2553 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002554 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002555 if (!str_obj)
2556 goto fail;
Benjamin Petersonbac79492012-01-14 13:34:47 -05002557 if (PyUnicode_READY(str_obj) == -1) {
Victor Stinnere1335c72011-10-04 20:53:03 +02002558 Py_DECREF(str_obj);
2559 goto fail;
2560 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002561 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002562 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002563 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002564 *callresult++ = str_obj;
2565 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002566 break;
2567 }
2568 case 'S':
2569 {
2570 PyObject *obj = va_arg(count, PyObject *);
2571 PyObject *str;
2572 assert(obj);
2573 str = PyObject_Str(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002574 if (!str)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002575 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002576 if (PyUnicode_READY(str) == -1) {
2577 Py_DECREF(str);
2578 goto fail;
2579 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002580 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002581 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002582 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002583 /* Remember the str and switch to the next slot */
2584 *callresult++ = str;
2585 break;
2586 }
2587 case 'R':
2588 {
2589 PyObject *obj = va_arg(count, PyObject *);
2590 PyObject *repr;
2591 assert(obj);
2592 repr = PyObject_Repr(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002593 if (!repr)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002594 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002595 if (PyUnicode_READY(repr) == -1) {
2596 Py_DECREF(repr);
2597 goto fail;
2598 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002599 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002600 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002601 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002602 /* Remember the repr and switch to the next slot */
2603 *callresult++ = repr;
2604 break;
2605 }
2606 case 'A':
2607 {
2608 PyObject *obj = va_arg(count, PyObject *);
2609 PyObject *ascii;
2610 assert(obj);
2611 ascii = PyObject_ASCII(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002612 if (!ascii)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002613 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002614 if (PyUnicode_READY(ascii) == -1) {
2615 Py_DECREF(ascii);
2616 goto fail;
2617 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002618 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002619 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002620 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002621 /* Remember the repr and switch to the next slot */
2622 *callresult++ = ascii;
2623 break;
2624 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002625 default:
2626 /* if we stumble upon an unknown
2627 formatting code, copy the rest of
2628 the format string to the output
2629 string. (we cannot just skip the
2630 code, since there's no way to know
2631 what's in the argument list) */
2632 n += strlen(p);
2633 goto expand;
2634 }
2635 } else
2636 n++;
2637 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002638 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002639 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002640 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002641 we don't have to resize the string.
2642 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002643 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002644 if (!string)
2645 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002646 kind = PyUnicode_KIND(string);
2647 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002648 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002649 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002650
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002651 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002652 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002653 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002654
2655 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002656 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2657 /* checking for == because the last argument could be a empty
2658 string, which causes i to point to end, the assert at the end of
2659 the loop */
2660 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002661
Benjamin Peterson14339b62009-01-31 16:36:08 +00002662 switch (*f) {
2663 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002664 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002665 const int ordinal = va_arg(vargs, int);
2666 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002667 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002668 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002669 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002670 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002671 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002672 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002673 case 'p':
Victor Stinnerc5166102012-02-22 13:55:02 +01002674 {
2675 Py_ssize_t written;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002676 /* unused, since we already have the result */
2677 if (*f == 'p')
2678 (void) va_arg(vargs, void *);
2679 else
2680 (void) va_arg(vargs, int);
2681 /* extract the result from numberresults and append. */
Victor Stinnerc5166102012-02-22 13:55:02 +01002682 written = unicode_write_cstr(string, i, numberresult);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002683 /* skip over the separating '\0' */
Victor Stinnerc5166102012-02-22 13:55:02 +01002684 i += written;
2685 numberresult += written;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002686 assert(*numberresult == '\0');
2687 numberresult++;
2688 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002689 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002690 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002691 case 's':
2692 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002693 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002694 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002695 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002696 size = PyUnicode_GET_LENGTH(*callresult);
2697 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002698 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002699 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002700 /* We're done with the unicode()/repr() => forget it */
2701 Py_DECREF(*callresult);
2702 /* switch to next unicode()/repr() result */
2703 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002704 break;
2705 }
2706 case 'U':
2707 {
2708 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002709 Py_ssize_t size;
2710 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2711 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002712 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002713 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002714 break;
2715 }
2716 case 'V':
2717 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002718 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002719 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002720 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002721 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002722 size = PyUnicode_GET_LENGTH(obj);
2723 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002724 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002725 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002726 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002727 size = PyUnicode_GET_LENGTH(*callresult);
2728 assert(PyUnicode_KIND(*callresult) <=
2729 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002730 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002731 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002732 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002733 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002734 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002735 break;
2736 }
2737 case 'S':
2738 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002739 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002740 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002741 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002742 /* unused, since we already have the result */
2743 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002744 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002745 copy_characters(string, i, *callresult, 0, size);
2746 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002747 /* We're done with the unicode()/repr() => forget it */
2748 Py_DECREF(*callresult);
2749 /* switch to next unicode()/repr() result */
2750 ++callresult;
2751 break;
2752 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002753 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002754 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002755 break;
2756 default:
Victor Stinnerc5166102012-02-22 13:55:02 +01002757 i += unicode_write_cstr(string, i, p);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002758 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002759 goto end;
2760 }
Victor Stinner1205f272010-09-11 00:54:47 +00002761 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002762 else {
2763 assert(i < PyUnicode_GET_LENGTH(string));
2764 PyUnicode_WRITE(kind, data, i++, *f);
2765 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002766 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002767 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002768
Benjamin Peterson29060642009-01-31 22:14:21 +00002769 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002770 if (callresults)
2771 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002772 if (numberresults)
2773 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002774 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002775 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002776 if (callresults) {
2777 PyObject **callresult2 = callresults;
2778 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002779 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002780 ++callresult2;
2781 }
2782 PyObject_Free(callresults);
2783 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002784 if (numberresults)
2785 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002786 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002787}
2788
Walter Dörwaldd2034312007-05-18 16:29:38 +00002789PyObject *
2790PyUnicode_FromFormat(const char *format, ...)
2791{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002792 PyObject* ret;
2793 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002794
2795#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002796 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002797#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002798 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002799#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002800 ret = PyUnicode_FromFormatV(format, vargs);
2801 va_end(vargs);
2802 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002803}
2804
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002805#ifdef HAVE_WCHAR_H
2806
Victor Stinner5593d8a2010-10-02 11:11:27 +00002807/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2808 convert a Unicode object to a wide character string.
2809
Victor Stinnerd88d9832011-09-06 02:00:05 +02002810 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002811 character) required to convert the unicode object. Ignore size argument.
2812
Victor Stinnerd88d9832011-09-06 02:00:05 +02002813 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002814 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002815 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002816static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002817unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002818 wchar_t *w,
2819 Py_ssize_t size)
2820{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002821 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002822 const wchar_t *wstr;
2823
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002824 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002825 if (wstr == NULL)
2826 return -1;
2827
Victor Stinner5593d8a2010-10-02 11:11:27 +00002828 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002829 if (size > res)
2830 size = res + 1;
2831 else
2832 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002833 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002834 return res;
2835 }
2836 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002837 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002838}
2839
2840Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002841PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002842 wchar_t *w,
2843 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002844{
2845 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002846 PyErr_BadInternalCall();
2847 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002848 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002849 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002850}
2851
Victor Stinner137c34c2010-09-29 10:25:54 +00002852wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002853PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002854 Py_ssize_t *size)
2855{
2856 wchar_t* buffer;
2857 Py_ssize_t buflen;
2858
2859 if (unicode == NULL) {
2860 PyErr_BadInternalCall();
2861 return NULL;
2862 }
2863
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002864 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002865 if (buflen == -1)
2866 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002867 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002868 PyErr_NoMemory();
2869 return NULL;
2870 }
2871
Victor Stinner137c34c2010-09-29 10:25:54 +00002872 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2873 if (buffer == NULL) {
2874 PyErr_NoMemory();
2875 return NULL;
2876 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002877 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002878 if (buflen == -1)
2879 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002880 if (size != NULL)
2881 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002882 return buffer;
2883}
2884
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002885#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002886
Alexander Belopolsky40018472011-02-26 01:02:56 +00002887PyObject *
2888PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002889{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002890 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002891 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002892 PyErr_SetString(PyExc_ValueError,
2893 "chr() arg not in range(0x110000)");
2894 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002895 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002896
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002897 if (ordinal < 256)
2898 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002899
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002900 v = PyUnicode_New(1, ordinal);
2901 if (v == NULL)
2902 return NULL;
2903 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002904 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002905 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002906}
2907
Alexander Belopolsky40018472011-02-26 01:02:56 +00002908PyObject *
2909PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002910{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002911 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002912 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002913 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002914 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002915 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002916 Py_INCREF(obj);
2917 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002918 }
2919 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002920 /* For a Unicode subtype that's not a Unicode object,
2921 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002922 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002923 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002924 PyErr_Format(PyExc_TypeError,
2925 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002926 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002927 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002928}
2929
Alexander Belopolsky40018472011-02-26 01:02:56 +00002930PyObject *
2931PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002932 const char *encoding,
2933 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002934{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002935 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002936 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002937
Guido van Rossumd57fd912000-03-10 22:53:23 +00002938 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002939 PyErr_BadInternalCall();
2940 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002941 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002942
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002943 /* Decoding bytes objects is the most common case and should be fast */
2944 if (PyBytes_Check(obj)) {
2945 if (PyBytes_GET_SIZE(obj) == 0) {
2946 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002947 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002948 }
2949 else {
2950 v = PyUnicode_Decode(
2951 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2952 encoding, errors);
2953 }
2954 return v;
2955 }
2956
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002957 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002958 PyErr_SetString(PyExc_TypeError,
2959 "decoding str is not supported");
2960 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002961 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002962
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002963 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2964 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2965 PyErr_Format(PyExc_TypeError,
2966 "coercing to str: need bytes, bytearray "
2967 "or buffer-like object, %.80s found",
2968 Py_TYPE(obj)->tp_name);
2969 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002970 }
Tim Petersced69f82003-09-16 20:30:58 +00002971
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002972 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002973 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002974 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002975 }
Tim Petersced69f82003-09-16 20:30:58 +00002976 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002977 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002978
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002979 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002980 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002981}
2982
Victor Stinner600d3be2010-06-10 12:00:55 +00002983/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002984 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2985 1 on success. */
2986static int
2987normalize_encoding(const char *encoding,
2988 char *lower,
2989 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002990{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002991 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002992 char *l;
2993 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002994
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002995 if (encoding == NULL) {
2996 strcpy(lower, "utf-8");
2997 return 1;
2998 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002999 e = encoding;
3000 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003001 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00003002 while (*e) {
3003 if (l == l_end)
3004 return 0;
David Malcolm96960882010-11-05 17:23:41 +00003005 if (Py_ISUPPER(*e)) {
3006 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003007 }
3008 else if (*e == '_') {
3009 *l++ = '-';
3010 e++;
3011 }
3012 else {
3013 *l++ = *e++;
3014 }
3015 }
3016 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003017 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003018}
3019
Alexander Belopolsky40018472011-02-26 01:02:56 +00003020PyObject *
3021PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003022 Py_ssize_t size,
3023 const char *encoding,
3024 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003025{
3026 PyObject *buffer = NULL, *unicode;
3027 Py_buffer info;
3028 char lower[11]; /* Enough for any encoding shortcut */
3029
Fred Drakee4315f52000-05-09 19:53:39 +00003030 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003031 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003032 if ((strcmp(lower, "utf-8") == 0) ||
3033 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003034 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003035 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003036 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003037 (strcmp(lower, "iso-8859-1") == 0))
3038 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003039#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003040 else if (strcmp(lower, "mbcs") == 0)
3041 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003042#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003043 else if (strcmp(lower, "ascii") == 0)
3044 return PyUnicode_DecodeASCII(s, size, errors);
3045 else if (strcmp(lower, "utf-16") == 0)
3046 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3047 else if (strcmp(lower, "utf-32") == 0)
3048 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3049 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003050
3051 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003052 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003053 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003054 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003055 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003056 if (buffer == NULL)
3057 goto onError;
3058 unicode = PyCodec_Decode(buffer, encoding, errors);
3059 if (unicode == NULL)
3060 goto onError;
3061 if (!PyUnicode_Check(unicode)) {
3062 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003063 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003064 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003065 Py_DECREF(unicode);
3066 goto onError;
3067 }
3068 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003069 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003070
Benjamin Peterson29060642009-01-31 22:14:21 +00003071 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003072 Py_XDECREF(buffer);
3073 return NULL;
3074}
3075
Alexander Belopolsky40018472011-02-26 01:02:56 +00003076PyObject *
3077PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003078 const char *encoding,
3079 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003080{
3081 PyObject *v;
3082
3083 if (!PyUnicode_Check(unicode)) {
3084 PyErr_BadArgument();
3085 goto onError;
3086 }
3087
3088 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003089 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003090
3091 /* Decode via the codec registry */
3092 v = PyCodec_Decode(unicode, encoding, errors);
3093 if (v == NULL)
3094 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003095 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003096
Benjamin Peterson29060642009-01-31 22:14:21 +00003097 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003098 return NULL;
3099}
3100
Alexander Belopolsky40018472011-02-26 01:02:56 +00003101PyObject *
3102PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003103 const char *encoding,
3104 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003105{
3106 PyObject *v;
3107
3108 if (!PyUnicode_Check(unicode)) {
3109 PyErr_BadArgument();
3110 goto onError;
3111 }
3112
3113 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003114 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003115
3116 /* Decode via the codec registry */
3117 v = PyCodec_Decode(unicode, encoding, errors);
3118 if (v == NULL)
3119 goto onError;
3120 if (!PyUnicode_Check(v)) {
3121 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003122 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003123 Py_TYPE(v)->tp_name);
3124 Py_DECREF(v);
3125 goto onError;
3126 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003127 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003128
Benjamin Peterson29060642009-01-31 22:14:21 +00003129 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003130 return NULL;
3131}
3132
Alexander Belopolsky40018472011-02-26 01:02:56 +00003133PyObject *
3134PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003135 Py_ssize_t size,
3136 const char *encoding,
3137 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003138{
3139 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003140
Guido van Rossumd57fd912000-03-10 22:53:23 +00003141 unicode = PyUnicode_FromUnicode(s, size);
3142 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003143 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003144 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3145 Py_DECREF(unicode);
3146 return v;
3147}
3148
Alexander Belopolsky40018472011-02-26 01:02:56 +00003149PyObject *
3150PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003151 const char *encoding,
3152 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003153{
3154 PyObject *v;
3155
3156 if (!PyUnicode_Check(unicode)) {
3157 PyErr_BadArgument();
3158 goto onError;
3159 }
3160
3161 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003162 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003163
3164 /* Encode via the codec registry */
3165 v = PyCodec_Encode(unicode, encoding, errors);
3166 if (v == NULL)
3167 goto onError;
3168 return v;
3169
Benjamin Peterson29060642009-01-31 22:14:21 +00003170 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003171 return NULL;
3172}
3173
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003174static size_t
3175wcstombs_errorpos(const wchar_t *wstr)
3176{
3177 size_t len;
3178#if SIZEOF_WCHAR_T == 2
3179 wchar_t buf[3];
3180#else
3181 wchar_t buf[2];
3182#endif
3183 char outbuf[MB_LEN_MAX];
3184 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003185
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003186#if SIZEOF_WCHAR_T == 2
3187 buf[2] = 0;
3188#else
3189 buf[1] = 0;
3190#endif
3191 start = wstr;
3192 while (*wstr != L'\0')
3193 {
3194 previous = wstr;
3195#if SIZEOF_WCHAR_T == 2
3196 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3197 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3198 {
3199 buf[0] = wstr[0];
3200 buf[1] = wstr[1];
3201 wstr += 2;
3202 }
3203 else {
3204 buf[0] = *wstr;
3205 buf[1] = 0;
3206 wstr++;
3207 }
3208#else
3209 buf[0] = *wstr;
3210 wstr++;
3211#endif
3212 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003213 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003214 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003215 }
3216
3217 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003218 return 0;
3219}
3220
Victor Stinner1b579672011-12-17 05:47:23 +01003221static int
3222locale_error_handler(const char *errors, int *surrogateescape)
3223{
3224 if (errors == NULL) {
3225 *surrogateescape = 0;
3226 return 0;
3227 }
3228
3229 if (strcmp(errors, "strict") == 0) {
3230 *surrogateescape = 0;
3231 return 0;
3232 }
3233 if (strcmp(errors, "surrogateescape") == 0) {
3234 *surrogateescape = 1;
3235 return 0;
3236 }
3237 PyErr_Format(PyExc_ValueError,
3238 "only 'strict' and 'surrogateescape' error handlers "
3239 "are supported, not '%s'",
3240 errors);
3241 return -1;
3242}
3243
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003244PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003245PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003246{
3247 Py_ssize_t wlen, wlen2;
3248 wchar_t *wstr;
3249 PyObject *bytes = NULL;
3250 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003251 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003252 PyObject *exc;
3253 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003254 int surrogateescape;
3255
3256 if (locale_error_handler(errors, &surrogateescape) < 0)
3257 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003258
3259 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3260 if (wstr == NULL)
3261 return NULL;
3262
3263 wlen2 = wcslen(wstr);
3264 if (wlen2 != wlen) {
3265 PyMem_Free(wstr);
3266 PyErr_SetString(PyExc_TypeError, "embedded null character");
3267 return NULL;
3268 }
3269
3270 if (surrogateescape) {
3271 /* locale encoding with surrogateescape */
3272 char *str;
3273
3274 str = _Py_wchar2char(wstr, &error_pos);
3275 if (str == NULL) {
3276 if (error_pos == (size_t)-1) {
3277 PyErr_NoMemory();
3278 PyMem_Free(wstr);
3279 return NULL;
3280 }
3281 else {
3282 goto encode_error;
3283 }
3284 }
3285 PyMem_Free(wstr);
3286
3287 bytes = PyBytes_FromString(str);
3288 PyMem_Free(str);
3289 }
3290 else {
3291 size_t len, len2;
3292
3293 len = wcstombs(NULL, wstr, 0);
3294 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003295 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003296 goto encode_error;
3297 }
3298
3299 bytes = PyBytes_FromStringAndSize(NULL, len);
3300 if (bytes == NULL) {
3301 PyMem_Free(wstr);
3302 return NULL;
3303 }
3304
3305 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3306 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003307 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003308 goto encode_error;
3309 }
3310 PyMem_Free(wstr);
3311 }
3312 return bytes;
3313
3314encode_error:
3315 errmsg = strerror(errno);
3316 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003317
3318 if (error_pos == (size_t)-1)
3319 error_pos = wcstombs_errorpos(wstr);
3320
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003321 PyMem_Free(wstr);
3322 Py_XDECREF(bytes);
3323
Victor Stinner2f197072011-12-17 07:08:30 +01003324 if (errmsg != NULL) {
3325 size_t errlen;
3326 wstr = _Py_char2wchar(errmsg, &errlen);
3327 if (wstr != NULL) {
3328 reason = PyUnicode_FromWideChar(wstr, errlen);
3329 PyMem_Free(wstr);
3330 } else
3331 errmsg = NULL;
3332 }
3333 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003334 reason = PyUnicode_FromString(
3335 "wcstombs() encountered an unencodable "
3336 "wide character");
3337 if (reason == NULL)
3338 return NULL;
3339
3340 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3341 "locale", unicode,
3342 (Py_ssize_t)error_pos,
3343 (Py_ssize_t)(error_pos+1),
3344 reason);
3345 Py_DECREF(reason);
3346 if (exc != NULL) {
3347 PyCodec_StrictErrors(exc);
3348 Py_XDECREF(exc);
3349 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003350 return NULL;
3351}
3352
Victor Stinnerad158722010-10-27 00:25:46 +00003353PyObject *
3354PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003355{
Victor Stinner99b95382011-07-04 14:23:54 +02003356#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003357 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003358#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003359 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003360#else
Victor Stinner793b5312011-04-27 00:24:21 +02003361 PyInterpreterState *interp = PyThreadState_GET()->interp;
3362 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3363 cannot use it to encode and decode filenames before it is loaded. Load
3364 the Python codec requires to encode at least its own filename. Use the C
3365 version of the locale codec until the codec registry is initialized and
3366 the Python codec is loaded.
3367
3368 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3369 cannot only rely on it: check also interp->fscodec_initialized for
3370 subinterpreters. */
3371 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003372 return PyUnicode_AsEncodedString(unicode,
3373 Py_FileSystemDefaultEncoding,
3374 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003375 }
3376 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003377 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003378 }
Victor Stinnerad158722010-10-27 00:25:46 +00003379#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003380}
3381
Alexander Belopolsky40018472011-02-26 01:02:56 +00003382PyObject *
3383PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003384 const char *encoding,
3385 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003386{
3387 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003388 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003389
Guido van Rossumd57fd912000-03-10 22:53:23 +00003390 if (!PyUnicode_Check(unicode)) {
3391 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003392 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003393 }
Fred Drakee4315f52000-05-09 19:53:39 +00003394
Fred Drakee4315f52000-05-09 19:53:39 +00003395 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003396 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003397 if ((strcmp(lower, "utf-8") == 0) ||
3398 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003399 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003400 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003401 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003402 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003403 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003404 }
Victor Stinner37296e82010-06-10 13:36:23 +00003405 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003406 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003407 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003408 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003409#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003410 else if (strcmp(lower, "mbcs") == 0)
3411 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003412#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003413 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003414 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003415 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003416
3417 /* Encode via the codec registry */
3418 v = PyCodec_Encode(unicode, encoding, errors);
3419 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003420 return NULL;
3421
3422 /* The normal path */
3423 if (PyBytes_Check(v))
3424 return v;
3425
3426 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003427 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003428 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003429 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003430
3431 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3432 "encoder %s returned bytearray instead of bytes",
3433 encoding);
3434 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003435 Py_DECREF(v);
3436 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003437 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003438
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003439 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3440 Py_DECREF(v);
3441 return b;
3442 }
3443
3444 PyErr_Format(PyExc_TypeError,
3445 "encoder did not return a bytes object (type=%.400s)",
3446 Py_TYPE(v)->tp_name);
3447 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003448 return NULL;
3449}
3450
Alexander Belopolsky40018472011-02-26 01:02:56 +00003451PyObject *
3452PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003453 const char *encoding,
3454 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003455{
3456 PyObject *v;
3457
3458 if (!PyUnicode_Check(unicode)) {
3459 PyErr_BadArgument();
3460 goto onError;
3461 }
3462
3463 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003464 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003465
3466 /* Encode via the codec registry */
3467 v = PyCodec_Encode(unicode, encoding, errors);
3468 if (v == NULL)
3469 goto onError;
3470 if (!PyUnicode_Check(v)) {
3471 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003472 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003473 Py_TYPE(v)->tp_name);
3474 Py_DECREF(v);
3475 goto onError;
3476 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003477 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003478
Benjamin Peterson29060642009-01-31 22:14:21 +00003479 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003480 return NULL;
3481}
3482
Victor Stinner2f197072011-12-17 07:08:30 +01003483static size_t
3484mbstowcs_errorpos(const char *str, size_t len)
3485{
3486#ifdef HAVE_MBRTOWC
3487 const char *start = str;
3488 mbstate_t mbs;
3489 size_t converted;
3490 wchar_t ch;
3491
3492 memset(&mbs, 0, sizeof mbs);
3493 while (len)
3494 {
3495 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3496 if (converted == 0)
3497 /* Reached end of string */
3498 break;
3499 if (converted == (size_t)-1 || converted == (size_t)-2) {
3500 /* Conversion error or incomplete character */
3501 return str - start;
3502 }
3503 else {
3504 str += converted;
3505 len -= converted;
3506 }
3507 }
3508 /* failed to find the undecodable byte sequence */
3509 return 0;
3510#endif
3511 return 0;
3512}
3513
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003514PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003515PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003516 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003517{
3518 wchar_t smallbuf[256];
3519 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3520 wchar_t *wstr;
3521 size_t wlen, wlen2;
3522 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003523 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003524 size_t error_pos;
3525 char *errmsg;
3526 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003527
3528 if (locale_error_handler(errors, &surrogateescape) < 0)
3529 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003530
3531 if (str[len] != '\0' || len != strlen(str)) {
3532 PyErr_SetString(PyExc_TypeError, "embedded null character");
3533 return NULL;
3534 }
3535
3536 if (surrogateescape)
3537 {
3538 wstr = _Py_char2wchar(str, &wlen);
3539 if (wstr == NULL) {
3540 if (wlen == (size_t)-1)
3541 PyErr_NoMemory();
3542 else
3543 PyErr_SetFromErrno(PyExc_OSError);
3544 return NULL;
3545 }
3546
3547 unicode = PyUnicode_FromWideChar(wstr, wlen);
3548 PyMem_Free(wstr);
3549 }
3550 else {
3551#ifndef HAVE_BROKEN_MBSTOWCS
3552 wlen = mbstowcs(NULL, str, 0);
3553#else
3554 wlen = len;
3555#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003556 if (wlen == (size_t)-1)
3557 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003558 if (wlen+1 <= smallbuf_len) {
3559 wstr = smallbuf;
3560 }
3561 else {
3562 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3563 return PyErr_NoMemory();
3564
3565 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3566 if (!wstr)
3567 return PyErr_NoMemory();
3568 }
3569
3570 /* This shouldn't fail now */
3571 wlen2 = mbstowcs(wstr, str, wlen+1);
3572 if (wlen2 == (size_t)-1) {
3573 if (wstr != smallbuf)
3574 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003575 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003576 }
3577#ifdef HAVE_BROKEN_MBSTOWCS
3578 assert(wlen2 == wlen);
3579#endif
3580 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3581 if (wstr != smallbuf)
3582 PyMem_Free(wstr);
3583 }
3584 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003585
3586decode_error:
3587 errmsg = strerror(errno);
3588 assert(errmsg != NULL);
3589
3590 error_pos = mbstowcs_errorpos(str, len);
3591 if (errmsg != NULL) {
3592 size_t errlen;
3593 wstr = _Py_char2wchar(errmsg, &errlen);
3594 if (wstr != NULL) {
3595 reason = PyUnicode_FromWideChar(wstr, errlen);
3596 PyMem_Free(wstr);
3597 } else
3598 errmsg = NULL;
3599 }
3600 if (errmsg == NULL)
3601 reason = PyUnicode_FromString(
3602 "mbstowcs() encountered an invalid multibyte sequence");
3603 if (reason == NULL)
3604 return NULL;
3605
3606 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3607 "locale", str, len,
3608 (Py_ssize_t)error_pos,
3609 (Py_ssize_t)(error_pos+1),
3610 reason);
3611 Py_DECREF(reason);
3612 if (exc != NULL) {
3613 PyCodec_StrictErrors(exc);
3614 Py_XDECREF(exc);
3615 }
3616 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003617}
3618
3619PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003620PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003621{
3622 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003623 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003624}
3625
3626
3627PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003628PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003629 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003630 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3631}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003632
Christian Heimes5894ba72007-11-04 11:43:14 +00003633PyObject*
3634PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3635{
Victor Stinner99b95382011-07-04 14:23:54 +02003636#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003637 return PyUnicode_DecodeMBCS(s, size, NULL);
3638#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003639 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003640#else
Victor Stinner793b5312011-04-27 00:24:21 +02003641 PyInterpreterState *interp = PyThreadState_GET()->interp;
3642 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3643 cannot use it to encode and decode filenames before it is loaded. Load
3644 the Python codec requires to encode at least its own filename. Use the C
3645 version of the locale codec until the codec registry is initialized and
3646 the Python codec is loaded.
3647
3648 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3649 cannot only rely on it: check also interp->fscodec_initialized for
3650 subinterpreters. */
3651 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003652 return PyUnicode_Decode(s, size,
3653 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003654 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003655 }
3656 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003657 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003658 }
Victor Stinnerad158722010-10-27 00:25:46 +00003659#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003660}
3661
Martin v. Löwis011e8422009-05-05 04:43:17 +00003662
3663int
Antoine Pitrou13348842012-01-29 18:36:34 +01003664_PyUnicode_HasNULChars(PyObject* s)
3665{
3666 static PyObject *nul = NULL;
3667
3668 if (nul == NULL)
3669 nul = PyUnicode_FromStringAndSize("\0", 1);
3670 if (nul == NULL)
3671 return -1;
3672 return PyUnicode_Contains(s, nul);
3673}
3674
3675
3676int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003677PyUnicode_FSConverter(PyObject* arg, void* addr)
3678{
3679 PyObject *output = NULL;
3680 Py_ssize_t size;
3681 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003682 if (arg == NULL) {
3683 Py_DECREF(*(PyObject**)addr);
3684 return 1;
3685 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003686 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003687 output = arg;
3688 Py_INCREF(output);
3689 }
3690 else {
3691 arg = PyUnicode_FromObject(arg);
3692 if (!arg)
3693 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003694 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003695 Py_DECREF(arg);
3696 if (!output)
3697 return 0;
3698 if (!PyBytes_Check(output)) {
3699 Py_DECREF(output);
3700 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3701 return 0;
3702 }
3703 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003704 size = PyBytes_GET_SIZE(output);
3705 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003706 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003707 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003708 Py_DECREF(output);
3709 return 0;
3710 }
3711 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003712 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003713}
3714
3715
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003716int
3717PyUnicode_FSDecoder(PyObject* arg, void* addr)
3718{
3719 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003720 if (arg == NULL) {
3721 Py_DECREF(*(PyObject**)addr);
3722 return 1;
3723 }
3724 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003725 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003726 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003727 output = arg;
3728 Py_INCREF(output);
3729 }
3730 else {
3731 arg = PyBytes_FromObject(arg);
3732 if (!arg)
3733 return 0;
3734 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3735 PyBytes_GET_SIZE(arg));
3736 Py_DECREF(arg);
3737 if (!output)
3738 return 0;
3739 if (!PyUnicode_Check(output)) {
3740 Py_DECREF(output);
3741 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3742 return 0;
3743 }
3744 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003745 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003746 Py_DECREF(output);
3747 return 0;
3748 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003749 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003750 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003751 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3752 Py_DECREF(output);
3753 return 0;
3754 }
3755 *(PyObject**)addr = output;
3756 return Py_CLEANUP_SUPPORTED;
3757}
3758
3759
Martin v. Löwis5b222132007-06-10 09:51:05 +00003760char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003761PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003762{
Christian Heimesf3863112007-11-22 07:46:41 +00003763 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003764
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003765 if (!PyUnicode_Check(unicode)) {
3766 PyErr_BadArgument();
3767 return NULL;
3768 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003769 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003770 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003771
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003772 if (PyUnicode_UTF8(unicode) == NULL) {
3773 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003774 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3775 if (bytes == NULL)
3776 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003777 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3778 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003779 Py_DECREF(bytes);
3780 return NULL;
3781 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003782 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3783 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3784 PyBytes_AS_STRING(bytes),
3785 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003786 Py_DECREF(bytes);
3787 }
3788
3789 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003790 *psize = PyUnicode_UTF8_LENGTH(unicode);
3791 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003792}
3793
3794char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003795PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003796{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003797 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3798}
3799
3800#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003801static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003802#endif
3803
3804
3805Py_UNICODE *
3806PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3807{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003808 const unsigned char *one_byte;
3809#if SIZEOF_WCHAR_T == 4
3810 const Py_UCS2 *two_bytes;
3811#else
3812 const Py_UCS4 *four_bytes;
3813 const Py_UCS4 *ucs4_end;
3814 Py_ssize_t num_surrogates;
3815#endif
3816 wchar_t *w;
3817 wchar_t *wchar_end;
3818
3819 if (!PyUnicode_Check(unicode)) {
3820 PyErr_BadArgument();
3821 return NULL;
3822 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003823 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003824 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003825 assert(_PyUnicode_KIND(unicode) != 0);
3826 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003827
3828#ifdef Py_DEBUG
3829 ++unicode_as_unicode_calls;
3830#endif
3831
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003832 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003833#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003834 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3835 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003836 num_surrogates = 0;
3837
3838 for (; four_bytes < ucs4_end; ++four_bytes) {
3839 if (*four_bytes > 0xFFFF)
3840 ++num_surrogates;
3841 }
3842
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003843 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3844 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3845 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003846 PyErr_NoMemory();
3847 return NULL;
3848 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003849 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003850
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003851 w = _PyUnicode_WSTR(unicode);
3852 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3853 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003854 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3855 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003856 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003857 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003858 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3859 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003860 }
3861 else
3862 *w = *four_bytes;
3863
3864 if (w > wchar_end) {
3865 assert(0 && "Miscalculated string end");
3866 }
3867 }
3868 *w = 0;
3869#else
3870 /* sizeof(wchar_t) == 4 */
3871 Py_FatalError("Impossible unicode object state, wstr and str "
3872 "should share memory already.");
3873 return NULL;
3874#endif
3875 }
3876 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003877 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3878 (_PyUnicode_LENGTH(unicode) + 1));
3879 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003880 PyErr_NoMemory();
3881 return NULL;
3882 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003883 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3884 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3885 w = _PyUnicode_WSTR(unicode);
3886 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003887
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003888 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3889 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003890 for (; w < wchar_end; ++one_byte, ++w)
3891 *w = *one_byte;
3892 /* null-terminate the wstr */
3893 *w = 0;
3894 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003895 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003896#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003897 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003898 for (; w < wchar_end; ++two_bytes, ++w)
3899 *w = *two_bytes;
3900 /* null-terminate the wstr */
3901 *w = 0;
3902#else
3903 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003904 PyObject_FREE(_PyUnicode_WSTR(unicode));
3905 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003906 Py_FatalError("Impossible unicode object state, wstr "
3907 "and str should share memory already.");
3908 return NULL;
3909#endif
3910 }
3911 else {
3912 assert(0 && "This should never happen.");
3913 }
3914 }
3915 }
3916 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003917 *size = PyUnicode_WSTR_LENGTH(unicode);
3918 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003919}
3920
Alexander Belopolsky40018472011-02-26 01:02:56 +00003921Py_UNICODE *
3922PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003923{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003924 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003925}
3926
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003927
Alexander Belopolsky40018472011-02-26 01:02:56 +00003928Py_ssize_t
3929PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003930{
3931 if (!PyUnicode_Check(unicode)) {
3932 PyErr_BadArgument();
3933 goto onError;
3934 }
3935 return PyUnicode_GET_SIZE(unicode);
3936
Benjamin Peterson29060642009-01-31 22:14:21 +00003937 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003938 return -1;
3939}
3940
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003941Py_ssize_t
3942PyUnicode_GetLength(PyObject *unicode)
3943{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003944 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003945 PyErr_BadArgument();
3946 return -1;
3947 }
3948
3949 return PyUnicode_GET_LENGTH(unicode);
3950}
3951
3952Py_UCS4
3953PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3954{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003955 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3956 PyErr_BadArgument();
3957 return (Py_UCS4)-1;
3958 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003959 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003960 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003961 return (Py_UCS4)-1;
3962 }
3963 return PyUnicode_READ_CHAR(unicode, index);
3964}
3965
3966int
3967PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3968{
3969 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003970 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003971 return -1;
3972 }
Victor Stinner488fa492011-12-12 00:01:39 +01003973 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003974 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003975 PyErr_SetString(PyExc_IndexError, "string index out of range");
3976 return -1;
3977 }
Victor Stinner488fa492011-12-12 00:01:39 +01003978 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003979 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003980 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3981 PyErr_SetString(PyExc_ValueError, "character out of range");
3982 return -1;
3983 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003984 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3985 index, ch);
3986 return 0;
3987}
3988
Alexander Belopolsky40018472011-02-26 01:02:56 +00003989const char *
3990PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003991{
Victor Stinner42cb4622010-09-01 19:39:01 +00003992 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003993}
3994
Victor Stinner554f3f02010-06-16 23:33:54 +00003995/* create or adjust a UnicodeDecodeError */
3996static void
3997make_decode_exception(PyObject **exceptionObject,
3998 const char *encoding,
3999 const char *input, Py_ssize_t length,
4000 Py_ssize_t startpos, Py_ssize_t endpos,
4001 const char *reason)
4002{
4003 if (*exceptionObject == NULL) {
4004 *exceptionObject = PyUnicodeDecodeError_Create(
4005 encoding, input, length, startpos, endpos, reason);
4006 }
4007 else {
4008 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4009 goto onError;
4010 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4011 goto onError;
4012 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4013 goto onError;
4014 }
4015 return;
4016
4017onError:
4018 Py_DECREF(*exceptionObject);
4019 *exceptionObject = NULL;
4020}
4021
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004022/* error handling callback helper:
4023 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004024 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004025 and adjust various state variables.
4026 return 0 on success, -1 on error
4027*/
4028
Alexander Belopolsky40018472011-02-26 01:02:56 +00004029static int
4030unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004031 const char *encoding, const char *reason,
4032 const char **input, const char **inend, Py_ssize_t *startinpos,
4033 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004034 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004035{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004036 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004037
4038 PyObject *restuple = NULL;
4039 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004040 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004041 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004042 Py_ssize_t requiredsize;
4043 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004044 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004045 int res = -1;
4046
Victor Stinner596a6c42011-11-09 00:02:18 +01004047 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4048 outsize = PyUnicode_GET_LENGTH(*output);
4049 else
4050 outsize = _PyUnicode_WSTR_LENGTH(*output);
4051
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004052 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004053 *errorHandler = PyCodec_LookupError(errors);
4054 if (*errorHandler == NULL)
4055 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004056 }
4057
Victor Stinner554f3f02010-06-16 23:33:54 +00004058 make_decode_exception(exceptionObject,
4059 encoding,
4060 *input, *inend - *input,
4061 *startinpos, *endinpos,
4062 reason);
4063 if (*exceptionObject == NULL)
4064 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004065
4066 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4067 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004068 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004069 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004070 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004071 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004072 }
4073 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004074 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004075 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004076 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004077
4078 /* Copy back the bytes variables, which might have been modified by the
4079 callback */
4080 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4081 if (!inputobj)
4082 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004083 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004084 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004085 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004086 *input = PyBytes_AS_STRING(inputobj);
4087 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004088 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004089 /* we can DECREF safely, as the exception has another reference,
4090 so the object won't go away. */
4091 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004092
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004093 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004094 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004095 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004096 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4097 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004098 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004099
Victor Stinner596a6c42011-11-09 00:02:18 +01004100 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4101 /* need more space? (at least enough for what we
4102 have+the replacement+the rest of the string (starting
4103 at the new input position), so we won't have to check space
4104 when there are no errors in the rest of the string) */
4105 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4106 requiredsize = *outpos + replen + insize-newpos;
4107 if (requiredsize > outsize) {
4108 if (requiredsize<2*outsize)
4109 requiredsize = 2*outsize;
4110 if (unicode_resize(output, requiredsize) < 0)
4111 goto onError;
4112 }
4113 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004114 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01004115 copy_characters(*output, *outpos, repunicode, 0, replen);
4116 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004117 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004118 else {
4119 wchar_t *repwstr;
4120 Py_ssize_t repwlen;
4121 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4122 if (repwstr == NULL)
4123 goto onError;
4124 /* need more space? (at least enough for what we
4125 have+the replacement+the rest of the string (starting
4126 at the new input position), so we won't have to check space
4127 when there are no errors in the rest of the string) */
4128 requiredsize = *outpos + repwlen + insize-newpos;
4129 if (requiredsize > outsize) {
4130 if (requiredsize < 2*outsize)
4131 requiredsize = 2*outsize;
4132 if (unicode_resize(output, requiredsize) < 0)
4133 goto onError;
4134 }
4135 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4136 *outpos += repwlen;
4137 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004138 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004139 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004140
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004141 /* we made it! */
4142 res = 0;
4143
Benjamin Peterson29060642009-01-31 22:14:21 +00004144 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004145 Py_XDECREF(restuple);
4146 return res;
4147}
4148
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004149/* --- UTF-7 Codec -------------------------------------------------------- */
4150
Antoine Pitrou244651a2009-05-04 18:56:13 +00004151/* See RFC2152 for details. We encode conservatively and decode liberally. */
4152
4153/* Three simple macros defining base-64. */
4154
4155/* Is c a base-64 character? */
4156
4157#define IS_BASE64(c) \
4158 (((c) >= 'A' && (c) <= 'Z') || \
4159 ((c) >= 'a' && (c) <= 'z') || \
4160 ((c) >= '0' && (c) <= '9') || \
4161 (c) == '+' || (c) == '/')
4162
4163/* given that c is a base-64 character, what is its base-64 value? */
4164
4165#define FROM_BASE64(c) \
4166 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4167 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4168 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4169 (c) == '+' ? 62 : 63)
4170
4171/* What is the base-64 character of the bottom 6 bits of n? */
4172
4173#define TO_BASE64(n) \
4174 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4175
4176/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4177 * decoded as itself. We are permissive on decoding; the only ASCII
4178 * byte not decoding to itself is the + which begins a base64
4179 * string. */
4180
4181#define DECODE_DIRECT(c) \
4182 ((c) <= 127 && (c) != '+')
4183
4184/* The UTF-7 encoder treats ASCII characters differently according to
4185 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4186 * the above). See RFC2152. This array identifies these different
4187 * sets:
4188 * 0 : "Set D"
4189 * alphanumeric and '(),-./:?
4190 * 1 : "Set O"
4191 * !"#$%&*;<=>@[]^_`{|}
4192 * 2 : "whitespace"
4193 * ht nl cr sp
4194 * 3 : special (must be base64 encoded)
4195 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4196 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004197
Tim Petersced69f82003-09-16 20:30:58 +00004198static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004199char utf7_category[128] = {
4200/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4201 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4202/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4203 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4204/* sp ! " # $ % & ' ( ) * + , - . / */
4205 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4206/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4207 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4208/* @ A B C D E F G H I J K L M N O */
4209 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4210/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4211 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4212/* ` a b c d e f g h i j k l m n o */
4213 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4214/* p q r s t u v w x y z { | } ~ del */
4215 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004216};
4217
Antoine Pitrou244651a2009-05-04 18:56:13 +00004218/* ENCODE_DIRECT: this character should be encoded as itself. The
4219 * answer depends on whether we are encoding set O as itself, and also
4220 * on whether we are encoding whitespace as itself. RFC2152 makes it
4221 * clear that the answers to these questions vary between
4222 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004223
Antoine Pitrou244651a2009-05-04 18:56:13 +00004224#define ENCODE_DIRECT(c, directO, directWS) \
4225 ((c) < 128 && (c) > 0 && \
4226 ((utf7_category[(c)] == 0) || \
4227 (directWS && (utf7_category[(c)] == 2)) || \
4228 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004229
Alexander Belopolsky40018472011-02-26 01:02:56 +00004230PyObject *
4231PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004232 Py_ssize_t size,
4233 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004234{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004235 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4236}
4237
Antoine Pitrou244651a2009-05-04 18:56:13 +00004238/* The decoder. The only state we preserve is our read position,
4239 * i.e. how many characters we have consumed. So if we end in the
4240 * middle of a shift sequence we have to back off the read position
4241 * and the output to the beginning of the sequence, otherwise we lose
4242 * all the shift state (seen bits, number of bits seen, high
4243 * surrogate). */
4244
Alexander Belopolsky40018472011-02-26 01:02:56 +00004245PyObject *
4246PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004247 Py_ssize_t size,
4248 const char *errors,
4249 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004250{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004251 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004252 Py_ssize_t startinpos;
4253 Py_ssize_t endinpos;
4254 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004255 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004256 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004257 const char *errmsg = "";
4258 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004259 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004260 unsigned int base64bits = 0;
4261 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004262 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004263 PyObject *errorHandler = NULL;
4264 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004265
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004266 /* Start off assuming it's all ASCII. Widen later as necessary. */
4267 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004268 if (!unicode)
4269 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004270 if (size == 0) {
4271 if (consumed)
4272 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004273 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004274 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004275
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004276 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004277 e = s + size;
4278
4279 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004280 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004281 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004282 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004283
Antoine Pitrou244651a2009-05-04 18:56:13 +00004284 if (inShift) { /* in a base-64 section */
4285 if (IS_BASE64(ch)) { /* consume a base-64 character */
4286 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4287 base64bits += 6;
4288 s++;
4289 if (base64bits >= 16) {
4290 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004291 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004292 base64bits -= 16;
4293 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4294 if (surrogate) {
4295 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004296 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4297 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004298 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4299 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004300 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004301 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004302 }
4303 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004304 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4305 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004306 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004307 }
4308 }
Victor Stinner551ac952011-11-29 22:58:13 +01004309 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004310 /* first surrogate */
4311 surrogate = outCh;
4312 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004313 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004314 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4315 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004316 }
4317 }
4318 }
4319 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004320 inShift = 0;
4321 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004322 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004323 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4324 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004325 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004326 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004327 if (base64bits > 0) { /* left-over bits */
4328 if (base64bits >= 6) {
4329 /* We've seen at least one base-64 character */
4330 errmsg = "partial character in shift sequence";
4331 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004332 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004333 else {
4334 /* Some bits remain; they should be zero */
4335 if (base64buffer != 0) {
4336 errmsg = "non-zero padding bits in shift sequence";
4337 goto utf7Error;
4338 }
4339 }
4340 }
4341 if (ch != '-') {
4342 /* '-' is absorbed; other terminating
4343 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004344 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4345 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004346 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004347 }
4348 }
4349 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004350 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004351 s++; /* consume '+' */
4352 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004353 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004354 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4355 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004356 }
4357 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004358 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004359 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004360 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004361 }
4362 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004363 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004364 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4365 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004366 s++;
4367 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004368 else {
4369 startinpos = s-starts;
4370 s++;
4371 errmsg = "unexpected special character";
4372 goto utf7Error;
4373 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004374 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004375utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004376 endinpos = s-starts;
4377 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004378 errors, &errorHandler,
4379 "utf7", errmsg,
4380 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004381 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004382 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004383 }
4384
Antoine Pitrou244651a2009-05-04 18:56:13 +00004385 /* end of string */
4386
4387 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4388 /* if we're in an inconsistent state, that's an error */
4389 if (surrogate ||
4390 (base64bits >= 6) ||
4391 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004392 endinpos = size;
4393 if (unicode_decode_call_errorhandler(
4394 errors, &errorHandler,
4395 "utf7", "unterminated shift sequence",
4396 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004397 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004398 goto onError;
4399 if (s < e)
4400 goto restart;
4401 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004402 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004403
4404 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004405 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004406 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004407 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004408 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004409 }
4410 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004411 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004412 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004413 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004414
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004415 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004416 goto onError;
4417
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004418 Py_XDECREF(errorHandler);
4419 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004420 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004421
Benjamin Peterson29060642009-01-31 22:14:21 +00004422 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004423 Py_XDECREF(errorHandler);
4424 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004425 Py_DECREF(unicode);
4426 return NULL;
4427}
4428
4429
Alexander Belopolsky40018472011-02-26 01:02:56 +00004430PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004431_PyUnicode_EncodeUTF7(PyObject *str,
4432 int base64SetO,
4433 int base64WhiteSpace,
4434 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004435{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004436 int kind;
4437 void *data;
4438 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004439 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004440 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004441 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004442 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004443 unsigned int base64bits = 0;
4444 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004445 char * out;
4446 char * start;
4447
Benjamin Petersonbac79492012-01-14 13:34:47 -05004448 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004449 return NULL;
4450 kind = PyUnicode_KIND(str);
4451 data = PyUnicode_DATA(str);
4452 len = PyUnicode_GET_LENGTH(str);
4453
4454 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004455 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004456
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004457 /* It might be possible to tighten this worst case */
4458 allocated = 8 * len;
4459 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004460 return PyErr_NoMemory();
4461
Antoine Pitrou244651a2009-05-04 18:56:13 +00004462 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004463 if (v == NULL)
4464 return NULL;
4465
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004466 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004467 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004468 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004469
Antoine Pitrou244651a2009-05-04 18:56:13 +00004470 if (inShift) {
4471 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4472 /* shifting out */
4473 if (base64bits) { /* output remaining bits */
4474 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4475 base64buffer = 0;
4476 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004477 }
4478 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004479 /* Characters not in the BASE64 set implicitly unshift the sequence
4480 so no '-' is required, except if the character is itself a '-' */
4481 if (IS_BASE64(ch) || ch == '-') {
4482 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004483 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004484 *out++ = (char) ch;
4485 }
4486 else {
4487 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004488 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004489 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004490 else { /* not in a shift sequence */
4491 if (ch == '+') {
4492 *out++ = '+';
4493 *out++ = '-';
4494 }
4495 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4496 *out++ = (char) ch;
4497 }
4498 else {
4499 *out++ = '+';
4500 inShift = 1;
4501 goto encode_char;
4502 }
4503 }
4504 continue;
4505encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004506 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004507 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004508
Antoine Pitrou244651a2009-05-04 18:56:13 +00004509 /* code first surrogate */
4510 base64bits += 16;
4511 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4512 while (base64bits >= 6) {
4513 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4514 base64bits -= 6;
4515 }
4516 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004517 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004518 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004519 base64bits += 16;
4520 base64buffer = (base64buffer << 16) | ch;
4521 while (base64bits >= 6) {
4522 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4523 base64bits -= 6;
4524 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004525 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004526 if (base64bits)
4527 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4528 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004529 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004530 if (_PyBytes_Resize(&v, out - start) < 0)
4531 return NULL;
4532 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004533}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004534PyObject *
4535PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4536 Py_ssize_t size,
4537 int base64SetO,
4538 int base64WhiteSpace,
4539 const char *errors)
4540{
4541 PyObject *result;
4542 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4543 if (tmp == NULL)
4544 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004545 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004546 base64WhiteSpace, errors);
4547 Py_DECREF(tmp);
4548 return result;
4549}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004550
Antoine Pitrou244651a2009-05-04 18:56:13 +00004551#undef IS_BASE64
4552#undef FROM_BASE64
4553#undef TO_BASE64
4554#undef DECODE_DIRECT
4555#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004556
Guido van Rossumd57fd912000-03-10 22:53:23 +00004557/* --- UTF-8 Codec -------------------------------------------------------- */
4558
Tim Petersced69f82003-09-16 20:30:58 +00004559static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004560char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004561 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4562 illegal prefix. See RFC 3629 for details */
4563 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4564 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004565 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004566 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4567 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4568 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4569 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004570 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4571 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 +00004572 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4573 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004574 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4575 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4576 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4577 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4578 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 +00004579};
4580
Alexander Belopolsky40018472011-02-26 01:02:56 +00004581PyObject *
4582PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004583 Py_ssize_t size,
4584 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004585{
Walter Dörwald69652032004-09-07 20:24:22 +00004586 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4587}
4588
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004589#include "stringlib/ucs1lib.h"
4590#include "stringlib/codecs.h"
4591#include "stringlib/undef.h"
4592
4593#include "stringlib/ucs2lib.h"
4594#include "stringlib/codecs.h"
4595#include "stringlib/undef.h"
4596
4597#include "stringlib/ucs4lib.h"
4598#include "stringlib/codecs.h"
4599#include "stringlib/undef.h"
4600
Antoine Pitrouab868312009-01-10 15:40:25 +00004601/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4602#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4603
4604/* Mask to quickly check whether a C 'long' contains a
4605 non-ASCII, UTF8-encoded char. */
4606#if (SIZEOF_LONG == 8)
4607# define ASCII_CHAR_MASK 0x8080808080808080L
4608#elif (SIZEOF_LONG == 4)
4609# define ASCII_CHAR_MASK 0x80808080L
4610#else
4611# error C 'long' size should be either 4 or 8!
4612#endif
4613
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004614/* Scans a UTF-8 string and returns the maximum character to be expected
4615 and the size of the decoded unicode string.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004616
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004617 This function doesn't check for errors, these checks are performed in
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004618 PyUnicode_DecodeUTF8Stateful.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004619 */
4620static Py_UCS4
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004621utf8_scanner(const unsigned char *p, Py_ssize_t string_size, Py_ssize_t *unicode_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004622{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004623 Py_ssize_t char_count = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004624 const unsigned char *end = p + string_size;
4625 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004626
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004627 assert(unicode_size != NULL);
4628
4629 /* By having a cascade of independent loops which fallback onto each
4630 other, we minimize the amount of work done in the average loop
4631 iteration, and we also maximize the CPU's ability to predict
4632 branches correctly (because a given condition will have always the
4633 same boolean outcome except perhaps in the last iteration of the
4634 corresponding loop).
4635 In the general case this brings us rather close to decoding
4636 performance pre-PEP 393, despite the two-pass decoding.
4637
4638 Note that the pure ASCII loop is not duplicated once a non-ASCII
4639 character has been encountered. It is actually a pessimization (by
4640 a significant factor) to use this loop on text with many non-ASCII
4641 characters, and it is important to avoid bad performance on valid
4642 utf-8 data (invalid utf-8 being a different can of worms).
4643 */
4644
4645 /* ASCII */
4646 for (; p < end; ++p) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004647 /* Only check value if it's not a ASCII char... */
4648 if (*p < 0x80) {
4649 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4650 an explanation. */
4651 if (!((size_t) p & LONG_PTR_MASK)) {
4652 /* Help register allocation */
4653 register const unsigned char *_p = p;
4654 while (_p < aligned_end) {
4655 unsigned long value = *(unsigned long *) _p;
4656 if (value & ASCII_CHAR_MASK)
4657 break;
4658 _p += SIZEOF_LONG;
4659 char_count += SIZEOF_LONG;
4660 }
4661 p = _p;
4662 if (p == end)
4663 break;
4664 }
4665 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004666 if (*p < 0x80)
4667 ++char_count;
4668 else
4669 goto _ucs1loop;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004670 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004671 *unicode_size = char_count;
4672 return 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004673
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004674_ucs1loop:
4675 for (; p < end; ++p) {
4676 if (*p < 0xc4)
4677 char_count += ((*p & 0xc0) != 0x80);
4678 else
4679 goto _ucs2loop;
4680 }
4681 *unicode_size = char_count;
4682 return 255;
4683
4684_ucs2loop:
4685 for (; p < end; ++p) {
4686 if (*p < 0xf0)
4687 char_count += ((*p & 0xc0) != 0x80);
4688 else
4689 goto _ucs4loop;
4690 }
4691 *unicode_size = char_count;
4692 return 65535;
4693
4694_ucs4loop:
4695 for (; p < end; ++p) {
4696 char_count += ((*p & 0xc0) != 0x80);
4697 }
4698 *unicode_size = char_count;
4699 return 65537;
4700}
4701
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004702/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
Victor Stinner785938e2011-12-11 20:09:03 +01004703 in case of errors. Implicit parameters: unicode, kind, data, onError.
4704 Potential resizing overallocates, so the result needs to shrink at the end.
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004705*/
Victor Stinner785938e2011-12-11 20:09:03 +01004706#define WRITE_MAYBE_FAIL(index, value) \
4707 do { \
4708 Py_ssize_t pos = index; \
4709 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4710 unicode_resize(&unicode, pos + pos/8) < 0) \
4711 goto onError; \
4712 if (unicode_putchar(&unicode, &pos, value) < 0) \
4713 goto onError; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004714 } while (0)
4715
Victor Stinnerbf6e5602011-12-12 01:53:47 +01004716static PyObject *
Victor Stinner785938e2011-12-11 20:09:03 +01004717decode_utf8_errors(const char *starts,
4718 Py_ssize_t size,
4719 const char *errors,
4720 Py_ssize_t *consumed,
4721 const char *s,
4722 PyObject *unicode,
4723 Py_ssize_t i)
Walter Dörwald69652032004-09-07 20:24:22 +00004724{
Guido van Rossumd57fd912000-03-10 22:53:23 +00004725 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004726 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004727 Py_ssize_t startinpos;
4728 Py_ssize_t endinpos;
Victor Stinner785938e2011-12-11 20:09:03 +01004729 const char *e = starts + size;
4730 const char *aligned_end;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004731 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004732 PyObject *errorHandler = NULL;
4733 PyObject *exc = NULL;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004734
Antoine Pitrouab868312009-01-10 15:40:25 +00004735 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004736
4737 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004738 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004739
4740 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004741 /* Fast path for runs of ASCII characters. Given that common UTF-8
4742 input will consist of an overwhelming majority of ASCII
4743 characters, we try to optimize for this case by checking
4744 as many characters as a C 'long' can contain.
4745 First, check if we can do an aligned read, as most CPUs have
4746 a penalty for unaligned reads.
4747 */
4748 if (!((size_t) s & LONG_PTR_MASK)) {
4749 /* Help register allocation */
4750 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004751 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004752 while (_s < aligned_end) {
4753 /* Read a whole long at a time (either 4 or 8 bytes),
4754 and do a fast unrolled copy if it only contains ASCII
4755 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004756 unsigned long value = *(unsigned long *) _s;
4757 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004758 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004759 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4760 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4761 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4762 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004763#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004764 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4765 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4766 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4767 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004768#endif
4769 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004770 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004771 }
4772 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004773 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004774 if (s == e)
4775 break;
4776 ch = (unsigned char)*s;
4777 }
4778 }
4779
4780 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004781 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004782 s++;
4783 continue;
4784 }
4785
4786 n = utf8_code_length[ch];
4787
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004788 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004789 if (consumed)
4790 break;
4791 else {
4792 errmsg = "unexpected end of data";
4793 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004794 endinpos = startinpos+1;
4795 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4796 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004797 goto utf8Error;
4798 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004799 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004800
4801 switch (n) {
4802
4803 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004804 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004805 startinpos = s-starts;
4806 endinpos = startinpos+1;
4807 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004808
4809 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004810 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004811 startinpos = s-starts;
4812 endinpos = startinpos+1;
4813 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004814
4815 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004816 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004817 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004818 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004819 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004820 goto utf8Error;
4821 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004822 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004823 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004824 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004825 break;
4826
4827 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004828 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4829 will result in surrogates in range d800-dfff. Surrogates are
4830 not valid UTF-8 so they are rejected.
4831 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4832 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004833 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004834 (s[2] & 0xc0) != 0x80 ||
4835 ((unsigned char)s[0] == 0xE0 &&
4836 (unsigned char)s[1] < 0xA0) ||
4837 ((unsigned char)s[0] == 0xED &&
4838 (unsigned char)s[1] > 0x9F)) {
4839 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004840 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004841 endinpos = startinpos + 1;
4842
4843 /* if s[1] first two bits are 1 and 0, then the invalid
4844 continuation byte is s[2], so increment endinpos by 1,
4845 if not, s[1] is invalid and endinpos doesn't need to
4846 be incremented. */
4847 if ((s[1] & 0xC0) == 0x80)
4848 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004849 goto utf8Error;
4850 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004851 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004852 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004853 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004854 break;
4855
4856 case 4:
4857 if ((s[1] & 0xc0) != 0x80 ||
4858 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004859 (s[3] & 0xc0) != 0x80 ||
4860 ((unsigned char)s[0] == 0xF0 &&
4861 (unsigned char)s[1] < 0x90) ||
4862 ((unsigned char)s[0] == 0xF4 &&
4863 (unsigned char)s[1] > 0x8F)) {
4864 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004865 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004866 endinpos = startinpos + 1;
4867 if ((s[1] & 0xC0) == 0x80) {
4868 endinpos++;
4869 if ((s[2] & 0xC0) == 0x80)
4870 endinpos++;
4871 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004872 goto utf8Error;
4873 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004874 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004875 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01004876 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Ezio Melotti57221d02010-07-01 07:32:02 +00004877
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004878 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004879 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004880 }
4881 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004882 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004883
Benjamin Peterson29060642009-01-31 22:14:21 +00004884 utf8Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00004885 if (unicode_decode_call_errorhandler(
4886 errors, &errorHandler,
Victor Stinnercbe01342012-02-14 01:17:45 +01004887 "utf-8", errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00004888 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004889 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004890 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004891 /* Update data because unicode_decode_call_errorhandler might have
4892 re-created or resized the unicode object. */
Benjamin Peterson29060642009-01-31 22:14:21 +00004893 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004894 }
Walter Dörwald69652032004-09-07 20:24:22 +00004895 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004896 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004897
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004898 /* Adjust length and ready string when it contained errors and
4899 is of the old resizable kind. */
Victor Stinner785938e2011-12-11 20:09:03 +01004900 if (unicode_resize(&unicode, i) < 0)
4901 goto onError;
4902 unicode_adjust_maxchar(&unicode);
4903 if (unicode == NULL)
4904 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004905
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004906 Py_XDECREF(errorHandler);
4907 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004908 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004909 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004910
Benjamin Peterson29060642009-01-31 22:14:21 +00004911 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004912 Py_XDECREF(errorHandler);
4913 Py_XDECREF(exc);
Victor Stinner785938e2011-12-11 20:09:03 +01004914 Py_XDECREF(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004915 return NULL;
4916}
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004917#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004918
Victor Stinner785938e2011-12-11 20:09:03 +01004919PyObject *
4920PyUnicode_DecodeUTF8Stateful(const char *s,
4921 Py_ssize_t size,
4922 const char *errors,
4923 Py_ssize_t *consumed)
4924{
4925 Py_UCS4 maxchar = 0;
4926 Py_ssize_t unicode_size;
4927 int has_errors = 0;
4928 PyObject *unicode;
4929 int kind;
4930 void *data;
4931 const char *starts = s;
4932 const char *e;
4933 Py_ssize_t i;
4934
4935 if (size == 0) {
4936 if (consumed)
4937 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004938 Py_INCREF(unicode_empty);
4939 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004940 }
4941
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004942 maxchar = utf8_scanner((const unsigned char *)s, size, &unicode_size);
Victor Stinner785938e2011-12-11 20:09:03 +01004943
4944 /* When the string is ASCII only, just use memcpy and return.
4945 unicode_size may be != size if there is an incomplete UTF-8
4946 sequence at the end of the ASCII block. */
4947 if (maxchar < 128 && size == unicode_size) {
4948 if (consumed)
4949 *consumed = size;
Victor Stinnerab870212011-12-17 22:39:43 +01004950 return unicode_fromascii((const unsigned char *)s, size);
Victor Stinner785938e2011-12-11 20:09:03 +01004951 }
4952
4953 unicode = PyUnicode_New(unicode_size, maxchar);
4954 if (!unicode)
4955 return NULL;
4956 kind = PyUnicode_KIND(unicode);
4957 data = PyUnicode_DATA(unicode);
4958
4959 /* Unpack UTF-8 encoded data */
4960 i = 0;
4961 e = starts + size;
4962 switch (kind) {
4963 case PyUnicode_1BYTE_KIND:
4964 has_errors = ucs1lib_utf8_try_decode(s, e, (Py_UCS1 *) data, &s, &i);
4965 break;
4966 case PyUnicode_2BYTE_KIND:
4967 has_errors = ucs2lib_utf8_try_decode(s, e, (Py_UCS2 *) data, &s, &i);
4968 break;
4969 case PyUnicode_4BYTE_KIND:
4970 has_errors = ucs4lib_utf8_try_decode(s, e, (Py_UCS4 *) data, &s, &i);
4971 break;
4972 }
4973 if (!has_errors) {
4974 /* Ensure the unicode size calculation was correct */
4975 assert(i == unicode_size);
4976 assert(s == e);
4977 if (consumed)
4978 *consumed = size;
4979 return unicode;
4980 }
4981
4982 /* In case of errors, maxchar and size computation might be incorrect;
4983 code below refits and resizes as necessary. */
4984 return decode_utf8_errors(starts, size, errors, consumed, s, unicode, i);
4985}
4986
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004987#ifdef __APPLE__
4988
4989/* Simplified UTF-8 decoder using surrogateescape error handler,
4990 used to decode the command line arguments on Mac OS X. */
4991
4992wchar_t*
4993_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4994{
4995 int n;
4996 const char *e;
4997 wchar_t *unicode, *p;
4998
4999 /* Note: size will always be longer than the resulting Unicode
5000 character count */
5001 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
5002 PyErr_NoMemory();
5003 return NULL;
5004 }
5005 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
5006 if (!unicode)
5007 return NULL;
5008
5009 /* Unpack UTF-8 encoded data */
5010 p = unicode;
5011 e = s + size;
5012 while (s < e) {
5013 Py_UCS4 ch = (unsigned char)*s;
5014
5015 if (ch < 0x80) {
5016 *p++ = (wchar_t)ch;
5017 s++;
5018 continue;
5019 }
5020
5021 n = utf8_code_length[ch];
5022 if (s + n > e) {
5023 goto surrogateescape;
5024 }
5025
5026 switch (n) {
5027 case 0:
5028 case 1:
5029 goto surrogateescape;
5030
5031 case 2:
5032 if ((s[1] & 0xc0) != 0x80)
5033 goto surrogateescape;
5034 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
5035 assert ((ch > 0x007F) && (ch <= 0x07FF));
5036 *p++ = (wchar_t)ch;
5037 break;
5038
5039 case 3:
5040 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
5041 will result in surrogates in range d800-dfff. Surrogates are
5042 not valid UTF-8 so they are rejected.
5043 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
5044 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
5045 if ((s[1] & 0xc0) != 0x80 ||
5046 (s[2] & 0xc0) != 0x80 ||
5047 ((unsigned char)s[0] == 0xE0 &&
5048 (unsigned char)s[1] < 0xA0) ||
5049 ((unsigned char)s[0] == 0xED &&
5050 (unsigned char)s[1] > 0x9F)) {
5051
5052 goto surrogateescape;
5053 }
5054 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
5055 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005056 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005057 break;
5058
5059 case 4:
5060 if ((s[1] & 0xc0) != 0x80 ||
5061 (s[2] & 0xc0) != 0x80 ||
5062 (s[3] & 0xc0) != 0x80 ||
5063 ((unsigned char)s[0] == 0xF0 &&
5064 (unsigned char)s[1] < 0x90) ||
5065 ((unsigned char)s[0] == 0xF4 &&
5066 (unsigned char)s[1] > 0x8F)) {
5067 goto surrogateescape;
5068 }
5069 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
5070 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01005071 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005072
5073#if SIZEOF_WCHAR_T == 4
5074 *p++ = (wchar_t)ch;
5075#else
5076 /* compute and append the two surrogates: */
Victor Stinner551ac952011-11-29 22:58:13 +01005077 *p++ = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5078 *p++ = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005079#endif
5080 break;
5081 }
5082 s += n;
5083 continue;
5084
5085 surrogateescape:
5086 *p++ = 0xDC00 + ch;
5087 s++;
5088 }
5089 *p = L'\0';
5090 return unicode;
5091}
5092
5093#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005094
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005095/* Primary internal function which creates utf8 encoded bytes objects.
5096
5097 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005098 and allocate exactly as much space needed at the end. Else allocate the
5099 maximum possible needed (4 result bytes per Unicode character), and return
5100 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005101*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005102PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005103_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005104{
Victor Stinner6099a032011-12-18 14:22:26 +01005105 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005106 void *data;
5107 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005108
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005109 if (!PyUnicode_Check(unicode)) {
5110 PyErr_BadArgument();
5111 return NULL;
5112 }
5113
5114 if (PyUnicode_READY(unicode) == -1)
5115 return NULL;
5116
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005117 if (PyUnicode_UTF8(unicode))
5118 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5119 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005120
5121 kind = PyUnicode_KIND(unicode);
5122 data = PyUnicode_DATA(unicode);
5123 size = PyUnicode_GET_LENGTH(unicode);
5124
Benjamin Petersonead6b532011-12-20 17:23:42 -06005125 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005126 default:
5127 assert(0);
5128 case PyUnicode_1BYTE_KIND:
5129 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5130 assert(!PyUnicode_IS_ASCII(unicode));
5131 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5132 case PyUnicode_2BYTE_KIND:
5133 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5134 case PyUnicode_4BYTE_KIND:
5135 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005136 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005137}
5138
Alexander Belopolsky40018472011-02-26 01:02:56 +00005139PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005140PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5141 Py_ssize_t size,
5142 const char *errors)
5143{
5144 PyObject *v, *unicode;
5145
5146 unicode = PyUnicode_FromUnicode(s, size);
5147 if (unicode == NULL)
5148 return NULL;
5149 v = _PyUnicode_AsUTF8String(unicode, errors);
5150 Py_DECREF(unicode);
5151 return v;
5152}
5153
5154PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005155PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005156{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005157 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005158}
5159
Walter Dörwald41980ca2007-08-16 21:55:45 +00005160/* --- UTF-32 Codec ------------------------------------------------------- */
5161
5162PyObject *
5163PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005164 Py_ssize_t size,
5165 const char *errors,
5166 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005167{
5168 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5169}
5170
5171PyObject *
5172PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005173 Py_ssize_t size,
5174 const char *errors,
5175 int *byteorder,
5176 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005177{
5178 const char *starts = s;
5179 Py_ssize_t startinpos;
5180 Py_ssize_t endinpos;
5181 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005182 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005183 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005184 int bo = 0; /* assume native ordering by default */
5185 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005186 /* Offsets from q for retrieving bytes in the right order. */
5187#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5188 int iorder[] = {0, 1, 2, 3};
5189#else
5190 int iorder[] = {3, 2, 1, 0};
5191#endif
5192 PyObject *errorHandler = NULL;
5193 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005194
Walter Dörwald41980ca2007-08-16 21:55:45 +00005195 q = (unsigned char *)s;
5196 e = q + size;
5197
5198 if (byteorder)
5199 bo = *byteorder;
5200
5201 /* Check for BOM marks (U+FEFF) in the input and adjust current
5202 byte order setting accordingly. In native mode, the leading BOM
5203 mark is skipped, in all other modes, it is copied to the output
5204 stream as-is (giving a ZWNBSP character). */
5205 if (bo == 0) {
5206 if (size >= 4) {
5207 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00005208 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005209#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005210 if (bom == 0x0000FEFF) {
5211 q += 4;
5212 bo = -1;
5213 }
5214 else if (bom == 0xFFFE0000) {
5215 q += 4;
5216 bo = 1;
5217 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005218#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005219 if (bom == 0x0000FEFF) {
5220 q += 4;
5221 bo = 1;
5222 }
5223 else if (bom == 0xFFFE0000) {
5224 q += 4;
5225 bo = -1;
5226 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005227#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005228 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005229 }
5230
5231 if (bo == -1) {
5232 /* force LE */
5233 iorder[0] = 0;
5234 iorder[1] = 1;
5235 iorder[2] = 2;
5236 iorder[3] = 3;
5237 }
5238 else if (bo == 1) {
5239 /* force BE */
5240 iorder[0] = 3;
5241 iorder[1] = 2;
5242 iorder[2] = 1;
5243 iorder[3] = 0;
5244 }
5245
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005246 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005247 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005248 if (!unicode)
5249 return NULL;
5250 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005251 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005252 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005253
Walter Dörwald41980ca2007-08-16 21:55:45 +00005254 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005255 Py_UCS4 ch;
5256 /* remaining bytes at the end? (size should be divisible by 4) */
5257 if (e-q<4) {
5258 if (consumed)
5259 break;
5260 errmsg = "truncated data";
5261 startinpos = ((const char *)q)-starts;
5262 endinpos = ((const char *)e)-starts;
5263 goto utf32Error;
5264 /* The remaining input chars are ignored if the callback
5265 chooses to skip the input */
5266 }
5267 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5268 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005269
Benjamin Peterson29060642009-01-31 22:14:21 +00005270 if (ch >= 0x110000)
5271 {
5272 errmsg = "codepoint not in range(0x110000)";
5273 startinpos = ((const char *)q)-starts;
5274 endinpos = startinpos+4;
5275 goto utf32Error;
5276 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005277 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5278 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005279 q += 4;
5280 continue;
5281 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005282 if (unicode_decode_call_errorhandler(
5283 errors, &errorHandler,
5284 "utf32", errmsg,
5285 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005286 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005287 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005288 }
5289
5290 if (byteorder)
5291 *byteorder = bo;
5292
5293 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005294 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005295
5296 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005297 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005298 goto onError;
5299
5300 Py_XDECREF(errorHandler);
5301 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005302 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005303
Benjamin Peterson29060642009-01-31 22:14:21 +00005304 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005305 Py_DECREF(unicode);
5306 Py_XDECREF(errorHandler);
5307 Py_XDECREF(exc);
5308 return NULL;
5309}
5310
5311PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005312_PyUnicode_EncodeUTF32(PyObject *str,
5313 const char *errors,
5314 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005315{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005316 int kind;
5317 void *data;
5318 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005319 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005320 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005321 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005322 /* Offsets from p for storing byte pairs in the right order. */
5323#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5324 int iorder[] = {0, 1, 2, 3};
5325#else
5326 int iorder[] = {3, 2, 1, 0};
5327#endif
5328
Benjamin Peterson29060642009-01-31 22:14:21 +00005329#define STORECHAR(CH) \
5330 do { \
5331 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5332 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5333 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5334 p[iorder[0]] = (CH) & 0xff; \
5335 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005336 } while(0)
5337
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005338 if (!PyUnicode_Check(str)) {
5339 PyErr_BadArgument();
5340 return NULL;
5341 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005342 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005343 return NULL;
5344 kind = PyUnicode_KIND(str);
5345 data = PyUnicode_DATA(str);
5346 len = PyUnicode_GET_LENGTH(str);
5347
5348 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005349 bytesize = nsize * 4;
5350 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005351 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005352 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005353 if (v == NULL)
5354 return NULL;
5355
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005356 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005357 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005358 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005359 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005360 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005361
5362 if (byteorder == -1) {
5363 /* force LE */
5364 iorder[0] = 0;
5365 iorder[1] = 1;
5366 iorder[2] = 2;
5367 iorder[3] = 3;
5368 }
5369 else if (byteorder == 1) {
5370 /* force BE */
5371 iorder[0] = 3;
5372 iorder[1] = 2;
5373 iorder[2] = 1;
5374 iorder[3] = 0;
5375 }
5376
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005377 for (i = 0; i < len; i++)
5378 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005379
5380 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005381 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005382#undef STORECHAR
5383}
5384
Alexander Belopolsky40018472011-02-26 01:02:56 +00005385PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005386PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5387 Py_ssize_t size,
5388 const char *errors,
5389 int byteorder)
5390{
5391 PyObject *result;
5392 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5393 if (tmp == NULL)
5394 return NULL;
5395 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5396 Py_DECREF(tmp);
5397 return result;
5398}
5399
5400PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005401PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005402{
Victor Stinnerb960b342011-11-20 19:12:52 +01005403 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005404}
5405
Guido van Rossumd57fd912000-03-10 22:53:23 +00005406/* --- UTF-16 Codec ------------------------------------------------------- */
5407
Tim Peters772747b2001-08-09 22:21:55 +00005408PyObject *
5409PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005410 Py_ssize_t size,
5411 const char *errors,
5412 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005413{
Walter Dörwald69652032004-09-07 20:24:22 +00005414 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5415}
5416
Antoine Pitrouab868312009-01-10 15:40:25 +00005417/* Two masks for fast checking of whether a C 'long' may contain
5418 UTF16-encoded surrogate characters. This is an efficient heuristic,
5419 assuming that non-surrogate characters with a code point >= 0x8000 are
5420 rare in most input.
5421 FAST_CHAR_MASK is used when the input is in native byte ordering,
5422 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005423*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005424#if (SIZEOF_LONG == 8)
5425# define FAST_CHAR_MASK 0x8000800080008000L
5426# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
Victor Stinnerafb52052012-04-05 22:54:49 +02005427# define STRIPPED_MASK 0x00FF00FF00FF00FFL
Antoine Pitrouab868312009-01-10 15:40:25 +00005428#elif (SIZEOF_LONG == 4)
5429# define FAST_CHAR_MASK 0x80008000L
5430# define SWAPPED_FAST_CHAR_MASK 0x00800080L
Victor Stinnerafb52052012-04-05 22:54:49 +02005431# define STRIPPED_MASK 0x00FF00FFL
Antoine Pitrouab868312009-01-10 15:40:25 +00005432#else
5433# error C 'long' size should be either 4 or 8!
5434#endif
5435
Walter Dörwald69652032004-09-07 20:24:22 +00005436PyObject *
5437PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005438 Py_ssize_t size,
5439 const char *errors,
5440 int *byteorder,
5441 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005442{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005443 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005444 Py_ssize_t startinpos;
5445 Py_ssize_t endinpos;
5446 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005447 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005448 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005449 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005450 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005451 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005452 /* Offsets from q for retrieving byte pairs in the right order. */
5453#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5454 int ihi = 1, ilo = 0;
5455#else
5456 int ihi = 0, ilo = 1;
5457#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005458 PyObject *errorHandler = NULL;
5459 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005460
5461 /* Note: size will always be longer than the resulting Unicode
5462 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005463 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005464 if (!unicode)
5465 return NULL;
5466 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005467 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005468 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005469
Tim Peters772747b2001-08-09 22:21:55 +00005470 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005471 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005472
5473 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005474 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005475
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005476 /* Check for BOM marks (U+FEFF) in the input and adjust current
5477 byte order setting accordingly. In native mode, the leading BOM
5478 mark is skipped, in all other modes, it is copied to the output
5479 stream as-is (giving a ZWNBSP character). */
5480 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005481 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005482 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005483#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005484 if (bom == 0xFEFF) {
5485 q += 2;
5486 bo = -1;
5487 }
5488 else if (bom == 0xFFFE) {
5489 q += 2;
5490 bo = 1;
5491 }
Tim Petersced69f82003-09-16 20:30:58 +00005492#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005493 if (bom == 0xFEFF) {
5494 q += 2;
5495 bo = 1;
5496 }
5497 else if (bom == 0xFFFE) {
5498 q += 2;
5499 bo = -1;
5500 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005501#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005502 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005503 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005504
Tim Peters772747b2001-08-09 22:21:55 +00005505 if (bo == -1) {
5506 /* force LE */
5507 ihi = 1;
5508 ilo = 0;
5509 }
5510 else if (bo == 1) {
5511 /* force BE */
5512 ihi = 0;
5513 ilo = 1;
5514 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005515#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5516 native_ordering = ilo < ihi;
5517#else
5518 native_ordering = ilo > ihi;
5519#endif
Tim Peters772747b2001-08-09 22:21:55 +00005520
Antoine Pitrouab868312009-01-10 15:40:25 +00005521 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005522 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005523 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005524 /* First check for possible aligned read of a C 'long'. Unaligned
5525 reads are more expensive, better to defer to another iteration. */
5526 if (!((size_t) q & LONG_PTR_MASK)) {
5527 /* Fast path for runs of non-surrogate chars. */
5528 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005529 int kind = PyUnicode_KIND(unicode);
5530 void *data = PyUnicode_DATA(unicode);
5531 while (_q < aligned_end) {
Victor Stinnerafb52052012-04-05 22:54:49 +02005532 unsigned long block = * (unsigned long *) _q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005533 Py_UCS4 maxch;
5534 if (native_ordering) {
5535 /* Can use buffer directly */
Victor Stinnerafb52052012-04-05 22:54:49 +02005536 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005537 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005538 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005539 else {
5540 /* Need to byte-swap */
Victor Stinnerafb52052012-04-05 22:54:49 +02005541 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005542 break;
Victor Stinnerafb52052012-04-05 22:54:49 +02005543 block = ((block >> 8) & STRIPPED_MASK) |
5544 ((block & STRIPPED_MASK) << 8);
Antoine Pitrouab868312009-01-10 15:40:25 +00005545 }
Victor Stinnerafb52052012-04-05 22:54:49 +02005546 maxch = (Py_UCS2)(block & 0xFFFF);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005547#if SIZEOF_LONG == 8
Victor Stinnerafb52052012-04-05 22:54:49 +02005548 ch = (Py_UCS2)((block >> 16) & 0xFFFF);
5549 maxch = Py_MAX(maxch, ch);
5550 ch = (Py_UCS2)((block >> 32) & 0xFFFF);
5551 maxch = Py_MAX(maxch, ch);
5552 ch = (Py_UCS2)(block >> 48);
5553 maxch = Py_MAX(maxch, ch);
5554#else
5555 ch = (Py_UCS2)(block >> 16);
5556 maxch = Py_MAX(maxch, ch);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005557#endif
5558 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5559 if (unicode_widen(&unicode, maxch) < 0)
5560 goto onError;
5561 kind = PyUnicode_KIND(unicode);
5562 data = PyUnicode_DATA(unicode);
5563 }
Victor Stinnerafb52052012-04-05 22:54:49 +02005564#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5565 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)(block & 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005566#if SIZEOF_LONG == 8
Victor Stinnerafb52052012-04-05 22:54:49 +02005567 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)((block >> 16) & 0xFFFF));
5568 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)((block >> 32) & 0xFFFF));
5569 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)((block >> 48)));
5570#else
5571 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)(block >> 16));
5572#endif
5573#else
5574#if SIZEOF_LONG == 8
5575 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)((block >> 48)));
5576 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)((block >> 32) & 0xFFFF));
5577 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)((block >> 16) & 0xFFFF));
5578#else
5579 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)(block >> 16));
5580#endif
5581 PyUnicode_WRITE(kind, data, outpos++, (Py_UCS2)(block & 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005582#endif
5583 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005584 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005585 q = _q;
5586 if (q >= e)
5587 break;
5588 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005589 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005590
Benjamin Peterson14339b62009-01-31 16:36:08 +00005591 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005592
Victor Stinner551ac952011-11-29 22:58:13 +01005593 if (!Py_UNICODE_IS_SURROGATE(ch)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005594 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5595 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005596 continue;
5597 }
5598
5599 /* UTF-16 code pair: */
5600 if (q > e) {
5601 errmsg = "unexpected end of data";
5602 startinpos = (((const char *)q) - 2) - starts;
5603 endinpos = ((const char *)e) + 1 - starts;
5604 goto utf16Error;
5605 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005606 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5607 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005608 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005609 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005610 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005611 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005612 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005613 continue;
5614 }
5615 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005616 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005617 startinpos = (((const char *)q)-4)-starts;
5618 endinpos = startinpos+2;
5619 goto utf16Error;
5620 }
5621
Benjamin Peterson14339b62009-01-31 16:36:08 +00005622 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005623 errmsg = "illegal encoding";
5624 startinpos = (((const char *)q)-2)-starts;
5625 endinpos = startinpos+2;
5626 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005627
Benjamin Peterson29060642009-01-31 22:14:21 +00005628 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005629 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005630 errors,
5631 &errorHandler,
5632 "utf16", errmsg,
5633 &starts,
5634 (const char **)&e,
5635 &startinpos,
5636 &endinpos,
5637 &exc,
5638 (const char **)&q,
5639 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005640 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005641 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005642 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005643 /* remaining byte at the end? (size should be even) */
5644 if (e == q) {
5645 if (!consumed) {
5646 errmsg = "truncated data";
5647 startinpos = ((const char *)q) - starts;
5648 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005649 if (unicode_decode_call_errorhandler(
5650 errors,
5651 &errorHandler,
5652 "utf16", errmsg,
5653 &starts,
5654 (const char **)&e,
5655 &startinpos,
5656 &endinpos,
5657 &exc,
5658 (const char **)&q,
5659 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005660 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005661 goto onError;
5662 /* The remaining input chars are ignored if the callback
5663 chooses to skip the input */
5664 }
5665 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005666
5667 if (byteorder)
5668 *byteorder = bo;
5669
Walter Dörwald69652032004-09-07 20:24:22 +00005670 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005671 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005672
Guido van Rossumd57fd912000-03-10 22:53:23 +00005673 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005674 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005675 goto onError;
5676
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005677 Py_XDECREF(errorHandler);
5678 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005679 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005680
Benjamin Peterson29060642009-01-31 22:14:21 +00005681 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005682 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005683 Py_XDECREF(errorHandler);
5684 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005685 return NULL;
5686}
5687
Antoine Pitrouab868312009-01-10 15:40:25 +00005688#undef FAST_CHAR_MASK
5689#undef SWAPPED_FAST_CHAR_MASK
5690
Tim Peters772747b2001-08-09 22:21:55 +00005691PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005692_PyUnicode_EncodeUTF16(PyObject *str,
5693 const char *errors,
5694 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005695{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005696 int kind;
5697 void *data;
5698 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005699 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005700 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005701 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005702 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005703 /* Offsets from p for storing byte pairs in the right order. */
5704#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5705 int ihi = 1, ilo = 0;
5706#else
5707 int ihi = 0, ilo = 1;
5708#endif
5709
Benjamin Peterson29060642009-01-31 22:14:21 +00005710#define STORECHAR(CH) \
5711 do { \
5712 p[ihi] = ((CH) >> 8) & 0xff; \
5713 p[ilo] = (CH) & 0xff; \
5714 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005715 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005716
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005717 if (!PyUnicode_Check(str)) {
5718 PyErr_BadArgument();
5719 return NULL;
5720 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005721 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005722 return NULL;
5723 kind = PyUnicode_KIND(str);
5724 data = PyUnicode_DATA(str);
5725 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005726
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005727 pairs = 0;
5728 if (kind == PyUnicode_4BYTE_KIND)
5729 for (i = 0; i < len; i++)
5730 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5731 pairs++;
5732 /* 2 * (len + pairs + (byteorder == 0)) */
5733 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005734 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005735 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005736 bytesize = nsize * 2;
5737 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005738 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005739 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740 if (v == NULL)
5741 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005742
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005743 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005744 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005745 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005746 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005747 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005748
5749 if (byteorder == -1) {
5750 /* force LE */
5751 ihi = 1;
5752 ilo = 0;
5753 }
5754 else if (byteorder == 1) {
5755 /* force BE */
5756 ihi = 0;
5757 ilo = 1;
5758 }
5759
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005760 for (i = 0; i < len; i++) {
5761 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5762 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005763 if (ch >= 0x10000) {
Victor Stinner551ac952011-11-29 22:58:13 +01005764 ch2 = Py_UNICODE_LOW_SURROGATE(ch);
5765 ch = Py_UNICODE_HIGH_SURROGATE(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00005766 }
Tim Peters772747b2001-08-09 22:21:55 +00005767 STORECHAR(ch);
5768 if (ch2)
5769 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005770 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005771
5772 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005773 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005774#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005775}
5776
Alexander Belopolsky40018472011-02-26 01:02:56 +00005777PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005778PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5779 Py_ssize_t size,
5780 const char *errors,
5781 int byteorder)
5782{
5783 PyObject *result;
5784 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5785 if (tmp == NULL)
5786 return NULL;
5787 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5788 Py_DECREF(tmp);
5789 return result;
5790}
5791
5792PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005793PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005794{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005795 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005796}
5797
5798/* --- Unicode Escape Codec ----------------------------------------------- */
5799
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005800/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5801 if all the escapes in the string make it still a valid ASCII string.
5802 Returns -1 if any escapes were found which cause the string to
5803 pop out of ASCII range. Otherwise returns the length of the
5804 required buffer to hold the string.
5805 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005806static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005807length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5808{
5809 const unsigned char *p = (const unsigned char *)s;
5810 const unsigned char *end = p + size;
5811 Py_ssize_t length = 0;
5812
5813 if (size < 0)
5814 return -1;
5815
5816 for (; p < end; ++p) {
5817 if (*p > 127) {
5818 /* Non-ASCII */
5819 return -1;
5820 }
5821 else if (*p != '\\') {
5822 /* Normal character */
5823 ++length;
5824 }
5825 else {
5826 /* Backslash-escape, check next char */
5827 ++p;
5828 /* Escape sequence reaches till end of string or
5829 non-ASCII follow-up. */
5830 if (p >= end || *p > 127)
5831 return -1;
5832 switch (*p) {
5833 case '\n':
5834 /* backslash + \n result in zero characters */
5835 break;
5836 case '\\': case '\'': case '\"':
5837 case 'b': case 'f': case 't':
5838 case 'n': case 'r': case 'v': case 'a':
5839 ++length;
5840 break;
5841 case '0': case '1': case '2': case '3':
5842 case '4': case '5': case '6': case '7':
5843 case 'x': case 'u': case 'U': case 'N':
5844 /* these do not guarantee ASCII characters */
5845 return -1;
5846 default:
5847 /* count the backslash + the other character */
5848 length += 2;
5849 }
5850 }
5851 }
5852 return length;
5853}
5854
Fredrik Lundh06d12682001-01-24 07:59:11 +00005855static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005856
Alexander Belopolsky40018472011-02-26 01:02:56 +00005857PyObject *
5858PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005859 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005860 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005861{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005862 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005863 Py_ssize_t startinpos;
5864 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005865 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005866 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005867 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005868 char* message;
5869 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005870 PyObject *errorHandler = NULL;
5871 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005872 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005873 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005874
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005875 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005876
5877 /* After length_of_escaped_ascii_string() there are two alternatives,
5878 either the string is pure ASCII with named escapes like \n, etc.
5879 and we determined it's exact size (common case)
5880 or it contains \x, \u, ... escape sequences. then we create a
5881 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005882 if (len >= 0) {
5883 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005884 if (!v)
5885 goto onError;
5886 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005887 }
5888 else {
5889 /* Escaped strings will always be longer than the resulting
5890 Unicode string, so we start with size here and then reduce the
5891 length after conversion to the true value.
5892 (but if the error callback returns a long replacement string
5893 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005894 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005895 if (!v)
5896 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005897 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005898 }
5899
Guido van Rossumd57fd912000-03-10 22:53:23 +00005900 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005901 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005902 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005903 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005904
Guido van Rossumd57fd912000-03-10 22:53:23 +00005905 while (s < end) {
5906 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005907 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005908 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005909
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005910 /* The only case in which i == ascii_length is a backslash
5911 followed by a newline. */
5912 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005913
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914 /* Non-escape characters are interpreted as Unicode ordinals */
5915 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005916 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5917 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005918 continue;
5919 }
5920
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005921 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005922 /* \ - Escapes */
5923 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005924 c = *s++;
5925 if (s > end)
5926 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005927
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005928 /* The only case in which i == ascii_length is a backslash
5929 followed by a newline. */
5930 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005931
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005932 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933
Benjamin Peterson29060642009-01-31 22:14:21 +00005934 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005935#define WRITECHAR(ch) \
5936 do { \
5937 if (unicode_putchar(&v, &i, ch) < 0) \
5938 goto onError; \
5939 }while(0)
5940
Guido van Rossumd57fd912000-03-10 22:53:23 +00005941 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005942 case '\\': WRITECHAR('\\'); break;
5943 case '\'': WRITECHAR('\''); break;
5944 case '\"': WRITECHAR('\"'); break;
5945 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005946 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005947 case 'f': WRITECHAR('\014'); break;
5948 case 't': WRITECHAR('\t'); break;
5949 case 'n': WRITECHAR('\n'); break;
5950 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005951 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005952 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005953 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005954 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005955
Benjamin Peterson29060642009-01-31 22:14:21 +00005956 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005957 case '0': case '1': case '2': case '3':
5958 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005959 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005960 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005961 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005962 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005963 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005964 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005965 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005966 break;
5967
Benjamin Peterson29060642009-01-31 22:14:21 +00005968 /* hex escapes */
5969 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005970 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005971 digits = 2;
5972 message = "truncated \\xXX escape";
5973 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005974
Benjamin Peterson29060642009-01-31 22:14:21 +00005975 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005976 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005977 digits = 4;
5978 message = "truncated \\uXXXX escape";
5979 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005980
Benjamin Peterson29060642009-01-31 22:14:21 +00005981 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005982 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005983 digits = 8;
5984 message = "truncated \\UXXXXXXXX escape";
5985 hexescape:
5986 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005987 if (s+digits>end) {
5988 endinpos = size;
5989 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005990 errors, &errorHandler,
5991 "unicodeescape", "end of string in escape sequence",
5992 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005993 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005994 goto onError;
5995 goto nextByte;
5996 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005997 for (j = 0; j < digits; ++j) {
5998 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005999 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006000 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006001 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006002 errors, &errorHandler,
6003 "unicodeescape", message,
6004 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006005 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00006006 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006007 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006008 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00006009 }
6010 chr = (chr<<4) & ~0xF;
6011 if (c >= '0' && c <= '9')
6012 chr += c - '0';
6013 else if (c >= 'a' && c <= 'f')
6014 chr += 10 + c - 'a';
6015 else
6016 chr += 10 + c - 'A';
6017 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006018 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00006019 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006020 /* _decoding_error will have already written into the
6021 target buffer. */
6022 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006023 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00006024 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01006025 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006026 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00006027 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006028 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006029 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006030 errors, &errorHandler,
6031 "unicodeescape", "illegal Unicode character",
6032 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006033 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00006034 goto onError;
6035 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006036 break;
6037
Benjamin Peterson29060642009-01-31 22:14:21 +00006038 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006039 case 'N':
6040 message = "malformed \\N character escape";
6041 if (ucnhash_CAPI == NULL) {
6042 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006043 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6044 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00006045 if (ucnhash_CAPI == NULL)
6046 goto ucnhashError;
6047 }
6048 if (*s == '{') {
6049 const char *start = s+1;
6050 /* look for the closing brace */
6051 while (*s != '}' && s < end)
6052 s++;
6053 if (s > start && s < end && *s == '}') {
6054 /* found a name. look it up in the unicode database */
6055 message = "unknown Unicode character name";
6056 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006057 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03006058 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00006059 goto store;
6060 }
6061 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006062 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006063 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006064 errors, &errorHandler,
6065 "unicodeescape", message,
6066 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006067 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00006068 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006069 break;
6070
6071 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00006072 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006073 message = "\\ at end of string";
6074 s--;
6075 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006076 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006077 errors, &errorHandler,
6078 "unicodeescape", message,
6079 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006080 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00006081 goto onError;
6082 }
6083 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006084 WRITECHAR('\\');
6085 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00006086 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006087 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006088 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006089 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006090 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006091 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006092#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006093
Victor Stinner16e6a802011-12-12 13:24:15 +01006094 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006095 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006096 Py_XDECREF(errorHandler);
6097 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006098 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00006099
Benjamin Peterson29060642009-01-31 22:14:21 +00006100 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00006101 PyErr_SetString(
6102 PyExc_UnicodeError,
6103 "\\N escapes not supported (can't load unicodedata module)"
6104 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00006105 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006106 Py_XDECREF(errorHandler);
6107 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00006108 return NULL;
6109
Benjamin Peterson29060642009-01-31 22:14:21 +00006110 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006111 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006112 Py_XDECREF(errorHandler);
6113 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006114 return NULL;
6115}
6116
6117/* Return a Unicode-Escape string version of the Unicode object.
6118
6119 If quotes is true, the string is enclosed in u"" or u'' quotes as
6120 appropriate.
6121
6122*/
6123
Alexander Belopolsky40018472011-02-26 01:02:56 +00006124PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006125PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006126{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006127 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006128 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006129 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006130 int kind;
6131 void *data;
6132 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006133
Thomas Wouters89f507f2006-12-13 04:49:30 +00006134 /* Initial allocation is based on the longest-possible unichr
6135 escape.
6136
6137 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
6138 unichr, so in this case it's the longest unichr escape. In
6139 narrow (UTF-16) builds this is five chars per source unichr
6140 since there are two unichrs in the surrogate pair, so in narrow
6141 (UTF-16) builds it's not the longest unichr escape.
6142
6143 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
6144 so in the narrow (UTF-16) build case it's the longest unichr
6145 escape.
6146 */
6147
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006148 if (!PyUnicode_Check(unicode)) {
6149 PyErr_BadArgument();
6150 return NULL;
6151 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006152 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006153 return NULL;
6154 len = PyUnicode_GET_LENGTH(unicode);
6155 kind = PyUnicode_KIND(unicode);
6156 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06006157 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006158 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6159 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6160 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6161 }
6162
6163 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006164 return PyBytes_FromStringAndSize(NULL, 0);
6165
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006166 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006167 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006168
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006169 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00006170 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006171 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00006172 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006173 if (repr == NULL)
6174 return NULL;
6175
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006176 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006177
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006178 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006179 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006180
Walter Dörwald79e913e2007-05-12 11:08:06 +00006181 /* Escape backslashes */
6182 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006183 *p++ = '\\';
6184 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00006185 continue;
Tim Petersced69f82003-09-16 20:30:58 +00006186 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006187
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006188 /* Map 21-bit characters to '\U00xxxxxx' */
6189 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006190 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006191 *p++ = '\\';
6192 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006193 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
6194 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
6195 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6196 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6197 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6198 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6199 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6200 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006201 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006202 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006203
Guido van Rossumd57fd912000-03-10 22:53:23 +00006204 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006205 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006206 *p++ = '\\';
6207 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006208 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6209 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6210 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6211 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006212 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006213
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006214 /* Map special whitespace to '\t', \n', '\r' */
6215 else if (ch == '\t') {
6216 *p++ = '\\';
6217 *p++ = 't';
6218 }
6219 else if (ch == '\n') {
6220 *p++ = '\\';
6221 *p++ = 'n';
6222 }
6223 else if (ch == '\r') {
6224 *p++ = '\\';
6225 *p++ = 'r';
6226 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006227
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006228 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006229 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006230 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006231 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006232 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6233 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006234 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006235
Guido van Rossumd57fd912000-03-10 22:53:23 +00006236 /* Copy everything else as-is */
6237 else
6238 *p++ = (char) ch;
6239 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006240
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006241 assert(p - PyBytes_AS_STRING(repr) > 0);
6242 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6243 return NULL;
6244 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006245}
6246
Alexander Belopolsky40018472011-02-26 01:02:56 +00006247PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006248PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6249 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006250{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006251 PyObject *result;
6252 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6253 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006254 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006255 result = PyUnicode_AsUnicodeEscapeString(tmp);
6256 Py_DECREF(tmp);
6257 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006258}
6259
6260/* --- Raw Unicode Escape Codec ------------------------------------------- */
6261
Alexander Belopolsky40018472011-02-26 01:02:56 +00006262PyObject *
6263PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006264 Py_ssize_t size,
6265 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006266{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006267 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006268 Py_ssize_t startinpos;
6269 Py_ssize_t endinpos;
6270 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006271 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006272 const char *end;
6273 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006274 PyObject *errorHandler = NULL;
6275 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006276
Guido van Rossumd57fd912000-03-10 22:53:23 +00006277 /* Escaped strings will always be longer than the resulting
6278 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006279 length after conversion to the true value. (But decoding error
6280 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006281 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006282 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006283 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006284 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006285 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006286 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006287 end = s + size;
6288 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006289 unsigned char c;
6290 Py_UCS4 x;
6291 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006292 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006293
Benjamin Peterson29060642009-01-31 22:14:21 +00006294 /* Non-escape characters are interpreted as Unicode ordinals */
6295 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006296 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6297 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006298 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006299 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006300 startinpos = s-starts;
6301
6302 /* \u-escapes are only interpreted iff the number of leading
6303 backslashes if odd */
6304 bs = s;
6305 for (;s < end;) {
6306 if (*s != '\\')
6307 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006308 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6309 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006310 }
6311 if (((s - bs) & 1) == 0 ||
6312 s >= end ||
6313 (*s != 'u' && *s != 'U')) {
6314 continue;
6315 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006316 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006317 count = *s=='u' ? 4 : 8;
6318 s++;
6319
6320 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006321 for (x = 0, i = 0; i < count; ++i, ++s) {
6322 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006323 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006324 endinpos = s-starts;
6325 if (unicode_decode_call_errorhandler(
6326 errors, &errorHandler,
6327 "rawunicodeescape", "truncated \\uXXXX",
6328 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006329 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006330 goto onError;
6331 goto nextByte;
6332 }
6333 x = (x<<4) & ~0xF;
6334 if (c >= '0' && c <= '9')
6335 x += c - '0';
6336 else if (c >= 'a' && c <= 'f')
6337 x += 10 + c - 'a';
6338 else
6339 x += 10 + c - 'A';
6340 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006341 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006342 if (unicode_putchar(&v, &outpos, x) < 0)
6343 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006344 } else {
6345 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006346 if (unicode_decode_call_errorhandler(
6347 errors, &errorHandler,
6348 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006349 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006350 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006351 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006352 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006353 nextByte:
6354 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006355 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006356 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006357 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006358 Py_XDECREF(errorHandler);
6359 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006360 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006361
Benjamin Peterson29060642009-01-31 22:14:21 +00006362 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006363 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006364 Py_XDECREF(errorHandler);
6365 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006366 return NULL;
6367}
6368
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006369
Alexander Belopolsky40018472011-02-26 01:02:56 +00006370PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006371PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006372{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006373 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006374 char *p;
6375 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006376 Py_ssize_t expandsize, pos;
6377 int kind;
6378 void *data;
6379 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006380
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006381 if (!PyUnicode_Check(unicode)) {
6382 PyErr_BadArgument();
6383 return NULL;
6384 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006385 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006386 return NULL;
6387 kind = PyUnicode_KIND(unicode);
6388 data = PyUnicode_DATA(unicode);
6389 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006390 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6391 bytes, and 1 byte characters 4. */
6392 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006393
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006394 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006395 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006396
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006397 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006398 if (repr == NULL)
6399 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006400 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006401 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006402
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006403 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006404 for (pos = 0; pos < len; pos++) {
6405 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006406 /* Map 32-bit characters to '\Uxxxxxxxx' */
6407 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006408 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006409 *p++ = '\\';
6410 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006411 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6412 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6413 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6414 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6415 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6416 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6417 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6418 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006419 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006420 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006421 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006422 *p++ = '\\';
6423 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006424 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6425 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6426 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6427 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006428 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006429 /* Copy everything else as-is */
6430 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006431 *p++ = (char) ch;
6432 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006433
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006434 assert(p > q);
6435 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006436 return NULL;
6437 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006438}
6439
Alexander Belopolsky40018472011-02-26 01:02:56 +00006440PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006441PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6442 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006443{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006444 PyObject *result;
6445 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6446 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006447 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006448 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6449 Py_DECREF(tmp);
6450 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006451}
6452
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006453/* --- Unicode Internal Codec ------------------------------------------- */
6454
Alexander Belopolsky40018472011-02-26 01:02:56 +00006455PyObject *
6456_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006457 Py_ssize_t size,
6458 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006459{
6460 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006461 Py_ssize_t startinpos;
6462 Py_ssize_t endinpos;
6463 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006464 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006465 const char *end;
6466 const char *reason;
6467 PyObject *errorHandler = NULL;
6468 PyObject *exc = NULL;
6469
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006470 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006471 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006472 1))
6473 return NULL;
6474
Thomas Wouters89f507f2006-12-13 04:49:30 +00006475 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006476 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006477 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006478 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006479 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006480 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006481 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006482 end = s + size;
6483
6484 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006485 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006486 Py_UCS4 ch;
6487 /* We copy the raw representation one byte at a time because the
6488 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006489 ((char *) &uch)[0] = s[0];
6490 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006491#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006492 ((char *) &uch)[2] = s[2];
6493 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006494#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006495 ch = uch;
6496
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006497 /* We have to sanity check the raw data, otherwise doom looms for
6498 some malformed UCS-4 data. */
6499 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006500#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006501 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006502#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006503 end-s < Py_UNICODE_SIZE
6504 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006505 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006506 startinpos = s - starts;
6507 if (end-s < Py_UNICODE_SIZE) {
6508 endinpos = end-starts;
6509 reason = "truncated input";
6510 }
6511 else {
6512 endinpos = s - starts + Py_UNICODE_SIZE;
6513 reason = "illegal code point (> 0x10FFFF)";
6514 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006515 if (unicode_decode_call_errorhandler(
6516 errors, &errorHandler,
6517 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006518 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006519 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006520 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006521 continue;
6522 }
6523
6524 s += Py_UNICODE_SIZE;
6525#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006526 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006527 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006528 Py_UNICODE uch2;
6529 ((char *) &uch2)[0] = s[0];
6530 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006531 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006532 {
Victor Stinner551ac952011-11-29 22:58:13 +01006533 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006534 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006535 }
6536 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006537#endif
6538
6539 if (unicode_putchar(&v, &outpos, ch) < 0)
6540 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006541 }
6542
Victor Stinner16e6a802011-12-12 13:24:15 +01006543 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006544 goto onError;
6545 Py_XDECREF(errorHandler);
6546 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006547 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006548
Benjamin Peterson29060642009-01-31 22:14:21 +00006549 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006550 Py_XDECREF(v);
6551 Py_XDECREF(errorHandler);
6552 Py_XDECREF(exc);
6553 return NULL;
6554}
6555
Guido van Rossumd57fd912000-03-10 22:53:23 +00006556/* --- Latin-1 Codec ------------------------------------------------------ */
6557
Alexander Belopolsky40018472011-02-26 01:02:56 +00006558PyObject *
6559PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006560 Py_ssize_t size,
6561 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006562{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006563 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006564 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006565}
6566
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006567/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006568static void
6569make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006570 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006571 PyObject *unicode,
6572 Py_ssize_t startpos, Py_ssize_t endpos,
6573 const char *reason)
6574{
6575 if (*exceptionObject == NULL) {
6576 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006577 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006578 encoding, unicode, startpos, endpos, reason);
6579 }
6580 else {
6581 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6582 goto onError;
6583 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6584 goto onError;
6585 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6586 goto onError;
6587 return;
6588 onError:
6589 Py_DECREF(*exceptionObject);
6590 *exceptionObject = NULL;
6591 }
6592}
6593
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006594/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006595static void
6596raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006597 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006598 PyObject *unicode,
6599 Py_ssize_t startpos, Py_ssize_t endpos,
6600 const char *reason)
6601{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006602 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006603 encoding, unicode, startpos, endpos, reason);
6604 if (*exceptionObject != NULL)
6605 PyCodec_StrictErrors(*exceptionObject);
6606}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006607
6608/* error handling callback helper:
6609 build arguments, call the callback and check the arguments,
6610 put the result into newpos and return the replacement string, which
6611 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006612static PyObject *
6613unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006614 PyObject **errorHandler,
6615 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006616 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006617 Py_ssize_t startpos, Py_ssize_t endpos,
6618 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006619{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006620 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006621 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006622 PyObject *restuple;
6623 PyObject *resunicode;
6624
6625 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006626 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006627 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006628 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006629 }
6630
Benjamin Petersonbac79492012-01-14 13:34:47 -05006631 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006632 return NULL;
6633 len = PyUnicode_GET_LENGTH(unicode);
6634
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006635 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006636 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006637 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006638 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006639
6640 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006641 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006642 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006643 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006644 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006645 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006646 Py_DECREF(restuple);
6647 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006648 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006649 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006650 &resunicode, newpos)) {
6651 Py_DECREF(restuple);
6652 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006653 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006654 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6655 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6656 Py_DECREF(restuple);
6657 return NULL;
6658 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006659 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006660 *newpos = len + *newpos;
6661 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006662 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6663 Py_DECREF(restuple);
6664 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006665 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006666 Py_INCREF(resunicode);
6667 Py_DECREF(restuple);
6668 return resunicode;
6669}
6670
Alexander Belopolsky40018472011-02-26 01:02:56 +00006671static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006672unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006673 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006674 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006675{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006676 /* input state */
6677 Py_ssize_t pos=0, size;
6678 int kind;
6679 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006680 /* output object */
6681 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006682 /* pointer into the output */
6683 char *str;
6684 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006685 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006686 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6687 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006688 PyObject *errorHandler = NULL;
6689 PyObject *exc = NULL;
6690 /* the following variable is used for caching string comparisons
6691 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6692 int known_errorHandler = -1;
6693
Benjamin Petersonbac79492012-01-14 13:34:47 -05006694 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006695 return NULL;
6696 size = PyUnicode_GET_LENGTH(unicode);
6697 kind = PyUnicode_KIND(unicode);
6698 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006699 /* allocate enough for a simple encoding without
6700 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006701 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006702 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006703 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006704 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006705 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006706 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006707 ressize = size;
6708
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006709 while (pos < size) {
6710 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006711
Benjamin Peterson29060642009-01-31 22:14:21 +00006712 /* can we encode this? */
6713 if (c<limit) {
6714 /* no overflow check, because we know that the space is enough */
6715 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006716 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006717 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006718 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006719 Py_ssize_t requiredsize;
6720 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006721 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006722 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006723 Py_ssize_t collstart = pos;
6724 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006725 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006726 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006727 ++collend;
6728 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6729 if (known_errorHandler==-1) {
6730 if ((errors==NULL) || (!strcmp(errors, "strict")))
6731 known_errorHandler = 1;
6732 else if (!strcmp(errors, "replace"))
6733 known_errorHandler = 2;
6734 else if (!strcmp(errors, "ignore"))
6735 known_errorHandler = 3;
6736 else if (!strcmp(errors, "xmlcharrefreplace"))
6737 known_errorHandler = 4;
6738 else
6739 known_errorHandler = 0;
6740 }
6741 switch (known_errorHandler) {
6742 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006743 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006744 goto onError;
6745 case 2: /* replace */
6746 while (collstart++<collend)
6747 *str++ = '?'; /* fall through */
6748 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006749 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006750 break;
6751 case 4: /* xmlcharrefreplace */
6752 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006753 /* determine replacement size */
6754 for (i = collstart, repsize = 0; i < collend; ++i) {
6755 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6756 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006757 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006758 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006759 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006760 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006761 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006762 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006763 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006764 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006765 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006766 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006767 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006768 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006769 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006770 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006771 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006772 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006773 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006774 if (requiredsize > ressize) {
6775 if (requiredsize<2*ressize)
6776 requiredsize = 2*ressize;
6777 if (_PyBytes_Resize(&res, requiredsize))
6778 goto onError;
6779 str = PyBytes_AS_STRING(res) + respos;
6780 ressize = requiredsize;
6781 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006782 /* generate replacement */
6783 for (i = collstart; i < collend; ++i) {
6784 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006785 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006786 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006787 break;
6788 default:
6789 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006790 encoding, reason, unicode, &exc,
6791 collstart, collend, &newpos);
6792 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006793 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006794 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006795 if (PyBytes_Check(repunicode)) {
6796 /* Directly copy bytes result to output. */
6797 repsize = PyBytes_Size(repunicode);
6798 if (repsize > 1) {
6799 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006800 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006801 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6802 Py_DECREF(repunicode);
6803 goto onError;
6804 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006805 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006806 ressize += repsize-1;
6807 }
6808 memcpy(str, PyBytes_AsString(repunicode), repsize);
6809 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006810 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006811 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006812 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006813 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006814 /* need more space? (at least enough for what we
6815 have+the replacement+the rest of the string, so
6816 we won't have to check space for encodable characters) */
6817 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006818 repsize = PyUnicode_GET_LENGTH(repunicode);
6819 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006820 if (requiredsize > ressize) {
6821 if (requiredsize<2*ressize)
6822 requiredsize = 2*ressize;
6823 if (_PyBytes_Resize(&res, requiredsize)) {
6824 Py_DECREF(repunicode);
6825 goto onError;
6826 }
6827 str = PyBytes_AS_STRING(res) + respos;
6828 ressize = requiredsize;
6829 }
6830 /* check if there is anything unencodable in the replacement
6831 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006832 for (i = 0; repsize-->0; ++i, ++str) {
6833 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006834 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006835 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006836 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006837 Py_DECREF(repunicode);
6838 goto onError;
6839 }
6840 *str = (char)c;
6841 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006842 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006843 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006844 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006845 }
6846 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006847 /* Resize if we allocated to much */
6848 size = str - PyBytes_AS_STRING(res);
6849 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006850 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006851 if (_PyBytes_Resize(&res, size) < 0)
6852 goto onError;
6853 }
6854
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006855 Py_XDECREF(errorHandler);
6856 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006857 return res;
6858
6859 onError:
6860 Py_XDECREF(res);
6861 Py_XDECREF(errorHandler);
6862 Py_XDECREF(exc);
6863 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006864}
6865
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006866/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006867PyObject *
6868PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006869 Py_ssize_t size,
6870 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006871{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006872 PyObject *result;
6873 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6874 if (unicode == NULL)
6875 return NULL;
6876 result = unicode_encode_ucs1(unicode, errors, 256);
6877 Py_DECREF(unicode);
6878 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006879}
6880
Alexander Belopolsky40018472011-02-26 01:02:56 +00006881PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006882_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006883{
6884 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006885 PyErr_BadArgument();
6886 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006887 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006888 if (PyUnicode_READY(unicode) == -1)
6889 return NULL;
6890 /* Fast path: if it is a one-byte string, construct
6891 bytes object directly. */
6892 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6893 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6894 PyUnicode_GET_LENGTH(unicode));
6895 /* Non-Latin-1 characters present. Defer to above function to
6896 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006897 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006898}
6899
6900PyObject*
6901PyUnicode_AsLatin1String(PyObject *unicode)
6902{
6903 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006904}
6905
6906/* --- 7-bit ASCII Codec -------------------------------------------------- */
6907
Alexander Belopolsky40018472011-02-26 01:02:56 +00006908PyObject *
6909PyUnicode_DecodeASCII(const char *s,
6910 Py_ssize_t size,
6911 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006912{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006913 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006914 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006915 int kind;
6916 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006917 Py_ssize_t startinpos;
6918 Py_ssize_t endinpos;
6919 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006920 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006921 int has_error;
6922 const unsigned char *p = (const unsigned char *)s;
6923 const unsigned char *end = p + size;
6924 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006925 PyObject *errorHandler = NULL;
6926 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006927
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006928 if (size == 0) {
6929 Py_INCREF(unicode_empty);
6930 return unicode_empty;
6931 }
6932
Guido van Rossumd57fd912000-03-10 22:53:23 +00006933 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006934 if (size == 1 && (unsigned char)s[0] < 128)
6935 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006936
Victor Stinner702c7342011-10-05 13:50:52 +02006937 has_error = 0;
6938 while (p < end && !has_error) {
6939 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6940 an explanation. */
6941 if (!((size_t) p & LONG_PTR_MASK)) {
6942 /* Help register allocation */
6943 register const unsigned char *_p = p;
6944 while (_p < aligned_end) {
6945 unsigned long value = *(unsigned long *) _p;
6946 if (value & ASCII_CHAR_MASK) {
6947 has_error = 1;
6948 break;
6949 }
6950 _p += SIZEOF_LONG;
6951 }
6952 if (_p == end)
6953 break;
6954 if (has_error)
6955 break;
6956 p = _p;
6957 }
6958 if (*p & 0x80) {
6959 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006960 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006961 }
6962 else {
6963 ++p;
6964 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006965 }
Victor Stinner702c7342011-10-05 13:50:52 +02006966 if (!has_error)
6967 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006968
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006969 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006970 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006971 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006972 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006973 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006974 kind = PyUnicode_KIND(v);
6975 data = PyUnicode_DATA(v);
6976 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006977 e = s + size;
6978 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006979 register unsigned char c = (unsigned char)*s;
6980 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006981 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006982 ++s;
6983 }
6984 else {
6985 startinpos = s-starts;
6986 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006987 if (unicode_decode_call_errorhandler(
6988 errors, &errorHandler,
6989 "ascii", "ordinal not in range(128)",
6990 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006991 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006992 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006993 kind = PyUnicode_KIND(v);
6994 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006995 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006996 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006997 if (unicode_resize(&v, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006998 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006999 Py_XDECREF(errorHandler);
7000 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007001 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01007002 return v;
Tim Petersced69f82003-09-16 20:30:58 +00007003
Benjamin Peterson29060642009-01-31 22:14:21 +00007004 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007005 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007006 Py_XDECREF(errorHandler);
7007 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007008 return NULL;
7009}
7010
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007011/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007012PyObject *
7013PyUnicode_EncodeASCII(const Py_UNICODE *p,
7014 Py_ssize_t size,
7015 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007016{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007017 PyObject *result;
7018 PyObject *unicode = PyUnicode_FromUnicode(p, size);
7019 if (unicode == NULL)
7020 return NULL;
7021 result = unicode_encode_ucs1(unicode, errors, 128);
7022 Py_DECREF(unicode);
7023 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007024}
7025
Alexander Belopolsky40018472011-02-26 01:02:56 +00007026PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007027_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007028{
7029 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007030 PyErr_BadArgument();
7031 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007032 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007033 if (PyUnicode_READY(unicode) == -1)
7034 return NULL;
7035 /* Fast path: if it is an ASCII-only string, construct bytes object
7036 directly. Else defer to above function to raise the exception. */
7037 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
7038 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7039 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007040 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007041}
7042
7043PyObject *
7044PyUnicode_AsASCIIString(PyObject *unicode)
7045{
7046 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007047}
7048
Victor Stinner99b95382011-07-04 14:23:54 +02007049#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007050
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007051/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007052
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007053#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007054#define NEED_RETRY
7055#endif
7056
Victor Stinner3a50e702011-10-18 21:21:00 +02007057#ifndef WC_ERR_INVALID_CHARS
7058# define WC_ERR_INVALID_CHARS 0x0080
7059#endif
7060
7061static char*
7062code_page_name(UINT code_page, PyObject **obj)
7063{
7064 *obj = NULL;
7065 if (code_page == CP_ACP)
7066 return "mbcs";
7067 if (code_page == CP_UTF7)
7068 return "CP_UTF7";
7069 if (code_page == CP_UTF8)
7070 return "CP_UTF8";
7071
7072 *obj = PyBytes_FromFormat("cp%u", code_page);
7073 if (*obj == NULL)
7074 return NULL;
7075 return PyBytes_AS_STRING(*obj);
7076}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007077
Alexander Belopolsky40018472011-02-26 01:02:56 +00007078static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007079is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007080{
7081 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02007082 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007083
Victor Stinner3a50e702011-10-18 21:21:00 +02007084 if (!IsDBCSLeadByteEx(code_page, *curr))
7085 return 0;
7086
7087 prev = CharPrevExA(code_page, s, curr, 0);
7088 if (prev == curr)
7089 return 1;
7090 /* FIXME: This code is limited to "true" double-byte encodings,
7091 as it assumes an incomplete character consists of a single
7092 byte. */
7093 if (curr - prev == 2)
7094 return 1;
7095 if (!IsDBCSLeadByteEx(code_page, *prev))
7096 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007097 return 0;
7098}
7099
Victor Stinner3a50e702011-10-18 21:21:00 +02007100static DWORD
7101decode_code_page_flags(UINT code_page)
7102{
7103 if (code_page == CP_UTF7) {
7104 /* The CP_UTF7 decoder only supports flags=0 */
7105 return 0;
7106 }
7107 else
7108 return MB_ERR_INVALID_CHARS;
7109}
7110
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007111/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007112 * Decode a byte string from a Windows code page into unicode object in strict
7113 * mode.
7114 *
7115 * Returns consumed size if succeed, returns -2 on decode error, or raise a
7116 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007117 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007118static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007119decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007120 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007121 const char *in,
7122 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007123{
Victor Stinner3a50e702011-10-18 21:21:00 +02007124 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007125 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007126 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007127
7128 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007129 assert(insize > 0);
7130 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7131 if (outsize <= 0)
7132 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007133
7134 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007135 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007136 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007137 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007138 if (*v == NULL)
7139 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007140 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007141 }
7142 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007143 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007144 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007145 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007146 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007147 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007148 }
7149
7150 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007151 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7152 if (outsize <= 0)
7153 goto error;
7154 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007155
Victor Stinner3a50e702011-10-18 21:21:00 +02007156error:
7157 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7158 return -2;
7159 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007160 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007161}
7162
Victor Stinner3a50e702011-10-18 21:21:00 +02007163/*
7164 * Decode a byte string from a code page into unicode object with an error
7165 * handler.
7166 *
7167 * Returns consumed size if succeed, or raise a WindowsError or
7168 * UnicodeDecodeError exception and returns -1 on error.
7169 */
7170static int
7171decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007172 PyObject **v,
7173 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007174 const char *errors)
7175{
7176 const char *startin = in;
7177 const char *endin = in + size;
7178 const DWORD flags = decode_code_page_flags(code_page);
7179 /* Ideally, we should get reason from FormatMessage. This is the Windows
7180 2000 English version of the message. */
7181 const char *reason = "No mapping for the Unicode character exists "
7182 "in the target code page.";
7183 /* each step cannot decode more than 1 character, but a character can be
7184 represented as a surrogate pair */
7185 wchar_t buffer[2], *startout, *out;
7186 int insize, outsize;
7187 PyObject *errorHandler = NULL;
7188 PyObject *exc = NULL;
7189 PyObject *encoding_obj = NULL;
7190 char *encoding;
7191 DWORD err;
7192 int ret = -1;
7193
7194 assert(size > 0);
7195
7196 encoding = code_page_name(code_page, &encoding_obj);
7197 if (encoding == NULL)
7198 return -1;
7199
7200 if (errors == NULL || strcmp(errors, "strict") == 0) {
7201 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7202 UnicodeDecodeError. */
7203 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7204 if (exc != NULL) {
7205 PyCodec_StrictErrors(exc);
7206 Py_CLEAR(exc);
7207 }
7208 goto error;
7209 }
7210
7211 if (*v == NULL) {
7212 /* Create unicode object */
7213 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7214 PyErr_NoMemory();
7215 goto error;
7216 }
Victor Stinnerab595942011-12-17 04:59:06 +01007217 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007218 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 if (*v == NULL)
7220 goto error;
7221 startout = PyUnicode_AS_UNICODE(*v);
7222 }
7223 else {
7224 /* Extend unicode object */
7225 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7226 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7227 PyErr_NoMemory();
7228 goto error;
7229 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007230 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007231 goto error;
7232 startout = PyUnicode_AS_UNICODE(*v) + n;
7233 }
7234
7235 /* Decode the byte string character per character */
7236 out = startout;
7237 while (in < endin)
7238 {
7239 /* Decode a character */
7240 insize = 1;
7241 do
7242 {
7243 outsize = MultiByteToWideChar(code_page, flags,
7244 in, insize,
7245 buffer, Py_ARRAY_LENGTH(buffer));
7246 if (outsize > 0)
7247 break;
7248 err = GetLastError();
7249 if (err != ERROR_NO_UNICODE_TRANSLATION
7250 && err != ERROR_INSUFFICIENT_BUFFER)
7251 {
7252 PyErr_SetFromWindowsErr(0);
7253 goto error;
7254 }
7255 insize++;
7256 }
7257 /* 4=maximum length of a UTF-8 sequence */
7258 while (insize <= 4 && (in + insize) <= endin);
7259
7260 if (outsize <= 0) {
7261 Py_ssize_t startinpos, endinpos, outpos;
7262
7263 startinpos = in - startin;
7264 endinpos = startinpos + 1;
7265 outpos = out - PyUnicode_AS_UNICODE(*v);
7266 if (unicode_decode_call_errorhandler(
7267 errors, &errorHandler,
7268 encoding, reason,
7269 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007270 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007271 {
7272 goto error;
7273 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007274 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007275 }
7276 else {
7277 in += insize;
7278 memcpy(out, buffer, outsize * sizeof(wchar_t));
7279 out += outsize;
7280 }
7281 }
7282
7283 /* write a NUL character at the end */
7284 *out = 0;
7285
7286 /* Extend unicode object */
7287 outsize = out - startout;
7288 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007289 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007290 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007291 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007292
7293error:
7294 Py_XDECREF(encoding_obj);
7295 Py_XDECREF(errorHandler);
7296 Py_XDECREF(exc);
7297 return ret;
7298}
7299
Victor Stinner3a50e702011-10-18 21:21:00 +02007300static PyObject *
7301decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007302 const char *s, Py_ssize_t size,
7303 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007304{
Victor Stinner76a31a62011-11-04 00:05:13 +01007305 PyObject *v = NULL;
7306 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007307
Victor Stinner3a50e702011-10-18 21:21:00 +02007308 if (code_page < 0) {
7309 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7310 return NULL;
7311 }
7312
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007313 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007314 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007315
Victor Stinner76a31a62011-11-04 00:05:13 +01007316 do
7317 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007318#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007319 if (size > INT_MAX) {
7320 chunk_size = INT_MAX;
7321 final = 0;
7322 done = 0;
7323 }
7324 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007325#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007326 {
7327 chunk_size = (int)size;
7328 final = (consumed == NULL);
7329 done = 1;
7330 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007331
Victor Stinner76a31a62011-11-04 00:05:13 +01007332 /* Skip trailing lead-byte unless 'final' is set */
7333 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7334 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007335
Victor Stinner76a31a62011-11-04 00:05:13 +01007336 if (chunk_size == 0 && done) {
7337 if (v != NULL)
7338 break;
7339 Py_INCREF(unicode_empty);
7340 return unicode_empty;
7341 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007342
Victor Stinner76a31a62011-11-04 00:05:13 +01007343
7344 converted = decode_code_page_strict(code_page, &v,
7345 s, chunk_size);
7346 if (converted == -2)
7347 converted = decode_code_page_errors(code_page, &v,
7348 s, chunk_size,
7349 errors);
7350 assert(converted != 0);
7351
7352 if (converted < 0) {
7353 Py_XDECREF(v);
7354 return NULL;
7355 }
7356
7357 if (consumed)
7358 *consumed += converted;
7359
7360 s += converted;
7361 size -= converted;
7362 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007363
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007364 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007365}
7366
Alexander Belopolsky40018472011-02-26 01:02:56 +00007367PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007368PyUnicode_DecodeCodePageStateful(int code_page,
7369 const char *s,
7370 Py_ssize_t size,
7371 const char *errors,
7372 Py_ssize_t *consumed)
7373{
7374 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7375}
7376
7377PyObject *
7378PyUnicode_DecodeMBCSStateful(const char *s,
7379 Py_ssize_t size,
7380 const char *errors,
7381 Py_ssize_t *consumed)
7382{
7383 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7384}
7385
7386PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007387PyUnicode_DecodeMBCS(const char *s,
7388 Py_ssize_t size,
7389 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007390{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007391 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7392}
7393
Victor Stinner3a50e702011-10-18 21:21:00 +02007394static DWORD
7395encode_code_page_flags(UINT code_page, const char *errors)
7396{
7397 if (code_page == CP_UTF8) {
7398 if (winver.dwMajorVersion >= 6)
7399 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7400 and later */
7401 return WC_ERR_INVALID_CHARS;
7402 else
7403 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7404 return 0;
7405 }
7406 else if (code_page == CP_UTF7) {
7407 /* CP_UTF7 only supports flags=0 */
7408 return 0;
7409 }
7410 else {
7411 if (errors != NULL && strcmp(errors, "replace") == 0)
7412 return 0;
7413 else
7414 return WC_NO_BEST_FIT_CHARS;
7415 }
7416}
7417
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007418/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007419 * Encode a Unicode string to a Windows code page into a byte string in strict
7420 * mode.
7421 *
7422 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7423 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007424 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007425static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007426encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007427 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007428 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007429{
Victor Stinner554f3f02010-06-16 23:33:54 +00007430 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007431 BOOL *pusedDefaultChar = &usedDefaultChar;
7432 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007433 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007434 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007435 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007436 const DWORD flags = encode_code_page_flags(code_page, NULL);
7437 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007438 /* Create a substring so that we can get the UTF-16 representation
7439 of just the slice under consideration. */
7440 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007441
Martin v. Löwis3d325192011-11-04 18:23:06 +01007442 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007443
Victor Stinner3a50e702011-10-18 21:21:00 +02007444 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007445 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007446 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007447 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007448
Victor Stinner2fc507f2011-11-04 20:06:39 +01007449 substring = PyUnicode_Substring(unicode, offset, offset+len);
7450 if (substring == NULL)
7451 return -1;
7452 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7453 if (p == NULL) {
7454 Py_DECREF(substring);
7455 return -1;
7456 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007457
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007458 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007459 outsize = WideCharToMultiByte(code_page, flags,
7460 p, size,
7461 NULL, 0,
7462 NULL, pusedDefaultChar);
7463 if (outsize <= 0)
7464 goto error;
7465 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007466 if (pusedDefaultChar && *pusedDefaultChar) {
7467 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007468 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007469 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007470
Victor Stinner3a50e702011-10-18 21:21:00 +02007471 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007472 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007473 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007474 if (*outbytes == NULL) {
7475 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007476 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007477 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007478 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007479 }
7480 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007481 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007482 const Py_ssize_t n = PyBytes_Size(*outbytes);
7483 if (outsize > PY_SSIZE_T_MAX - n) {
7484 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007485 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007486 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007487 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007488 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7489 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007490 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007491 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007492 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007493 }
7494
7495 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007496 outsize = WideCharToMultiByte(code_page, flags,
7497 p, size,
7498 out, outsize,
7499 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007500 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007501 if (outsize <= 0)
7502 goto error;
7503 if (pusedDefaultChar && *pusedDefaultChar)
7504 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007505 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007506
Victor Stinner3a50e702011-10-18 21:21:00 +02007507error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007508 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007509 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7510 return -2;
7511 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007512 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007513}
7514
Victor Stinner3a50e702011-10-18 21:21:00 +02007515/*
7516 * Encode a Unicode string to a Windows code page into a byte string using a
7517 * error handler.
7518 *
7519 * Returns consumed characters if succeed, or raise a WindowsError and returns
7520 * -1 on other error.
7521 */
7522static int
7523encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007524 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007525 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007526{
Victor Stinner3a50e702011-10-18 21:21:00 +02007527 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007528 Py_ssize_t pos = unicode_offset;
7529 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007530 /* Ideally, we should get reason from FormatMessage. This is the Windows
7531 2000 English version of the message. */
7532 const char *reason = "invalid character";
7533 /* 4=maximum length of a UTF-8 sequence */
7534 char buffer[4];
7535 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7536 Py_ssize_t outsize;
7537 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007538 PyObject *errorHandler = NULL;
7539 PyObject *exc = NULL;
7540 PyObject *encoding_obj = NULL;
7541 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007542 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007543 PyObject *rep;
7544 int ret = -1;
7545
7546 assert(insize > 0);
7547
7548 encoding = code_page_name(code_page, &encoding_obj);
7549 if (encoding == NULL)
7550 return -1;
7551
7552 if (errors == NULL || strcmp(errors, "strict") == 0) {
7553 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7554 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007555 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007556 if (exc != NULL) {
7557 PyCodec_StrictErrors(exc);
7558 Py_DECREF(exc);
7559 }
7560 Py_XDECREF(encoding_obj);
7561 return -1;
7562 }
7563
7564 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7565 pusedDefaultChar = &usedDefaultChar;
7566 else
7567 pusedDefaultChar = NULL;
7568
7569 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7570 PyErr_NoMemory();
7571 goto error;
7572 }
7573 outsize = insize * Py_ARRAY_LENGTH(buffer);
7574
7575 if (*outbytes == NULL) {
7576 /* Create string object */
7577 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7578 if (*outbytes == NULL)
7579 goto error;
7580 out = PyBytes_AS_STRING(*outbytes);
7581 }
7582 else {
7583 /* Extend string object */
7584 Py_ssize_t n = PyBytes_Size(*outbytes);
7585 if (n > PY_SSIZE_T_MAX - outsize) {
7586 PyErr_NoMemory();
7587 goto error;
7588 }
7589 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7590 goto error;
7591 out = PyBytes_AS_STRING(*outbytes) + n;
7592 }
7593
7594 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007595 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007596 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007597 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7598 wchar_t chars[2];
7599 int charsize;
7600 if (ch < 0x10000) {
7601 chars[0] = (wchar_t)ch;
7602 charsize = 1;
7603 }
7604 else {
7605 ch -= 0x10000;
7606 chars[0] = 0xd800 + (ch >> 10);
7607 chars[1] = 0xdc00 + (ch & 0x3ff);
7608 charsize = 2;
7609 }
7610
Victor Stinner3a50e702011-10-18 21:21:00 +02007611 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007612 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007613 buffer, Py_ARRAY_LENGTH(buffer),
7614 NULL, pusedDefaultChar);
7615 if (outsize > 0) {
7616 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7617 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007618 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007619 memcpy(out, buffer, outsize);
7620 out += outsize;
7621 continue;
7622 }
7623 }
7624 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7625 PyErr_SetFromWindowsErr(0);
7626 goto error;
7627 }
7628
Victor Stinner3a50e702011-10-18 21:21:00 +02007629 rep = unicode_encode_call_errorhandler(
7630 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007631 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007632 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007633 if (rep == NULL)
7634 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007635 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007636
7637 if (PyBytes_Check(rep)) {
7638 outsize = PyBytes_GET_SIZE(rep);
7639 if (outsize != 1) {
7640 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7641 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7642 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7643 Py_DECREF(rep);
7644 goto error;
7645 }
7646 out = PyBytes_AS_STRING(*outbytes) + offset;
7647 }
7648 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7649 out += outsize;
7650 }
7651 else {
7652 Py_ssize_t i;
7653 enum PyUnicode_Kind kind;
7654 void *data;
7655
Benjamin Petersonbac79492012-01-14 13:34:47 -05007656 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007657 Py_DECREF(rep);
7658 goto error;
7659 }
7660
7661 outsize = PyUnicode_GET_LENGTH(rep);
7662 if (outsize != 1) {
7663 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7664 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7665 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7666 Py_DECREF(rep);
7667 goto error;
7668 }
7669 out = PyBytes_AS_STRING(*outbytes) + offset;
7670 }
7671 kind = PyUnicode_KIND(rep);
7672 data = PyUnicode_DATA(rep);
7673 for (i=0; i < outsize; i++) {
7674 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7675 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007676 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007677 encoding, unicode,
7678 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007679 "unable to encode error handler result to ASCII");
7680 Py_DECREF(rep);
7681 goto error;
7682 }
7683 *out = (unsigned char)ch;
7684 out++;
7685 }
7686 }
7687 Py_DECREF(rep);
7688 }
7689 /* write a NUL byte */
7690 *out = 0;
7691 outsize = out - PyBytes_AS_STRING(*outbytes);
7692 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7693 if (_PyBytes_Resize(outbytes, outsize) < 0)
7694 goto error;
7695 ret = 0;
7696
7697error:
7698 Py_XDECREF(encoding_obj);
7699 Py_XDECREF(errorHandler);
7700 Py_XDECREF(exc);
7701 return ret;
7702}
7703
Victor Stinner3a50e702011-10-18 21:21:00 +02007704static PyObject *
7705encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007706 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007707 const char *errors)
7708{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007709 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007710 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007711 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007712 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007713
Benjamin Petersonbac79492012-01-14 13:34:47 -05007714 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007715 return NULL;
7716 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007717
Victor Stinner3a50e702011-10-18 21:21:00 +02007718 if (code_page < 0) {
7719 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7720 return NULL;
7721 }
7722
Martin v. Löwis3d325192011-11-04 18:23:06 +01007723 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007724 return PyBytes_FromStringAndSize(NULL, 0);
7725
Victor Stinner7581cef2011-11-03 22:32:33 +01007726 offset = 0;
7727 do
7728 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007729#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007730 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007731 chunks. */
7732 if (len > INT_MAX/2) {
7733 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007734 done = 0;
7735 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007736 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007737#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007738 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007739 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007740 done = 1;
7741 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007742
Victor Stinner76a31a62011-11-04 00:05:13 +01007743 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007744 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007745 errors);
7746 if (ret == -2)
7747 ret = encode_code_page_errors(code_page, &outbytes,
7748 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007749 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007750 if (ret < 0) {
7751 Py_XDECREF(outbytes);
7752 return NULL;
7753 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007754
Victor Stinner7581cef2011-11-03 22:32:33 +01007755 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007756 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007757 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007758
Victor Stinner3a50e702011-10-18 21:21:00 +02007759 return outbytes;
7760}
7761
7762PyObject *
7763PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7764 Py_ssize_t size,
7765 const char *errors)
7766{
Victor Stinner7581cef2011-11-03 22:32:33 +01007767 PyObject *unicode, *res;
7768 unicode = PyUnicode_FromUnicode(p, size);
7769 if (unicode == NULL)
7770 return NULL;
7771 res = encode_code_page(CP_ACP, unicode, errors);
7772 Py_DECREF(unicode);
7773 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007774}
7775
7776PyObject *
7777PyUnicode_EncodeCodePage(int code_page,
7778 PyObject *unicode,
7779 const char *errors)
7780{
Victor Stinner7581cef2011-11-03 22:32:33 +01007781 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007782}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007783
Alexander Belopolsky40018472011-02-26 01:02:56 +00007784PyObject *
7785PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007786{
7787 if (!PyUnicode_Check(unicode)) {
7788 PyErr_BadArgument();
7789 return NULL;
7790 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007791 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007792}
7793
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007794#undef NEED_RETRY
7795
Victor Stinner99b95382011-07-04 14:23:54 +02007796#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007797
Guido van Rossumd57fd912000-03-10 22:53:23 +00007798/* --- Character Mapping Codec -------------------------------------------- */
7799
Alexander Belopolsky40018472011-02-26 01:02:56 +00007800PyObject *
7801PyUnicode_DecodeCharmap(const char *s,
7802 Py_ssize_t size,
7803 PyObject *mapping,
7804 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007805{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007806 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007807 Py_ssize_t startinpos;
7808 Py_ssize_t endinpos;
7809 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007810 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007811 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007812 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007813 PyObject *errorHandler = NULL;
7814 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007815
Guido van Rossumd57fd912000-03-10 22:53:23 +00007816 /* Default to Latin-1 */
7817 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007818 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007819
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007820 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007821 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007822 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007823 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007824 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007825 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007826 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007827 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007828 Py_ssize_t maplen;
7829 enum PyUnicode_Kind kind;
7830 void *data;
7831 Py_UCS4 x;
7832
Benjamin Petersonbac79492012-01-14 13:34:47 -05007833 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007834 return NULL;
7835
7836 maplen = PyUnicode_GET_LENGTH(mapping);
7837 data = PyUnicode_DATA(mapping);
7838 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007839 while (s < e) {
7840 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007841
Benjamin Peterson29060642009-01-31 22:14:21 +00007842 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007843 x = PyUnicode_READ(kind, data, ch);
7844 else
7845 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007846
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007847 if (x == 0xfffe)
7848 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007849 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007850 startinpos = s-starts;
7851 endinpos = startinpos+1;
7852 if (unicode_decode_call_errorhandler(
7853 errors, &errorHandler,
7854 "charmap", "character maps to <undefined>",
7855 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007856 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007857 goto onError;
7858 }
7859 continue;
7860 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007861
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007862 if (unicode_putchar(&v, &outpos, x) < 0)
7863 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007864 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007865 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007866 }
7867 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007868 while (s < e) {
7869 unsigned char ch = *s;
7870 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007871
Benjamin Peterson29060642009-01-31 22:14:21 +00007872 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7873 w = PyLong_FromLong((long)ch);
7874 if (w == NULL)
7875 goto onError;
7876 x = PyObject_GetItem(mapping, w);
7877 Py_DECREF(w);
7878 if (x == NULL) {
7879 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7880 /* No mapping found means: mapping is undefined. */
7881 PyErr_Clear();
7882 x = Py_None;
7883 Py_INCREF(x);
7884 } else
7885 goto onError;
7886 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007887
Benjamin Peterson29060642009-01-31 22:14:21 +00007888 /* Apply mapping */
7889 if (PyLong_Check(x)) {
7890 long value = PyLong_AS_LONG(x);
7891 if (value < 0 || value > 65535) {
7892 PyErr_SetString(PyExc_TypeError,
7893 "character mapping must be in range(65536)");
7894 Py_DECREF(x);
7895 goto onError;
7896 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007897 if (unicode_putchar(&v, &outpos, value) < 0)
7898 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007899 }
7900 else if (x == Py_None) {
7901 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007902 startinpos = s-starts;
7903 endinpos = startinpos+1;
7904 if (unicode_decode_call_errorhandler(
7905 errors, &errorHandler,
7906 "charmap", "character maps to <undefined>",
7907 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007908 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007909 Py_DECREF(x);
7910 goto onError;
7911 }
7912 Py_DECREF(x);
7913 continue;
7914 }
7915 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007916 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007917
Benjamin Petersonbac79492012-01-14 13:34:47 -05007918 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007919 goto onError;
7920 targetsize = PyUnicode_GET_LENGTH(x);
7921
7922 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007923 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007924 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007925 PyUnicode_READ_CHAR(x, 0)) < 0)
7926 goto onError;
7927 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007928 else if (targetsize > 1) {
7929 /* 1-n mapping */
7930 if (targetsize > extrachars) {
7931 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007932 Py_ssize_t needed = (targetsize - extrachars) + \
7933 (targetsize << 2);
7934 extrachars += needed;
7935 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007936 if (unicode_resize(&v,
7937 PyUnicode_GET_LENGTH(v) + needed) < 0)
7938 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007939 Py_DECREF(x);
7940 goto onError;
7941 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007942 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007943 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7944 goto onError;
7945 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7946 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007947 extrachars -= targetsize;
7948 }
7949 /* 1-0 mapping: skip the character */
7950 }
7951 else {
7952 /* wrong return value */
7953 PyErr_SetString(PyExc_TypeError,
7954 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007955 Py_DECREF(x);
7956 goto onError;
7957 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007958 Py_DECREF(x);
7959 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007960 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007961 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007962 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007963 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007964 Py_XDECREF(errorHandler);
7965 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007966 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007967
Benjamin Peterson29060642009-01-31 22:14:21 +00007968 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007969 Py_XDECREF(errorHandler);
7970 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007971 Py_XDECREF(v);
7972 return NULL;
7973}
7974
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007975/* Charmap encoding: the lookup table */
7976
Alexander Belopolsky40018472011-02-26 01:02:56 +00007977struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007978 PyObject_HEAD
7979 unsigned char level1[32];
7980 int count2, count3;
7981 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007982};
7983
7984static PyObject*
7985encoding_map_size(PyObject *obj, PyObject* args)
7986{
7987 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007988 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007989 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007990}
7991
7992static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007993 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007994 PyDoc_STR("Return the size (in bytes) of this object") },
7995 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007996};
7997
7998static void
7999encoding_map_dealloc(PyObject* o)
8000{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008001 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008002}
8003
8004static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008005 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008006 "EncodingMap", /*tp_name*/
8007 sizeof(struct encoding_map), /*tp_basicsize*/
8008 0, /*tp_itemsize*/
8009 /* methods */
8010 encoding_map_dealloc, /*tp_dealloc*/
8011 0, /*tp_print*/
8012 0, /*tp_getattr*/
8013 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008014 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008015 0, /*tp_repr*/
8016 0, /*tp_as_number*/
8017 0, /*tp_as_sequence*/
8018 0, /*tp_as_mapping*/
8019 0, /*tp_hash*/
8020 0, /*tp_call*/
8021 0, /*tp_str*/
8022 0, /*tp_getattro*/
8023 0, /*tp_setattro*/
8024 0, /*tp_as_buffer*/
8025 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8026 0, /*tp_doc*/
8027 0, /*tp_traverse*/
8028 0, /*tp_clear*/
8029 0, /*tp_richcompare*/
8030 0, /*tp_weaklistoffset*/
8031 0, /*tp_iter*/
8032 0, /*tp_iternext*/
8033 encoding_map_methods, /*tp_methods*/
8034 0, /*tp_members*/
8035 0, /*tp_getset*/
8036 0, /*tp_base*/
8037 0, /*tp_dict*/
8038 0, /*tp_descr_get*/
8039 0, /*tp_descr_set*/
8040 0, /*tp_dictoffset*/
8041 0, /*tp_init*/
8042 0, /*tp_alloc*/
8043 0, /*tp_new*/
8044 0, /*tp_free*/
8045 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008046};
8047
8048PyObject*
8049PyUnicode_BuildEncodingMap(PyObject* string)
8050{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008051 PyObject *result;
8052 struct encoding_map *mresult;
8053 int i;
8054 int need_dict = 0;
8055 unsigned char level1[32];
8056 unsigned char level2[512];
8057 unsigned char *mlevel1, *mlevel2, *mlevel3;
8058 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008059 int kind;
8060 void *data;
8061 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008062
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008063 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008064 PyErr_BadArgument();
8065 return NULL;
8066 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008067 kind = PyUnicode_KIND(string);
8068 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008069 memset(level1, 0xFF, sizeof level1);
8070 memset(level2, 0xFF, sizeof level2);
8071
8072 /* If there isn't a one-to-one mapping of NULL to \0,
8073 or if there are non-BMP characters, we need to use
8074 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008075 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008076 need_dict = 1;
8077 for (i = 1; i < 256; i++) {
8078 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008079 ch = PyUnicode_READ(kind, data, i);
8080 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008081 need_dict = 1;
8082 break;
8083 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008084 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008085 /* unmapped character */
8086 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008087 l1 = ch >> 11;
8088 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008089 if (level1[l1] == 0xFF)
8090 level1[l1] = count2++;
8091 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008092 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008093 }
8094
8095 if (count2 >= 0xFF || count3 >= 0xFF)
8096 need_dict = 1;
8097
8098 if (need_dict) {
8099 PyObject *result = PyDict_New();
8100 PyObject *key, *value;
8101 if (!result)
8102 return NULL;
8103 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008104 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008105 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008106 if (!key || !value)
8107 goto failed1;
8108 if (PyDict_SetItem(result, key, value) == -1)
8109 goto failed1;
8110 Py_DECREF(key);
8111 Py_DECREF(value);
8112 }
8113 return result;
8114 failed1:
8115 Py_XDECREF(key);
8116 Py_XDECREF(value);
8117 Py_DECREF(result);
8118 return NULL;
8119 }
8120
8121 /* Create a three-level trie */
8122 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8123 16*count2 + 128*count3 - 1);
8124 if (!result)
8125 return PyErr_NoMemory();
8126 PyObject_Init(result, &EncodingMapType);
8127 mresult = (struct encoding_map*)result;
8128 mresult->count2 = count2;
8129 mresult->count3 = count3;
8130 mlevel1 = mresult->level1;
8131 mlevel2 = mresult->level23;
8132 mlevel3 = mresult->level23 + 16*count2;
8133 memcpy(mlevel1, level1, 32);
8134 memset(mlevel2, 0xFF, 16*count2);
8135 memset(mlevel3, 0, 128*count3);
8136 count3 = 0;
8137 for (i = 1; i < 256; i++) {
8138 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008139 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008140 /* unmapped character */
8141 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008142 o1 = PyUnicode_READ(kind, data, i)>>11;
8143 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008144 i2 = 16*mlevel1[o1] + o2;
8145 if (mlevel2[i2] == 0xFF)
8146 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008147 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008148 i3 = 128*mlevel2[i2] + o3;
8149 mlevel3[i3] = i;
8150 }
8151 return result;
8152}
8153
8154static int
Victor Stinner22168992011-11-20 17:09:18 +01008155encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008156{
8157 struct encoding_map *map = (struct encoding_map*)mapping;
8158 int l1 = c>>11;
8159 int l2 = (c>>7) & 0xF;
8160 int l3 = c & 0x7F;
8161 int i;
8162
Victor Stinner22168992011-11-20 17:09:18 +01008163 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008164 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008165 if (c == 0)
8166 return 0;
8167 /* level 1*/
8168 i = map->level1[l1];
8169 if (i == 0xFF) {
8170 return -1;
8171 }
8172 /* level 2*/
8173 i = map->level23[16*i+l2];
8174 if (i == 0xFF) {
8175 return -1;
8176 }
8177 /* level 3 */
8178 i = map->level23[16*map->count2 + 128*i + l3];
8179 if (i == 0) {
8180 return -1;
8181 }
8182 return i;
8183}
8184
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008185/* Lookup the character ch in the mapping. If the character
8186 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008187 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008188static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008189charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008190{
Christian Heimes217cfd12007-12-02 14:31:20 +00008191 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008192 PyObject *x;
8193
8194 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008195 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008196 x = PyObject_GetItem(mapping, w);
8197 Py_DECREF(w);
8198 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008199 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8200 /* No mapping found means: mapping is undefined. */
8201 PyErr_Clear();
8202 x = Py_None;
8203 Py_INCREF(x);
8204 return x;
8205 } else
8206 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008207 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008208 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008209 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008210 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008211 long value = PyLong_AS_LONG(x);
8212 if (value < 0 || value > 255) {
8213 PyErr_SetString(PyExc_TypeError,
8214 "character mapping must be in range(256)");
8215 Py_DECREF(x);
8216 return NULL;
8217 }
8218 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008219 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008220 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008221 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008222 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008223 /* wrong return value */
8224 PyErr_Format(PyExc_TypeError,
8225 "character mapping must return integer, bytes or None, not %.400s",
8226 x->ob_type->tp_name);
8227 Py_DECREF(x);
8228 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008229 }
8230}
8231
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008232static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008233charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008234{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008235 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8236 /* exponentially overallocate to minimize reallocations */
8237 if (requiredsize < 2*outsize)
8238 requiredsize = 2*outsize;
8239 if (_PyBytes_Resize(outobj, requiredsize))
8240 return -1;
8241 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008242}
8243
Benjamin Peterson14339b62009-01-31 16:36:08 +00008244typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008245 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008246} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008247/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008248 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008249 space is available. Return a new reference to the object that
8250 was put in the output buffer, or Py_None, if the mapping was undefined
8251 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008252 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008253static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008254charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008255 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008256{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008257 PyObject *rep;
8258 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008259 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008260
Christian Heimes90aa7642007-12-19 02:45:37 +00008261 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008262 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008263 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008264 if (res == -1)
8265 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008266 if (outsize<requiredsize)
8267 if (charmapencode_resize(outobj, outpos, requiredsize))
8268 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008269 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008270 outstart[(*outpos)++] = (char)res;
8271 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008272 }
8273
8274 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008275 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008277 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008278 Py_DECREF(rep);
8279 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008280 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008281 if (PyLong_Check(rep)) {
8282 Py_ssize_t requiredsize = *outpos+1;
8283 if (outsize<requiredsize)
8284 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8285 Py_DECREF(rep);
8286 return enc_EXCEPTION;
8287 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008288 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008289 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008290 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008291 else {
8292 const char *repchars = PyBytes_AS_STRING(rep);
8293 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8294 Py_ssize_t requiredsize = *outpos+repsize;
8295 if (outsize<requiredsize)
8296 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8297 Py_DECREF(rep);
8298 return enc_EXCEPTION;
8299 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008300 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008301 memcpy(outstart + *outpos, repchars, repsize);
8302 *outpos += repsize;
8303 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008304 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008305 Py_DECREF(rep);
8306 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008307}
8308
8309/* handle an error in PyUnicode_EncodeCharmap
8310 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008311static int
8312charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008313 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008314 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008315 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008316 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008317{
8318 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008319 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008320 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008321 enum PyUnicode_Kind kind;
8322 void *data;
8323 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008324 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008325 Py_ssize_t collstartpos = *inpos;
8326 Py_ssize_t collendpos = *inpos+1;
8327 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008328 char *encoding = "charmap";
8329 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008330 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008331 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008332 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008333
Benjamin Petersonbac79492012-01-14 13:34:47 -05008334 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008335 return -1;
8336 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008337 /* find all unencodable characters */
8338 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008339 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008340 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008341 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008342 val = encoding_map_lookup(ch, mapping);
8343 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008344 break;
8345 ++collendpos;
8346 continue;
8347 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008348
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008349 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8350 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008351 if (rep==NULL)
8352 return -1;
8353 else if (rep!=Py_None) {
8354 Py_DECREF(rep);
8355 break;
8356 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008357 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008358 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008359 }
8360 /* cache callback name lookup
8361 * (if not done yet, i.e. it's the first error) */
8362 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008363 if ((errors==NULL) || (!strcmp(errors, "strict")))
8364 *known_errorHandler = 1;
8365 else if (!strcmp(errors, "replace"))
8366 *known_errorHandler = 2;
8367 else if (!strcmp(errors, "ignore"))
8368 *known_errorHandler = 3;
8369 else if (!strcmp(errors, "xmlcharrefreplace"))
8370 *known_errorHandler = 4;
8371 else
8372 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008373 }
8374 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008375 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008376 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008377 return -1;
8378 case 2: /* replace */
8379 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008380 x = charmapencode_output('?', mapping, res, respos);
8381 if (x==enc_EXCEPTION) {
8382 return -1;
8383 }
8384 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008385 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008386 return -1;
8387 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008388 }
8389 /* fall through */
8390 case 3: /* ignore */
8391 *inpos = collendpos;
8392 break;
8393 case 4: /* xmlcharrefreplace */
8394 /* generate replacement (temporarily (mis)uses p) */
8395 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008396 char buffer[2+29+1+1];
8397 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008398 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008399 for (cp = buffer; *cp; ++cp) {
8400 x = charmapencode_output(*cp, mapping, res, respos);
8401 if (x==enc_EXCEPTION)
8402 return -1;
8403 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008404 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008405 return -1;
8406 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008407 }
8408 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008409 *inpos = collendpos;
8410 break;
8411 default:
8412 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008413 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008414 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008415 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008417 if (PyBytes_Check(repunicode)) {
8418 /* Directly copy bytes result to output. */
8419 Py_ssize_t outsize = PyBytes_Size(*res);
8420 Py_ssize_t requiredsize;
8421 repsize = PyBytes_Size(repunicode);
8422 requiredsize = *respos + repsize;
8423 if (requiredsize > outsize)
8424 /* Make room for all additional bytes. */
8425 if (charmapencode_resize(res, respos, requiredsize)) {
8426 Py_DECREF(repunicode);
8427 return -1;
8428 }
8429 memcpy(PyBytes_AsString(*res) + *respos,
8430 PyBytes_AsString(repunicode), repsize);
8431 *respos += repsize;
8432 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008433 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008434 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008435 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008436 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008437 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008438 Py_DECREF(repunicode);
8439 return -1;
8440 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008441 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008442 data = PyUnicode_DATA(repunicode);
8443 kind = PyUnicode_KIND(repunicode);
8444 for (index = 0; index < repsize; index++) {
8445 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8446 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008447 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008448 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008449 return -1;
8450 }
8451 else if (x==enc_FAILED) {
8452 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008453 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008454 return -1;
8455 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008456 }
8457 *inpos = newpos;
8458 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008459 }
8460 return 0;
8461}
8462
Alexander Belopolsky40018472011-02-26 01:02:56 +00008463PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008464_PyUnicode_EncodeCharmap(PyObject *unicode,
8465 PyObject *mapping,
8466 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008467{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008468 /* output object */
8469 PyObject *res = NULL;
8470 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008471 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008472 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008473 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008474 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008475 PyObject *errorHandler = NULL;
8476 PyObject *exc = NULL;
8477 /* the following variable is used for caching string comparisons
8478 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8479 * 3=ignore, 4=xmlcharrefreplace */
8480 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008481
Benjamin Petersonbac79492012-01-14 13:34:47 -05008482 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008483 return NULL;
8484 size = PyUnicode_GET_LENGTH(unicode);
8485
Guido van Rossumd57fd912000-03-10 22:53:23 +00008486 /* Default to Latin-1 */
8487 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008488 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008489
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008490 /* allocate enough for a simple encoding without
8491 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008492 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008493 if (res == NULL)
8494 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008495 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008496 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008497
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008498 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008499 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008500 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008501 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 if (x==enc_EXCEPTION) /* error */
8503 goto onError;
8504 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008505 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008506 &exc,
8507 &known_errorHandler, &errorHandler, errors,
8508 &res, &respos)) {
8509 goto onError;
8510 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008511 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008512 else
8513 /* done with this character => adjust input position */
8514 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008515 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008516
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008517 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008518 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008519 if (_PyBytes_Resize(&res, respos) < 0)
8520 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008521
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008522 Py_XDECREF(exc);
8523 Py_XDECREF(errorHandler);
8524 return res;
8525
Benjamin Peterson29060642009-01-31 22:14:21 +00008526 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008527 Py_XDECREF(res);
8528 Py_XDECREF(exc);
8529 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008530 return NULL;
8531}
8532
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008533/* Deprecated */
8534PyObject *
8535PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8536 Py_ssize_t size,
8537 PyObject *mapping,
8538 const char *errors)
8539{
8540 PyObject *result;
8541 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8542 if (unicode == NULL)
8543 return NULL;
8544 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8545 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008546 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008547}
8548
Alexander Belopolsky40018472011-02-26 01:02:56 +00008549PyObject *
8550PyUnicode_AsCharmapString(PyObject *unicode,
8551 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008552{
8553 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008554 PyErr_BadArgument();
8555 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008556 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008557 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008558}
8559
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008560/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008561static void
8562make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008563 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008564 Py_ssize_t startpos, Py_ssize_t endpos,
8565 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008566{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008567 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008568 *exceptionObject = _PyUnicodeTranslateError_Create(
8569 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008570 }
8571 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008572 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8573 goto onError;
8574 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8575 goto onError;
8576 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8577 goto onError;
8578 return;
8579 onError:
8580 Py_DECREF(*exceptionObject);
8581 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008582 }
8583}
8584
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008585/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008586static void
8587raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008588 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008589 Py_ssize_t startpos, Py_ssize_t endpos,
8590 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008591{
8592 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008593 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008594 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008595 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008596}
8597
8598/* error handling callback helper:
8599 build arguments, call the callback and check the arguments,
8600 put the result into newpos and return the replacement string, which
8601 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008602static PyObject *
8603unicode_translate_call_errorhandler(const char *errors,
8604 PyObject **errorHandler,
8605 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008606 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008607 Py_ssize_t startpos, Py_ssize_t endpos,
8608 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008609{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008610 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008611
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008612 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008613 PyObject *restuple;
8614 PyObject *resunicode;
8615
8616 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008617 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008618 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008619 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008620 }
8621
8622 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008623 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008624 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008625 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008626
8627 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008628 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008629 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008630 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008631 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008632 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008633 Py_DECREF(restuple);
8634 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008635 }
8636 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008637 &resunicode, &i_newpos)) {
8638 Py_DECREF(restuple);
8639 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008640 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008641 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008642 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008643 else
8644 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008645 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008646 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8647 Py_DECREF(restuple);
8648 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008649 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008650 Py_INCREF(resunicode);
8651 Py_DECREF(restuple);
8652 return resunicode;
8653}
8654
8655/* Lookup the character ch in the mapping and put the result in result,
8656 which must be decrefed by the caller.
8657 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008658static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008659charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008660{
Christian Heimes217cfd12007-12-02 14:31:20 +00008661 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008662 PyObject *x;
8663
8664 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008665 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008666 x = PyObject_GetItem(mapping, w);
8667 Py_DECREF(w);
8668 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008669 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8670 /* No mapping found means: use 1:1 mapping. */
8671 PyErr_Clear();
8672 *result = NULL;
8673 return 0;
8674 } else
8675 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008676 }
8677 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008678 *result = x;
8679 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008680 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008681 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008682 long value = PyLong_AS_LONG(x);
8683 long max = PyUnicode_GetMax();
8684 if (value < 0 || value > max) {
8685 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008686 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008687 Py_DECREF(x);
8688 return -1;
8689 }
8690 *result = x;
8691 return 0;
8692 }
8693 else if (PyUnicode_Check(x)) {
8694 *result = x;
8695 return 0;
8696 }
8697 else {
8698 /* wrong return value */
8699 PyErr_SetString(PyExc_TypeError,
8700 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008701 Py_DECREF(x);
8702 return -1;
8703 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008704}
8705/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008706 if not reallocate and adjust various state variables.
8707 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008708static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008709charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008710 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008711{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008712 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008713 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008714 /* exponentially overallocate to minimize reallocations */
8715 if (requiredsize < 2 * oldsize)
8716 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008717 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8718 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008719 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008720 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008721 }
8722 return 0;
8723}
8724/* lookup the character, put the result in the output string and adjust
8725 various state variables. Return a new reference to the object that
8726 was put in the output buffer in *result, or Py_None, if the mapping was
8727 undefined (in which case no character was written).
8728 The called must decref result.
8729 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008730static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008731charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8732 PyObject *mapping, Py_UCS4 **output,
8733 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008734 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008735{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008736 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8737 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008738 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008739 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008740 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008741 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008742 }
8743 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008744 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008745 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008746 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008747 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008748 }
8749 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008750 Py_ssize_t repsize;
8751 if (PyUnicode_READY(*res) == -1)
8752 return -1;
8753 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008754 if (repsize==1) {
8755 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008756 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008757 }
8758 else if (repsize!=0) {
8759 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008760 Py_ssize_t requiredsize = *opos +
8761 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008762 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008763 Py_ssize_t i;
8764 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008765 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008766 for(i = 0; i < repsize; i++)
8767 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008768 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008769 }
8770 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008771 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008772 return 0;
8773}
8774
Alexander Belopolsky40018472011-02-26 01:02:56 +00008775PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008776_PyUnicode_TranslateCharmap(PyObject *input,
8777 PyObject *mapping,
8778 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008779{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008780 /* input object */
8781 char *idata;
8782 Py_ssize_t size, i;
8783 int kind;
8784 /* output buffer */
8785 Py_UCS4 *output = NULL;
8786 Py_ssize_t osize;
8787 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008788 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008789 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008790 char *reason = "character maps to <undefined>";
8791 PyObject *errorHandler = NULL;
8792 PyObject *exc = NULL;
8793 /* the following variable is used for caching string comparisons
8794 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8795 * 3=ignore, 4=xmlcharrefreplace */
8796 int known_errorHandler = -1;
8797
Guido van Rossumd57fd912000-03-10 22:53:23 +00008798 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008799 PyErr_BadArgument();
8800 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008801 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008802
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008803 if (PyUnicode_READY(input) == -1)
8804 return NULL;
8805 idata = (char*)PyUnicode_DATA(input);
8806 kind = PyUnicode_KIND(input);
8807 size = PyUnicode_GET_LENGTH(input);
8808 i = 0;
8809
8810 if (size == 0) {
8811 Py_INCREF(input);
8812 return input;
8813 }
8814
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008815 /* allocate enough for a simple 1:1 translation without
8816 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008817 osize = size;
8818 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8819 opos = 0;
8820 if (output == NULL) {
8821 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008822 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008823 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008824
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008825 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008826 /* try to encode it */
8827 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008828 if (charmaptranslate_output(input, i, mapping,
8829 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008830 Py_XDECREF(x);
8831 goto onError;
8832 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008833 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008834 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008835 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008836 else { /* untranslatable character */
8837 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8838 Py_ssize_t repsize;
8839 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008840 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008841 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008842 Py_ssize_t collstart = i;
8843 Py_ssize_t collend = i+1;
8844 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008845
Benjamin Peterson29060642009-01-31 22:14:21 +00008846 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008847 while (collend < size) {
8848 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008849 goto onError;
8850 Py_XDECREF(x);
8851 if (x!=Py_None)
8852 break;
8853 ++collend;
8854 }
8855 /* cache callback name lookup
8856 * (if not done yet, i.e. it's the first error) */
8857 if (known_errorHandler==-1) {
8858 if ((errors==NULL) || (!strcmp(errors, "strict")))
8859 known_errorHandler = 1;
8860 else if (!strcmp(errors, "replace"))
8861 known_errorHandler = 2;
8862 else if (!strcmp(errors, "ignore"))
8863 known_errorHandler = 3;
8864 else if (!strcmp(errors, "xmlcharrefreplace"))
8865 known_errorHandler = 4;
8866 else
8867 known_errorHandler = 0;
8868 }
8869 switch (known_errorHandler) {
8870 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008871 raise_translate_exception(&exc, input, collstart,
8872 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008873 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008874 case 2: /* replace */
8875 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008876 for (coll = collstart; coll<collend; coll++)
8877 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008878 /* fall through */
8879 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008880 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008881 break;
8882 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008883 /* generate replacement (temporarily (mis)uses i) */
8884 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008885 char buffer[2+29+1+1];
8886 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008887 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8888 if (charmaptranslate_makespace(&output, &osize,
8889 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008890 goto onError;
8891 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008892 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008893 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008894 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008895 break;
8896 default:
8897 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008898 reason, input, &exc,
8899 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008900 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008901 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008902 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008903 Py_DECREF(repunicode);
8904 goto onError;
8905 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008906 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008907 repsize = PyUnicode_GET_LENGTH(repunicode);
8908 if (charmaptranslate_makespace(&output, &osize,
8909 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008910 Py_DECREF(repunicode);
8911 goto onError;
8912 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008913 for (uni2 = 0; repsize-->0; ++uni2)
8914 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8915 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008916 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008917 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008918 }
8919 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008920 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8921 if (!res)
8922 goto onError;
8923 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008924 Py_XDECREF(exc);
8925 Py_XDECREF(errorHandler);
8926 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008927
Benjamin Peterson29060642009-01-31 22:14:21 +00008928 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008929 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008930 Py_XDECREF(exc);
8931 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008932 return NULL;
8933}
8934
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008935/* Deprecated. Use PyUnicode_Translate instead. */
8936PyObject *
8937PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8938 Py_ssize_t size,
8939 PyObject *mapping,
8940 const char *errors)
8941{
8942 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8943 if (!unicode)
8944 return NULL;
8945 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8946}
8947
Alexander Belopolsky40018472011-02-26 01:02:56 +00008948PyObject *
8949PyUnicode_Translate(PyObject *str,
8950 PyObject *mapping,
8951 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008952{
8953 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008954
Guido van Rossumd57fd912000-03-10 22:53:23 +00008955 str = PyUnicode_FromObject(str);
8956 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008957 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008958 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008959 Py_DECREF(str);
8960 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008961
Benjamin Peterson29060642009-01-31 22:14:21 +00008962 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008963 Py_XDECREF(str);
8964 return NULL;
8965}
Tim Petersced69f82003-09-16 20:30:58 +00008966
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008967static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008968fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008969{
8970 /* No need to call PyUnicode_READY(self) because this function is only
8971 called as a callback from fixup() which does it already. */
8972 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8973 const int kind = PyUnicode_KIND(self);
8974 void *data = PyUnicode_DATA(self);
8975 Py_UCS4 maxchar = 0, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008976 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008977 Py_ssize_t i;
8978
8979 for (i = 0; i < len; ++i) {
8980 ch = PyUnicode_READ(kind, data, i);
8981 fixed = 0;
8982 if (ch > 127) {
8983 if (Py_UNICODE_ISSPACE(ch))
8984 fixed = ' ';
8985 else {
8986 const int decimal = Py_UNICODE_TODECIMAL(ch);
8987 if (decimal >= 0)
8988 fixed = '0' + decimal;
8989 }
8990 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008991 modified = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008992 if (fixed > maxchar)
8993 maxchar = fixed;
8994 PyUnicode_WRITE(kind, data, i, fixed);
8995 }
8996 else if (ch > maxchar)
8997 maxchar = ch;
8998 }
8999 else if (ch > maxchar)
9000 maxchar = ch;
9001 }
9002
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009003 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009004}
9005
9006PyObject *
9007_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9008{
9009 if (!PyUnicode_Check(unicode)) {
9010 PyErr_BadInternalCall();
9011 return NULL;
9012 }
9013 if (PyUnicode_READY(unicode) == -1)
9014 return NULL;
9015 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9016 /* If the string is already ASCII, just return the same string */
9017 Py_INCREF(unicode);
9018 return unicode;
9019 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009020 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009021}
9022
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009023PyObject *
9024PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9025 Py_ssize_t length)
9026{
Victor Stinnerf0124502011-11-21 23:12:56 +01009027 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009028 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009029 Py_UCS4 maxchar;
9030 enum PyUnicode_Kind kind;
9031 void *data;
9032
Victor Stinner99d7ad02012-02-22 13:37:39 +01009033 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009034 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01009035 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009036 if (ch > 127) {
9037 int decimal = Py_UNICODE_TODECIMAL(ch);
9038 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009039 ch = '0' + decimal;
Victor Stinner99d7ad02012-02-22 13:37:39 +01009040 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009041 }
9042 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009043
9044 /* Copy to a new string */
9045 decimal = PyUnicode_New(length, maxchar);
9046 if (decimal == NULL)
9047 return decimal;
9048 kind = PyUnicode_KIND(decimal);
9049 data = PyUnicode_DATA(decimal);
9050 /* Iterate over code points */
9051 for (i = 0; i < length; i++) {
9052 Py_UNICODE ch = s[i];
9053 if (ch > 127) {
9054 int decimal = Py_UNICODE_TODECIMAL(ch);
9055 if (decimal >= 0)
9056 ch = '0' + decimal;
9057 }
9058 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009059 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009060 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009061}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009062/* --- Decimal Encoder ---------------------------------------------------- */
9063
Alexander Belopolsky40018472011-02-26 01:02:56 +00009064int
9065PyUnicode_EncodeDecimal(Py_UNICODE *s,
9066 Py_ssize_t length,
9067 char *output,
9068 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009069{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009070 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009071 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009072 enum PyUnicode_Kind kind;
9073 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009074
9075 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009076 PyErr_BadArgument();
9077 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009078 }
9079
Victor Stinner42bf7752011-11-21 22:52:58 +01009080 unicode = PyUnicode_FromUnicode(s, length);
9081 if (unicode == NULL)
9082 return -1;
9083
Benjamin Petersonbac79492012-01-14 13:34:47 -05009084 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009085 Py_DECREF(unicode);
9086 return -1;
9087 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009088 kind = PyUnicode_KIND(unicode);
9089 data = PyUnicode_DATA(unicode);
9090
Victor Stinnerb84d7232011-11-22 01:50:07 +01009091 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009092 PyObject *exc;
9093 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009094 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009095 Py_ssize_t startpos;
9096
9097 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009098
Benjamin Peterson29060642009-01-31 22:14:21 +00009099 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009100 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009101 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009102 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009103 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009104 decimal = Py_UNICODE_TODECIMAL(ch);
9105 if (decimal >= 0) {
9106 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009107 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009108 continue;
9109 }
9110 if (0 < ch && ch < 256) {
9111 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009112 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009113 continue;
9114 }
Victor Stinner6345be92011-11-25 20:09:01 +01009115
Victor Stinner42bf7752011-11-21 22:52:58 +01009116 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009117 exc = NULL;
9118 raise_encode_exception(&exc, "decimal", unicode,
9119 startpos, startpos+1,
9120 "invalid decimal Unicode string");
9121 Py_XDECREF(exc);
9122 Py_DECREF(unicode);
9123 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009124 }
9125 /* 0-terminate the output string */
9126 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009127 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009128 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009129}
9130
Guido van Rossumd57fd912000-03-10 22:53:23 +00009131/* --- Helpers ------------------------------------------------------------ */
9132
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009133static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009134any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009135 Py_ssize_t start,
9136 Py_ssize_t end)
9137{
9138 int kind1, kind2, kind;
9139 void *buf1, *buf2;
9140 Py_ssize_t len1, len2, result;
9141
9142 kind1 = PyUnicode_KIND(s1);
9143 kind2 = PyUnicode_KIND(s2);
9144 kind = kind1 > kind2 ? kind1 : kind2;
9145 buf1 = PyUnicode_DATA(s1);
9146 buf2 = PyUnicode_DATA(s2);
9147 if (kind1 != kind)
9148 buf1 = _PyUnicode_AsKind(s1, kind);
9149 if (!buf1)
9150 return -2;
9151 if (kind2 != kind)
9152 buf2 = _PyUnicode_AsKind(s2, kind);
9153 if (!buf2) {
9154 if (kind1 != kind) PyMem_Free(buf1);
9155 return -2;
9156 }
9157 len1 = PyUnicode_GET_LENGTH(s1);
9158 len2 = PyUnicode_GET_LENGTH(s2);
9159
Victor Stinner794d5672011-10-10 03:21:36 +02009160 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009161 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009162 case PyUnicode_1BYTE_KIND:
9163 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9164 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9165 else
9166 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9167 break;
9168 case PyUnicode_2BYTE_KIND:
9169 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9170 break;
9171 case PyUnicode_4BYTE_KIND:
9172 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9173 break;
9174 default:
9175 assert(0); result = -2;
9176 }
9177 }
9178 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009179 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009180 case PyUnicode_1BYTE_KIND:
9181 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9182 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9183 else
9184 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9185 break;
9186 case PyUnicode_2BYTE_KIND:
9187 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9188 break;
9189 case PyUnicode_4BYTE_KIND:
9190 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9191 break;
9192 default:
9193 assert(0); result = -2;
9194 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009195 }
9196
9197 if (kind1 != kind)
9198 PyMem_Free(buf1);
9199 if (kind2 != kind)
9200 PyMem_Free(buf2);
9201
9202 return result;
9203}
9204
9205Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009206_PyUnicode_InsertThousandsGrouping(
9207 PyObject *unicode, Py_ssize_t index,
9208 Py_ssize_t n_buffer,
9209 void *digits, Py_ssize_t n_digits,
9210 Py_ssize_t min_width,
9211 const char *grouping, PyObject *thousands_sep,
9212 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009213{
Victor Stinner41a863c2012-02-24 00:37:51 +01009214 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009215 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009216 Py_ssize_t thousands_sep_len;
9217 Py_ssize_t len;
9218
9219 if (unicode != NULL) {
9220 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009221 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009222 }
9223 else {
9224 kind = PyUnicode_1BYTE_KIND;
9225 data = NULL;
9226 }
9227 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9228 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9229 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9230 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009231 if (thousands_sep_kind < kind) {
9232 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9233 if (!thousands_sep_data)
9234 return -1;
9235 }
9236 else {
9237 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9238 if (!data)
9239 return -1;
9240 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009241 }
9242
Benjamin Petersonead6b532011-12-20 17:23:42 -06009243 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009244 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009245 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009246 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009247 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009248 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009249 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009250 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009251 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009252 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009253 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009254 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009255 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009256 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009257 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009258 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009259 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009260 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009261 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009262 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009263 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009264 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009265 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009266 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009267 break;
9268 default:
9269 assert(0);
9270 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009271 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009272 if (unicode != NULL && thousands_sep_kind != kind) {
9273 if (thousands_sep_kind < kind)
9274 PyMem_Free(thousands_sep_data);
9275 else
9276 PyMem_Free(data);
9277 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009278 if (unicode == NULL) {
9279 *maxchar = 127;
9280 if (len != n_digits) {
9281 *maxchar = Py_MAX(*maxchar,
9282 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
9283 }
9284 }
9285 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009286}
9287
9288
Thomas Wouters477c8d52006-05-27 19:21:47 +00009289/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009290#define ADJUST_INDICES(start, end, len) \
9291 if (end > len) \
9292 end = len; \
9293 else if (end < 0) { \
9294 end += len; \
9295 if (end < 0) \
9296 end = 0; \
9297 } \
9298 if (start < 0) { \
9299 start += len; \
9300 if (start < 0) \
9301 start = 0; \
9302 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009303
Alexander Belopolsky40018472011-02-26 01:02:56 +00009304Py_ssize_t
9305PyUnicode_Count(PyObject *str,
9306 PyObject *substr,
9307 Py_ssize_t start,
9308 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009309{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009310 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009311 PyObject* str_obj;
9312 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009313 int kind1, kind2, kind;
9314 void *buf1 = NULL, *buf2 = NULL;
9315 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009316
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009317 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009318 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009319 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009320 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009321 if (!sub_obj) {
9322 Py_DECREF(str_obj);
9323 return -1;
9324 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009325 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009326 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009327 Py_DECREF(str_obj);
9328 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009329 }
Tim Petersced69f82003-09-16 20:30:58 +00009330
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009331 kind1 = PyUnicode_KIND(str_obj);
9332 kind2 = PyUnicode_KIND(sub_obj);
9333 kind = kind1 > kind2 ? kind1 : kind2;
9334 buf1 = PyUnicode_DATA(str_obj);
9335 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009336 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009337 if (!buf1)
9338 goto onError;
9339 buf2 = PyUnicode_DATA(sub_obj);
9340 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009341 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009342 if (!buf2)
9343 goto onError;
9344 len1 = PyUnicode_GET_LENGTH(str_obj);
9345 len2 = PyUnicode_GET_LENGTH(sub_obj);
9346
9347 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009348 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009349 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009350 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9351 result = asciilib_count(
9352 ((Py_UCS1*)buf1) + start, end - start,
9353 buf2, len2, PY_SSIZE_T_MAX
9354 );
9355 else
9356 result = ucs1lib_count(
9357 ((Py_UCS1*)buf1) + start, end - start,
9358 buf2, len2, PY_SSIZE_T_MAX
9359 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009360 break;
9361 case PyUnicode_2BYTE_KIND:
9362 result = ucs2lib_count(
9363 ((Py_UCS2*)buf1) + start, end - start,
9364 buf2, len2, PY_SSIZE_T_MAX
9365 );
9366 break;
9367 case PyUnicode_4BYTE_KIND:
9368 result = ucs4lib_count(
9369 ((Py_UCS4*)buf1) + start, end - start,
9370 buf2, len2, PY_SSIZE_T_MAX
9371 );
9372 break;
9373 default:
9374 assert(0); result = 0;
9375 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009376
9377 Py_DECREF(sub_obj);
9378 Py_DECREF(str_obj);
9379
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009380 if (kind1 != kind)
9381 PyMem_Free(buf1);
9382 if (kind2 != kind)
9383 PyMem_Free(buf2);
9384
Guido van Rossumd57fd912000-03-10 22:53:23 +00009385 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009386 onError:
9387 Py_DECREF(sub_obj);
9388 Py_DECREF(str_obj);
9389 if (kind1 != kind && buf1)
9390 PyMem_Free(buf1);
9391 if (kind2 != kind && buf2)
9392 PyMem_Free(buf2);
9393 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009394}
9395
Alexander Belopolsky40018472011-02-26 01:02:56 +00009396Py_ssize_t
9397PyUnicode_Find(PyObject *str,
9398 PyObject *sub,
9399 Py_ssize_t start,
9400 Py_ssize_t end,
9401 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009402{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009403 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009404
Guido van Rossumd57fd912000-03-10 22:53:23 +00009405 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009406 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009407 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009408 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009409 if (!sub) {
9410 Py_DECREF(str);
9411 return -2;
9412 }
9413 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9414 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009415 Py_DECREF(str);
9416 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009417 }
Tim Petersced69f82003-09-16 20:30:58 +00009418
Victor Stinner794d5672011-10-10 03:21:36 +02009419 result = any_find_slice(direction,
9420 str, sub, start, end
9421 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009422
Guido van Rossumd57fd912000-03-10 22:53:23 +00009423 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009424 Py_DECREF(sub);
9425
Guido van Rossumd57fd912000-03-10 22:53:23 +00009426 return result;
9427}
9428
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009429Py_ssize_t
9430PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9431 Py_ssize_t start, Py_ssize_t end,
9432 int direction)
9433{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009434 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009435 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009436 if (PyUnicode_READY(str) == -1)
9437 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009438 if (start < 0 || end < 0) {
9439 PyErr_SetString(PyExc_IndexError, "string index out of range");
9440 return -2;
9441 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009442 if (end > PyUnicode_GET_LENGTH(str))
9443 end = PyUnicode_GET_LENGTH(str);
9444 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009445 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9446 kind, end-start, ch, direction);
9447 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009448 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009449 else
9450 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009451}
9452
Alexander Belopolsky40018472011-02-26 01:02:56 +00009453static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009454tailmatch(PyObject *self,
9455 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009456 Py_ssize_t start,
9457 Py_ssize_t end,
9458 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009459{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009460 int kind_self;
9461 int kind_sub;
9462 void *data_self;
9463 void *data_sub;
9464 Py_ssize_t offset;
9465 Py_ssize_t i;
9466 Py_ssize_t end_sub;
9467
9468 if (PyUnicode_READY(self) == -1 ||
9469 PyUnicode_READY(substring) == -1)
9470 return 0;
9471
9472 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009473 return 1;
9474
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009475 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9476 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009477 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009478 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009479
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009480 kind_self = PyUnicode_KIND(self);
9481 data_self = PyUnicode_DATA(self);
9482 kind_sub = PyUnicode_KIND(substring);
9483 data_sub = PyUnicode_DATA(substring);
9484 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9485
9486 if (direction > 0)
9487 offset = end;
9488 else
9489 offset = start;
9490
9491 if (PyUnicode_READ(kind_self, data_self, offset) ==
9492 PyUnicode_READ(kind_sub, data_sub, 0) &&
9493 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9494 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9495 /* If both are of the same kind, memcmp is sufficient */
9496 if (kind_self == kind_sub) {
9497 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009498 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009499 data_sub,
9500 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009501 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009502 }
9503 /* otherwise we have to compare each character by first accesing it */
9504 else {
9505 /* We do not need to compare 0 and len(substring)-1 because
9506 the if statement above ensured already that they are equal
9507 when we end up here. */
9508 // TODO: honor direction and do a forward or backwards search
9509 for (i = 1; i < end_sub; ++i) {
9510 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9511 PyUnicode_READ(kind_sub, data_sub, i))
9512 return 0;
9513 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009514 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009515 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009516 }
9517
9518 return 0;
9519}
9520
Alexander Belopolsky40018472011-02-26 01:02:56 +00009521Py_ssize_t
9522PyUnicode_Tailmatch(PyObject *str,
9523 PyObject *substr,
9524 Py_ssize_t start,
9525 Py_ssize_t end,
9526 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009527{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009528 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009529
Guido van Rossumd57fd912000-03-10 22:53:23 +00009530 str = PyUnicode_FromObject(str);
9531 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009532 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009533 substr = PyUnicode_FromObject(substr);
9534 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009535 Py_DECREF(str);
9536 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009537 }
Tim Petersced69f82003-09-16 20:30:58 +00009538
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009539 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009540 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009541 Py_DECREF(str);
9542 Py_DECREF(substr);
9543 return result;
9544}
9545
Guido van Rossumd57fd912000-03-10 22:53:23 +00009546/* Apply fixfct filter to the Unicode object self and return a
9547 reference to the modified object */
9548
Alexander Belopolsky40018472011-02-26 01:02:56 +00009549static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009550fixup(PyObject *self,
9551 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009552{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009553 PyObject *u;
9554 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009555 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009556
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009557 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009558 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009559 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009560 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009561
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009562 /* fix functions return the new maximum character in a string,
9563 if the kind of the resulting unicode object does not change,
9564 everything is fine. Otherwise we need to change the string kind
9565 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009566 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009567
9568 if (maxchar_new == 0) {
9569 /* no changes */;
9570 if (PyUnicode_CheckExact(self)) {
9571 Py_DECREF(u);
9572 Py_INCREF(self);
9573 return self;
9574 }
9575 else
9576 return u;
9577 }
9578
9579 if (maxchar_new <= 127)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009580 maxchar_new = 127;
9581 else if (maxchar_new <= 255)
9582 maxchar_new = 255;
9583 else if (maxchar_new <= 65535)
9584 maxchar_new = 65535;
9585 else
Victor Stinner8faf8212011-12-08 22:14:11 +01009586 maxchar_new = MAX_UNICODE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009587
Victor Stinnereaab6042011-12-11 22:22:39 +01009588 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009589 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009590
9591 /* In case the maximum character changed, we need to
9592 convert the string to the new category. */
9593 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9594 if (v == NULL) {
9595 Py_DECREF(u);
9596 return NULL;
9597 }
9598 if (maxchar_new > maxchar_old) {
9599 /* If the maxchar increased so that the kind changed, not all
9600 characters are representable anymore and we need to fix the
9601 string again. This only happens in very few cases. */
9602 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
9603 maxchar_old = fixfct(v);
9604 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009605 }
9606 else {
Victor Stinnereaab6042011-12-11 22:22:39 +01009607 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009608 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009609 Py_DECREF(u);
9610 assert(_PyUnicode_CheckConsistency(v, 1));
9611 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009612}
9613
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009614static PyObject *
9615ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009616{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009617 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9618 char *resdata, *data = PyUnicode_DATA(self);
9619 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009620
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009621 res = PyUnicode_New(len, 127);
9622 if (res == NULL)
9623 return NULL;
9624 resdata = PyUnicode_DATA(res);
9625 if (lower)
9626 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009627 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009628 _Py_bytes_upper(resdata, data, len);
9629 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009630}
9631
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009632static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009633handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009634{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009635 Py_ssize_t j;
9636 int final_sigma;
9637 Py_UCS4 c;
9638 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009639
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009640 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9641
9642 where ! is a negation and \p{xxx} is a character with property xxx.
9643 */
9644 for (j = i - 1; j >= 0; j--) {
9645 c = PyUnicode_READ(kind, data, j);
9646 if (!_PyUnicode_IsCaseIgnorable(c))
9647 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009648 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009649 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9650 if (final_sigma) {
9651 for (j = i + 1; j < length; j++) {
9652 c = PyUnicode_READ(kind, data, j);
9653 if (!_PyUnicode_IsCaseIgnorable(c))
9654 break;
9655 }
9656 final_sigma = j == length || !_PyUnicode_IsCased(c);
9657 }
9658 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009659}
9660
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009661static int
9662lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9663 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009664{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009665 /* Obscure special case. */
9666 if (c == 0x3A3) {
9667 mapped[0] = handle_capital_sigma(kind, data, length, i);
9668 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009669 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009670 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009671}
9672
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009673static Py_ssize_t
9674do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009675{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009676 Py_ssize_t i, k = 0;
9677 int n_res, j;
9678 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009679
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009680 c = PyUnicode_READ(kind, data, 0);
9681 n_res = _PyUnicode_ToUpperFull(c, mapped);
9682 for (j = 0; j < n_res; j++) {
9683 if (mapped[j] > *maxchar)
9684 *maxchar = mapped[j];
9685 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009686 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009687 for (i = 1; i < length; i++) {
9688 c = PyUnicode_READ(kind, data, i);
9689 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9690 for (j = 0; j < n_res; j++) {
9691 if (mapped[j] > *maxchar)
9692 *maxchar = mapped[j];
9693 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009694 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009695 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009696 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009697}
9698
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009699static Py_ssize_t
9700do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9701 Py_ssize_t i, k = 0;
9702
9703 for (i = 0; i < length; i++) {
9704 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9705 int n_res, j;
9706 if (Py_UNICODE_ISUPPER(c)) {
9707 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9708 }
9709 else if (Py_UNICODE_ISLOWER(c)) {
9710 n_res = _PyUnicode_ToUpperFull(c, mapped);
9711 }
9712 else {
9713 n_res = 1;
9714 mapped[0] = c;
9715 }
9716 for (j = 0; j < n_res; j++) {
9717 if (mapped[j] > *maxchar)
9718 *maxchar = mapped[j];
9719 res[k++] = mapped[j];
9720 }
9721 }
9722 return k;
9723}
9724
9725static Py_ssize_t
9726do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9727 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009728{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009729 Py_ssize_t i, k = 0;
9730
9731 for (i = 0; i < length; i++) {
9732 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9733 int n_res, j;
9734 if (lower)
9735 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9736 else
9737 n_res = _PyUnicode_ToUpperFull(c, mapped);
9738 for (j = 0; j < n_res; j++) {
9739 if (mapped[j] > *maxchar)
9740 *maxchar = mapped[j];
9741 res[k++] = mapped[j];
9742 }
9743 }
9744 return k;
9745}
9746
9747static Py_ssize_t
9748do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9749{
9750 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9751}
9752
9753static Py_ssize_t
9754do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9755{
9756 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9757}
9758
Benjamin Petersone51757f2012-01-12 21:10:29 -05009759static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009760do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9761{
9762 Py_ssize_t i, k = 0;
9763
9764 for (i = 0; i < length; i++) {
9765 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9766 Py_UCS4 mapped[3];
9767 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9768 for (j = 0; j < n_res; j++) {
9769 if (mapped[j] > *maxchar)
9770 *maxchar = mapped[j];
9771 res[k++] = mapped[j];
9772 }
9773 }
9774 return k;
9775}
9776
9777static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009778do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9779{
9780 Py_ssize_t i, k = 0;
9781 int previous_is_cased;
9782
9783 previous_is_cased = 0;
9784 for (i = 0; i < length; i++) {
9785 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9786 Py_UCS4 mapped[3];
9787 int n_res, j;
9788
9789 if (previous_is_cased)
9790 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9791 else
9792 n_res = _PyUnicode_ToTitleFull(c, mapped);
9793
9794 for (j = 0; j < n_res; j++) {
9795 if (mapped[j] > *maxchar)
9796 *maxchar = mapped[j];
9797 res[k++] = mapped[j];
9798 }
9799
9800 previous_is_cased = _PyUnicode_IsCased(c);
9801 }
9802 return k;
9803}
9804
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009805static PyObject *
9806case_operation(PyObject *self,
9807 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9808{
9809 PyObject *res = NULL;
9810 Py_ssize_t length, newlength = 0;
9811 int kind, outkind;
9812 void *data, *outdata;
9813 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9814
Benjamin Petersoneea48462012-01-16 14:28:50 -05009815 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009816
9817 kind = PyUnicode_KIND(self);
9818 data = PyUnicode_DATA(self);
9819 length = PyUnicode_GET_LENGTH(self);
9820 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9821 if (tmp == NULL)
9822 return PyErr_NoMemory();
9823 newlength = perform(kind, data, length, tmp, &maxchar);
9824 res = PyUnicode_New(newlength, maxchar);
9825 if (res == NULL)
9826 goto leave;
9827 tmpend = tmp + newlength;
9828 outdata = PyUnicode_DATA(res);
9829 outkind = PyUnicode_KIND(res);
9830 switch (outkind) {
9831 case PyUnicode_1BYTE_KIND:
9832 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9833 break;
9834 case PyUnicode_2BYTE_KIND:
9835 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9836 break;
9837 case PyUnicode_4BYTE_KIND:
9838 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9839 break;
9840 default:
9841 assert(0);
9842 break;
9843 }
9844 leave:
9845 PyMem_FREE(tmp);
9846 return res;
9847}
9848
Tim Peters8ce9f162004-08-27 01:49:32 +00009849PyObject *
9850PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009851{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009852 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009853 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009854 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009855 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009856 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9857 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009858 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009859 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009860 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009861 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009862 int use_memcpy;
9863 unsigned char *res_data = NULL, *sep_data = NULL;
9864 PyObject *last_obj;
9865 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009866
Tim Peters05eba1f2004-08-27 21:32:02 +00009867 fseq = PySequence_Fast(seq, "");
9868 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009869 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009870 }
9871
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009872 /* NOTE: the following code can't call back into Python code,
9873 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009874 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009875
Tim Peters05eba1f2004-08-27 21:32:02 +00009876 seqlen = PySequence_Fast_GET_SIZE(fseq);
9877 /* If empty sequence, return u"". */
9878 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009879 Py_DECREF(fseq);
9880 Py_INCREF(unicode_empty);
9881 res = unicode_empty;
9882 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009883 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009884
Tim Peters05eba1f2004-08-27 21:32:02 +00009885 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009886 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009887 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009888 if (seqlen == 1) {
9889 if (PyUnicode_CheckExact(items[0])) {
9890 res = items[0];
9891 Py_INCREF(res);
9892 Py_DECREF(fseq);
9893 return res;
9894 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009895 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009896 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009897 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009898 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009899 /* Set up sep and seplen */
9900 if (separator == NULL) {
9901 /* fall back to a blank space separator */
9902 sep = PyUnicode_FromOrdinal(' ');
9903 if (!sep)
9904 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009905 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009906 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009907 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009908 else {
9909 if (!PyUnicode_Check(separator)) {
9910 PyErr_Format(PyExc_TypeError,
9911 "separator: expected str instance,"
9912 " %.80s found",
9913 Py_TYPE(separator)->tp_name);
9914 goto onError;
9915 }
9916 if (PyUnicode_READY(separator))
9917 goto onError;
9918 sep = separator;
9919 seplen = PyUnicode_GET_LENGTH(separator);
9920 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9921 /* inc refcount to keep this code path symmetric with the
9922 above case of a blank separator */
9923 Py_INCREF(sep);
9924 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009925 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009926 }
9927
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009928 /* There are at least two things to join, or else we have a subclass
9929 * of str in the sequence.
9930 * Do a pre-pass to figure out the total amount of space we'll
9931 * need (sz), and see whether all argument are strings.
9932 */
9933 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009934#ifdef Py_DEBUG
9935 use_memcpy = 0;
9936#else
9937 use_memcpy = 1;
9938#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009939 for (i = 0; i < seqlen; i++) {
9940 const Py_ssize_t old_sz = sz;
9941 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009942 if (!PyUnicode_Check(item)) {
9943 PyErr_Format(PyExc_TypeError,
9944 "sequence item %zd: expected str instance,"
9945 " %.80s found",
9946 i, Py_TYPE(item)->tp_name);
9947 goto onError;
9948 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009949 if (PyUnicode_READY(item) == -1)
9950 goto onError;
9951 sz += PyUnicode_GET_LENGTH(item);
9952 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009953 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009954 if (i != 0)
9955 sz += seplen;
9956 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9957 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009958 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009959 goto onError;
9960 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009961 if (use_memcpy && last_obj != NULL) {
9962 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9963 use_memcpy = 0;
9964 }
9965 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009966 }
Tim Petersced69f82003-09-16 20:30:58 +00009967
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009968 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009969 if (res == NULL)
9970 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009971
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009972 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009973#ifdef Py_DEBUG
9974 use_memcpy = 0;
9975#else
9976 if (use_memcpy) {
9977 res_data = PyUnicode_1BYTE_DATA(res);
9978 kind = PyUnicode_KIND(res);
9979 if (seplen != 0)
9980 sep_data = PyUnicode_1BYTE_DATA(sep);
9981 }
9982#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009983 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009984 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009985 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009986 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009987 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009988 if (use_memcpy) {
9989 Py_MEMCPY(res_data,
9990 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009991 kind * seplen);
9992 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009993 }
9994 else {
9995 copy_characters(res, res_offset, sep, 0, seplen);
9996 res_offset += seplen;
9997 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009998 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009999 itemlen = PyUnicode_GET_LENGTH(item);
10000 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +020010001 if (use_memcpy) {
10002 Py_MEMCPY(res_data,
10003 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010004 kind * itemlen);
10005 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010006 }
10007 else {
10008 copy_characters(res, res_offset, item, 0, itemlen);
10009 res_offset += itemlen;
10010 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010011 }
Tim Peters05eba1f2004-08-27 21:32:02 +000010012 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010013 if (use_memcpy)
10014 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010015 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +020010016 else
10017 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +000010018
Tim Peters05eba1f2004-08-27 21:32:02 +000010019 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010020 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010021 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010022 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010023
Benjamin Peterson29060642009-01-31 22:14:21 +000010024 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +000010025 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010026 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010027 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010028 return NULL;
10029}
10030
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010031#define FILL(kind, data, value, start, length) \
10032 do { \
10033 Py_ssize_t i_ = 0; \
10034 assert(kind != PyUnicode_WCHAR_KIND); \
10035 switch ((kind)) { \
10036 case PyUnicode_1BYTE_KIND: { \
10037 unsigned char * to_ = (unsigned char *)((data)) + (start); \
10038 memset(to_, (unsigned char)value, length); \
10039 break; \
10040 } \
10041 case PyUnicode_2BYTE_KIND: { \
10042 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10043 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10044 break; \
10045 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010046 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010047 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10048 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10049 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010050 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010051 } \
10052 } \
10053 } while (0)
10054
Victor Stinner3fe55312012-01-04 00:33:50 +010010055Py_ssize_t
10056PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10057 Py_UCS4 fill_char)
10058{
10059 Py_ssize_t maxlen;
10060 enum PyUnicode_Kind kind;
10061 void *data;
10062
10063 if (!PyUnicode_Check(unicode)) {
10064 PyErr_BadInternalCall();
10065 return -1;
10066 }
10067 if (PyUnicode_READY(unicode) == -1)
10068 return -1;
10069 if (unicode_check_modifiable(unicode))
10070 return -1;
10071
10072 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10073 PyErr_SetString(PyExc_ValueError,
10074 "fill character is bigger than "
10075 "the string maximum character");
10076 return -1;
10077 }
10078
10079 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10080 length = Py_MIN(maxlen, length);
10081 if (length <= 0)
10082 return 0;
10083
10084 kind = PyUnicode_KIND(unicode);
10085 data = PyUnicode_DATA(unicode);
10086 FILL(kind, data, fill_char, start, length);
10087 return length;
10088}
10089
Victor Stinner9310abb2011-10-05 00:59:23 +020010090static PyObject *
10091pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010092 Py_ssize_t left,
10093 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010095{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010096 PyObject *u;
10097 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010098 int kind;
10099 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010100
10101 if (left < 0)
10102 left = 0;
10103 if (right < 0)
10104 right = 0;
10105
Victor Stinnerc4b49542011-12-11 22:44:26 +010010106 if (left == 0 && right == 0)
10107 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010108
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010109 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10110 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010111 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10112 return NULL;
10113 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010114 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10115 if (fill > maxchar)
10116 maxchar = fill;
10117 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010118 if (!u)
10119 return NULL;
10120
10121 kind = PyUnicode_KIND(u);
10122 data = PyUnicode_DATA(u);
10123 if (left)
10124 FILL(kind, data, fill, 0, left);
10125 if (right)
10126 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010127 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010128 assert(_PyUnicode_CheckConsistency(u, 1));
10129 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010130}
10131
Alexander Belopolsky40018472011-02-26 01:02:56 +000010132PyObject *
10133PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010134{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010135 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010136
10137 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010138 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010139 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060010140 if (PyUnicode_READY(string) == -1) {
10141 Py_DECREF(string);
10142 return NULL;
10143 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010144
Benjamin Petersonead6b532011-12-20 17:23:42 -060010145 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010146 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010147 if (PyUnicode_IS_ASCII(string))
10148 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010149 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010150 PyUnicode_GET_LENGTH(string), keepends);
10151 else
10152 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010153 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010154 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010155 break;
10156 case PyUnicode_2BYTE_KIND:
10157 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010158 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 PyUnicode_GET_LENGTH(string), keepends);
10160 break;
10161 case PyUnicode_4BYTE_KIND:
10162 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010163 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010164 PyUnicode_GET_LENGTH(string), keepends);
10165 break;
10166 default:
10167 assert(0);
10168 list = 0;
10169 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010170 Py_DECREF(string);
10171 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010172}
10173
Alexander Belopolsky40018472011-02-26 01:02:56 +000010174static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010175split(PyObject *self,
10176 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010177 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010178{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 int kind1, kind2, kind;
10180 void *buf1, *buf2;
10181 Py_ssize_t len1, len2;
10182 PyObject* out;
10183
Guido van Rossumd57fd912000-03-10 22:53:23 +000010184 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010185 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010186
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010187 if (PyUnicode_READY(self) == -1)
10188 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010189
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010191 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010192 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010193 if (PyUnicode_IS_ASCII(self))
10194 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010195 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010196 PyUnicode_GET_LENGTH(self), maxcount
10197 );
10198 else
10199 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010200 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010201 PyUnicode_GET_LENGTH(self), maxcount
10202 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 case PyUnicode_2BYTE_KIND:
10204 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010205 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010206 PyUnicode_GET_LENGTH(self), maxcount
10207 );
10208 case PyUnicode_4BYTE_KIND:
10209 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010210 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010211 PyUnicode_GET_LENGTH(self), maxcount
10212 );
10213 default:
10214 assert(0);
10215 return NULL;
10216 }
10217
10218 if (PyUnicode_READY(substring) == -1)
10219 return NULL;
10220
10221 kind1 = PyUnicode_KIND(self);
10222 kind2 = PyUnicode_KIND(substring);
10223 kind = kind1 > kind2 ? kind1 : kind2;
10224 buf1 = PyUnicode_DATA(self);
10225 buf2 = PyUnicode_DATA(substring);
10226 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010227 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010228 if (!buf1)
10229 return NULL;
10230 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010231 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 if (!buf2) {
10233 if (kind1 != kind) PyMem_Free(buf1);
10234 return NULL;
10235 }
10236 len1 = PyUnicode_GET_LENGTH(self);
10237 len2 = PyUnicode_GET_LENGTH(substring);
10238
Benjamin Petersonead6b532011-12-20 17:23:42 -060010239 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010241 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10242 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010243 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010244 else
10245 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010246 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010247 break;
10248 case PyUnicode_2BYTE_KIND:
10249 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010250 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010251 break;
10252 case PyUnicode_4BYTE_KIND:
10253 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010254 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010255 break;
10256 default:
10257 out = NULL;
10258 }
10259 if (kind1 != kind)
10260 PyMem_Free(buf1);
10261 if (kind2 != kind)
10262 PyMem_Free(buf2);
10263 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010264}
10265
Alexander Belopolsky40018472011-02-26 01:02:56 +000010266static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010267rsplit(PyObject *self,
10268 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010269 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010270{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010271 int kind1, kind2, kind;
10272 void *buf1, *buf2;
10273 Py_ssize_t len1, len2;
10274 PyObject* out;
10275
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010276 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010277 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010278
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010279 if (PyUnicode_READY(self) == -1)
10280 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010281
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010282 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010283 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010285 if (PyUnicode_IS_ASCII(self))
10286 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010287 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010288 PyUnicode_GET_LENGTH(self), maxcount
10289 );
10290 else
10291 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010292 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010293 PyUnicode_GET_LENGTH(self), maxcount
10294 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010295 case PyUnicode_2BYTE_KIND:
10296 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010297 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010298 PyUnicode_GET_LENGTH(self), maxcount
10299 );
10300 case PyUnicode_4BYTE_KIND:
10301 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010302 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010303 PyUnicode_GET_LENGTH(self), maxcount
10304 );
10305 default:
10306 assert(0);
10307 return NULL;
10308 }
10309
10310 if (PyUnicode_READY(substring) == -1)
10311 return NULL;
10312
10313 kind1 = PyUnicode_KIND(self);
10314 kind2 = PyUnicode_KIND(substring);
10315 kind = kind1 > kind2 ? kind1 : kind2;
10316 buf1 = PyUnicode_DATA(self);
10317 buf2 = PyUnicode_DATA(substring);
10318 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010319 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010320 if (!buf1)
10321 return NULL;
10322 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010323 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010324 if (!buf2) {
10325 if (kind1 != kind) PyMem_Free(buf1);
10326 return NULL;
10327 }
10328 len1 = PyUnicode_GET_LENGTH(self);
10329 len2 = PyUnicode_GET_LENGTH(substring);
10330
Benjamin Petersonead6b532011-12-20 17:23:42 -060010331 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010332 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010333 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10334 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010335 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010336 else
10337 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010338 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010339 break;
10340 case PyUnicode_2BYTE_KIND:
10341 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010342 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010343 break;
10344 case PyUnicode_4BYTE_KIND:
10345 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010346 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010347 break;
10348 default:
10349 out = NULL;
10350 }
10351 if (kind1 != kind)
10352 PyMem_Free(buf1);
10353 if (kind2 != kind)
10354 PyMem_Free(buf2);
10355 return out;
10356}
10357
10358static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010359anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10360 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010361{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010362 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010364 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10365 return asciilib_find(buf1, len1, buf2, len2, offset);
10366 else
10367 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010368 case PyUnicode_2BYTE_KIND:
10369 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10370 case PyUnicode_4BYTE_KIND:
10371 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10372 }
10373 assert(0);
10374 return -1;
10375}
10376
10377static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010378anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10379 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010380{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010381 switch (kind) {
10382 case PyUnicode_1BYTE_KIND:
10383 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10384 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10385 else
10386 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10387 case PyUnicode_2BYTE_KIND:
10388 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10389 case PyUnicode_4BYTE_KIND:
10390 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10391 }
10392 assert(0);
10393 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010394}
10395
Alexander Belopolsky40018472011-02-26 01:02:56 +000010396static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010397replace(PyObject *self, PyObject *str1,
10398 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010399{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010400 PyObject *u;
10401 char *sbuf = PyUnicode_DATA(self);
10402 char *buf1 = PyUnicode_DATA(str1);
10403 char *buf2 = PyUnicode_DATA(str2);
10404 int srelease = 0, release1 = 0, release2 = 0;
10405 int skind = PyUnicode_KIND(self);
10406 int kind1 = PyUnicode_KIND(str1);
10407 int kind2 = PyUnicode_KIND(str2);
10408 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10409 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10410 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010411 int mayshrink;
10412 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010413
10414 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010415 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010416 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010417 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010418
Victor Stinner59de0ee2011-10-07 10:01:28 +020010419 if (str1 == str2)
10420 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421 if (skind < kind1)
10422 /* substring too wide to be present */
10423 goto nothing;
10424
Victor Stinner49a0a212011-10-12 23:46:10 +020010425 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10426 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10427 /* Replacing str1 with str2 may cause a maxchar reduction in the
10428 result string. */
10429 mayshrink = (maxchar_str2 < maxchar);
10430 maxchar = Py_MAX(maxchar, maxchar_str2);
10431
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010433 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010434 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010435 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010436 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010437 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010438 Py_UCS4 u1, u2;
10439 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010440 Py_ssize_t index, pos;
10441 char *src;
10442
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010443 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010444 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10445 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010446 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010447 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010449 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010450 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010451 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010452 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010453
10454 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10455 index = 0;
10456 src = sbuf;
10457 while (--maxcount)
10458 {
10459 pos++;
10460 src += pos * PyUnicode_KIND(self);
10461 slen -= pos;
10462 index += pos;
10463 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10464 if (pos < 0)
10465 break;
10466 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10467 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010468 }
10469 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470 int rkind = skind;
10471 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010472 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010473
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010474 if (kind1 < rkind) {
10475 /* widen substring */
10476 buf1 = _PyUnicode_AsKind(str1, rkind);
10477 if (!buf1) goto error;
10478 release1 = 1;
10479 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010480 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010481 if (i < 0)
10482 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010483 if (rkind > kind2) {
10484 /* widen replacement */
10485 buf2 = _PyUnicode_AsKind(str2, rkind);
10486 if (!buf2) goto error;
10487 release2 = 1;
10488 }
10489 else if (rkind < kind2) {
10490 /* widen self and buf1 */
10491 rkind = kind2;
10492 if (release1) PyMem_Free(buf1);
10493 sbuf = _PyUnicode_AsKind(self, rkind);
10494 if (!sbuf) goto error;
10495 srelease = 1;
10496 buf1 = _PyUnicode_AsKind(str1, rkind);
10497 if (!buf1) goto error;
10498 release1 = 1;
10499 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010500 u = PyUnicode_New(slen, maxchar);
10501 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010502 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010503 assert(PyUnicode_KIND(u) == rkind);
10504 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010505
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010506 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010507 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010508 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010510 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010512
10513 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010514 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010515 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010516 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010517 if (i == -1)
10518 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010519 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010520 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010521 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010522 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010523 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010524 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010525 }
10526 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010527 Py_ssize_t n, i, j, ires;
10528 Py_ssize_t product, new_size;
10529 int rkind = skind;
10530 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010531
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010532 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010533 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010534 buf1 = _PyUnicode_AsKind(str1, rkind);
10535 if (!buf1) goto error;
10536 release1 = 1;
10537 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010538 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010539 if (n == 0)
10540 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010541 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010542 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010543 buf2 = _PyUnicode_AsKind(str2, rkind);
10544 if (!buf2) goto error;
10545 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010546 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010547 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010548 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010549 rkind = kind2;
10550 sbuf = _PyUnicode_AsKind(self, rkind);
10551 if (!sbuf) goto error;
10552 srelease = 1;
10553 if (release1) PyMem_Free(buf1);
10554 buf1 = _PyUnicode_AsKind(str1, rkind);
10555 if (!buf1) goto error;
10556 release1 = 1;
10557 }
10558 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10559 PyUnicode_GET_LENGTH(str1))); */
10560 product = n * (len2-len1);
10561 if ((product / (len2-len1)) != n) {
10562 PyErr_SetString(PyExc_OverflowError,
10563 "replace string is too long");
10564 goto error;
10565 }
10566 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010567 if (new_size == 0) {
10568 Py_INCREF(unicode_empty);
10569 u = unicode_empty;
10570 goto done;
10571 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010572 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10573 PyErr_SetString(PyExc_OverflowError,
10574 "replace string is too long");
10575 goto error;
10576 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010577 u = PyUnicode_New(new_size, maxchar);
10578 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010579 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010580 assert(PyUnicode_KIND(u) == rkind);
10581 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 ires = i = 0;
10583 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010584 while (n-- > 0) {
10585 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010586 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010587 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010588 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010589 if (j == -1)
10590 break;
10591 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010592 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010593 memcpy(res + rkind * ires,
10594 sbuf + rkind * i,
10595 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010596 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010597 }
10598 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010599 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010600 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010602 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010604 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010605 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010606 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010607 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010608 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010609 memcpy(res + rkind * ires,
10610 sbuf + rkind * i,
10611 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010612 }
10613 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010614 /* interleave */
10615 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010616 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010617 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010618 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010619 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010620 if (--n <= 0)
10621 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010622 memcpy(res + rkind * ires,
10623 sbuf + rkind * i,
10624 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010625 ires++;
10626 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010627 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010628 memcpy(res + rkind * ires,
10629 sbuf + rkind * i,
10630 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010631 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010632 }
10633
10634 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010635 unicode_adjust_maxchar(&u);
10636 if (u == NULL)
10637 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010638 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010639
10640 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010641 if (srelease)
10642 PyMem_FREE(sbuf);
10643 if (release1)
10644 PyMem_FREE(buf1);
10645 if (release2)
10646 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010647 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010648 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010649
Benjamin Peterson29060642009-01-31 22:14:21 +000010650 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010651 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010652 if (srelease)
10653 PyMem_FREE(sbuf);
10654 if (release1)
10655 PyMem_FREE(buf1);
10656 if (release2)
10657 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010658 return unicode_result_unchanged(self);
10659
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010660 error:
10661 if (srelease && sbuf)
10662 PyMem_FREE(sbuf);
10663 if (release1 && buf1)
10664 PyMem_FREE(buf1);
10665 if (release2 && buf2)
10666 PyMem_FREE(buf2);
10667 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010668}
10669
10670/* --- Unicode Object Methods --------------------------------------------- */
10671
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010672PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010673 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010674\n\
10675Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010676characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010677
10678static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010679unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010680{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010681 if (PyUnicode_READY(self) == -1)
10682 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010683 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010684}
10685
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010686PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010687 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010688\n\
10689Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010690have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010691
10692static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010693unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010694{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010695 if (PyUnicode_READY(self) == -1)
10696 return NULL;
10697 if (PyUnicode_GET_LENGTH(self) == 0)
10698 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010699 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010700}
10701
Benjamin Petersond5890c82012-01-14 13:23:30 -050010702PyDoc_STRVAR(casefold__doc__,
10703 "S.casefold() -> str\n\
10704\n\
10705Return a version of S suitable for caseless comparisons.");
10706
10707static PyObject *
10708unicode_casefold(PyObject *self)
10709{
10710 if (PyUnicode_READY(self) == -1)
10711 return NULL;
10712 if (PyUnicode_IS_ASCII(self))
10713 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010714 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010715}
10716
10717
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010718/* Argument converter. Coerces to a single unicode character */
10719
10720static int
10721convert_uc(PyObject *obj, void *addr)
10722{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010723 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010724 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010725
Benjamin Peterson14339b62009-01-31 16:36:08 +000010726 uniobj = PyUnicode_FromObject(obj);
10727 if (uniobj == NULL) {
10728 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010729 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010730 return 0;
10731 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010732 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010733 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010734 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010735 Py_DECREF(uniobj);
10736 return 0;
10737 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010738 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010739 Py_DECREF(uniobj);
10740 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010741}
10742
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010743PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010744 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010745\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010746Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010747done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010748
10749static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010750unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010751{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010752 Py_ssize_t marg, left;
10753 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010754 Py_UCS4 fillchar = ' ';
10755
Victor Stinnere9a29352011-10-01 02:14:59 +020010756 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010757 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010758
Benjamin Petersonbac79492012-01-14 13:34:47 -050010759 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010760 return NULL;
10761
Victor Stinnerc4b49542011-12-11 22:44:26 +010010762 if (PyUnicode_GET_LENGTH(self) >= width)
10763 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010764
Victor Stinnerc4b49542011-12-11 22:44:26 +010010765 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010766 left = marg / 2 + (marg & width & 1);
10767
Victor Stinner9310abb2011-10-05 00:59:23 +020010768 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010769}
10770
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010771/* This function assumes that str1 and str2 are readied by the caller. */
10772
Marc-André Lemburge5034372000-08-08 08:04:29 +000010773static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010774unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010775{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010776 int kind1, kind2;
10777 void *data1, *data2;
10778 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010779
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010780 kind1 = PyUnicode_KIND(str1);
10781 kind2 = PyUnicode_KIND(str2);
10782 data1 = PyUnicode_DATA(str1);
10783 data2 = PyUnicode_DATA(str2);
10784 len1 = PyUnicode_GET_LENGTH(str1);
10785 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010786
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010787 for (i = 0; i < len1 && i < len2; ++i) {
10788 Py_UCS4 c1, c2;
10789 c1 = PyUnicode_READ(kind1, data1, i);
10790 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010791
10792 if (c1 != c2)
10793 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010794 }
10795
10796 return (len1 < len2) ? -1 : (len1 != len2);
10797}
10798
Alexander Belopolsky40018472011-02-26 01:02:56 +000010799int
10800PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010801{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010802 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10803 if (PyUnicode_READY(left) == -1 ||
10804 PyUnicode_READY(right) == -1)
10805 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010806 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010807 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010808 PyErr_Format(PyExc_TypeError,
10809 "Can't compare %.100s and %.100s",
10810 left->ob_type->tp_name,
10811 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010812 return -1;
10813}
10814
Martin v. Löwis5b222132007-06-10 09:51:05 +000010815int
10816PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10817{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010818 Py_ssize_t i;
10819 int kind;
10820 void *data;
10821 Py_UCS4 chr;
10822
Victor Stinner910337b2011-10-03 03:20:16 +020010823 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010824 if (PyUnicode_READY(uni) == -1)
10825 return -1;
10826 kind = PyUnicode_KIND(uni);
10827 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010828 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010829 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10830 if (chr != str[i])
10831 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010832 /* This check keeps Python strings that end in '\0' from comparing equal
10833 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010834 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010835 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010836 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010837 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010838 return 0;
10839}
10840
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010841
Benjamin Peterson29060642009-01-31 22:14:21 +000010842#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010843 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010844
Alexander Belopolsky40018472011-02-26 01:02:56 +000010845PyObject *
10846PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010847{
10848 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010849
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010850 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10851 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010852 if (PyUnicode_READY(left) == -1 ||
10853 PyUnicode_READY(right) == -1)
10854 return NULL;
10855 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10856 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010857 if (op == Py_EQ) {
10858 Py_INCREF(Py_False);
10859 return Py_False;
10860 }
10861 if (op == Py_NE) {
10862 Py_INCREF(Py_True);
10863 return Py_True;
10864 }
10865 }
10866 if (left == right)
10867 result = 0;
10868 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010869 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010870
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010871 /* Convert the return value to a Boolean */
10872 switch (op) {
10873 case Py_EQ:
10874 v = TEST_COND(result == 0);
10875 break;
10876 case Py_NE:
10877 v = TEST_COND(result != 0);
10878 break;
10879 case Py_LE:
10880 v = TEST_COND(result <= 0);
10881 break;
10882 case Py_GE:
10883 v = TEST_COND(result >= 0);
10884 break;
10885 case Py_LT:
10886 v = TEST_COND(result == -1);
10887 break;
10888 case Py_GT:
10889 v = TEST_COND(result == 1);
10890 break;
10891 default:
10892 PyErr_BadArgument();
10893 return NULL;
10894 }
10895 Py_INCREF(v);
10896 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010897 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010898
Brian Curtindfc80e32011-08-10 20:28:54 -050010899 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010900}
10901
Alexander Belopolsky40018472011-02-26 01:02:56 +000010902int
10903PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010904{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010905 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010906 int kind1, kind2, kind;
10907 void *buf1, *buf2;
10908 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010909 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010910
10911 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010912 sub = PyUnicode_FromObject(element);
10913 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010914 PyErr_Format(PyExc_TypeError,
10915 "'in <string>' requires string as left operand, not %s",
10916 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010917 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010918 }
10919
Thomas Wouters477c8d52006-05-27 19:21:47 +000010920 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010921 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010922 Py_DECREF(sub);
10923 return -1;
10924 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010925 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10926 Py_DECREF(sub);
10927 Py_DECREF(str);
10928 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010929
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010930 kind1 = PyUnicode_KIND(str);
10931 kind2 = PyUnicode_KIND(sub);
10932 kind = kind1 > kind2 ? kind1 : kind2;
10933 buf1 = PyUnicode_DATA(str);
10934 buf2 = PyUnicode_DATA(sub);
10935 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010936 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010937 if (!buf1) {
10938 Py_DECREF(sub);
10939 return -1;
10940 }
10941 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010942 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010943 if (!buf2) {
10944 Py_DECREF(sub);
10945 if (kind1 != kind) PyMem_Free(buf1);
10946 return -1;
10947 }
10948 len1 = PyUnicode_GET_LENGTH(str);
10949 len2 = PyUnicode_GET_LENGTH(sub);
10950
Benjamin Petersonead6b532011-12-20 17:23:42 -060010951 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010952 case PyUnicode_1BYTE_KIND:
10953 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10954 break;
10955 case PyUnicode_2BYTE_KIND:
10956 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10957 break;
10958 case PyUnicode_4BYTE_KIND:
10959 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10960 break;
10961 default:
10962 result = -1;
10963 assert(0);
10964 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010965
10966 Py_DECREF(str);
10967 Py_DECREF(sub);
10968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010969 if (kind1 != kind)
10970 PyMem_Free(buf1);
10971 if (kind2 != kind)
10972 PyMem_Free(buf2);
10973
Guido van Rossum403d68b2000-03-13 15:55:09 +000010974 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010975}
10976
Guido van Rossumd57fd912000-03-10 22:53:23 +000010977/* Concat to string or Unicode object giving a new Unicode object. */
10978
Alexander Belopolsky40018472011-02-26 01:02:56 +000010979PyObject *
10980PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010981{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010982 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010983 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010984 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010985
10986 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010987 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010988 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010989 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010990 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010991 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010992 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010993
10994 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010995 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010996 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010997 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010998 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010999 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011000 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011001 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002 }
11003
Victor Stinner488fa492011-12-12 00:01:39 +010011004 u_len = PyUnicode_GET_LENGTH(u);
11005 v_len = PyUnicode_GET_LENGTH(v);
11006 if (u_len > PY_SSIZE_T_MAX - v_len) {
11007 PyErr_SetString(PyExc_OverflowError,
11008 "strings are too large to concat");
11009 goto onError;
11010 }
11011 new_len = u_len + v_len;
11012
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011013 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011014 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
11015 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011016
Guido van Rossumd57fd912000-03-10 22:53:23 +000011017 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011018 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011019 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011020 goto onError;
Victor Stinner488fa492011-12-12 00:01:39 +010011021 copy_characters(w, 0, u, 0, u_len);
11022 copy_characters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011023 Py_DECREF(u);
11024 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011025 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011026 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011027
Benjamin Peterson29060642009-01-31 22:14:21 +000011028 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011029 Py_XDECREF(u);
11030 Py_XDECREF(v);
11031 return NULL;
11032}
11033
Walter Dörwald1ab83302007-05-18 17:15:44 +000011034void
Victor Stinner23e56682011-10-03 03:54:37 +020011035PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011036{
Victor Stinner23e56682011-10-03 03:54:37 +020011037 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011038 Py_UCS4 maxchar, maxchar2;
11039 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011040
11041 if (p_left == NULL) {
11042 if (!PyErr_Occurred())
11043 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011044 return;
11045 }
Victor Stinner23e56682011-10-03 03:54:37 +020011046 left = *p_left;
11047 if (right == NULL || !PyUnicode_Check(left)) {
11048 if (!PyErr_Occurred())
11049 PyErr_BadInternalCall();
11050 goto error;
11051 }
11052
Benjamin Petersonbac79492012-01-14 13:34:47 -050011053 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011054 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011055 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011056 goto error;
11057
Victor Stinner488fa492011-12-12 00:01:39 +010011058 /* Shortcuts */
11059 if (left == unicode_empty) {
11060 Py_DECREF(left);
11061 Py_INCREF(right);
11062 *p_left = right;
11063 return;
11064 }
11065 if (right == unicode_empty)
11066 return;
11067
11068 left_len = PyUnicode_GET_LENGTH(left);
11069 right_len = PyUnicode_GET_LENGTH(right);
11070 if (left_len > PY_SSIZE_T_MAX - right_len) {
11071 PyErr_SetString(PyExc_OverflowError,
11072 "strings are too large to concat");
11073 goto error;
11074 }
11075 new_len = left_len + right_len;
11076
11077 if (unicode_modifiable(left)
11078 && PyUnicode_CheckExact(right)
11079 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011080 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11081 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011082 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011083 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011084 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11085 {
11086 /* append inplace */
11087 if (unicode_resize(p_left, new_len) != 0) {
11088 /* XXX if _PyUnicode_Resize() fails, 'left' has been
11089 * deallocated so it cannot be put back into
11090 * 'variable'. The MemoryError is raised when there
11091 * is no value in 'variable', which might (very
11092 * remotely) be a cause of incompatibilities.
11093 */
11094 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020011095 }
Victor Stinner488fa492011-12-12 00:01:39 +010011096 /* copy 'right' into the newly allocated area of 'left' */
11097 copy_characters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011098 }
Victor Stinner488fa492011-12-12 00:01:39 +010011099 else {
11100 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11101 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11102 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011103
Victor Stinner488fa492011-12-12 00:01:39 +010011104 /* Concat the two Unicode strings */
11105 res = PyUnicode_New(new_len, maxchar);
11106 if (res == NULL)
11107 goto error;
11108 copy_characters(res, 0, left, 0, left_len);
11109 copy_characters(res, left_len, right, 0, right_len);
11110 Py_DECREF(left);
11111 *p_left = res;
11112 }
11113 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011114 return;
11115
11116error:
Victor Stinner488fa492011-12-12 00:01:39 +010011117 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011118}
11119
11120void
11121PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11122{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011123 PyUnicode_Append(pleft, right);
11124 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011125}
11126
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011127PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011128 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011129\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011130Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011131string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011132interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011133
11134static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011135unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011136{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011137 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011138 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011139 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011140 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011141 int kind1, kind2, kind;
11142 void *buf1, *buf2;
11143 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011144
Jesus Ceaac451502011-04-20 17:09:23 +020011145 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11146 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011147 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011148
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011149 kind1 = PyUnicode_KIND(self);
11150 kind2 = PyUnicode_KIND(substring);
11151 kind = kind1 > kind2 ? kind1 : kind2;
11152 buf1 = PyUnicode_DATA(self);
11153 buf2 = PyUnicode_DATA(substring);
11154 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011155 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011156 if (!buf1) {
11157 Py_DECREF(substring);
11158 return NULL;
11159 }
11160 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011161 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011162 if (!buf2) {
11163 Py_DECREF(substring);
11164 if (kind1 != kind) PyMem_Free(buf1);
11165 return NULL;
11166 }
11167 len1 = PyUnicode_GET_LENGTH(self);
11168 len2 = PyUnicode_GET_LENGTH(substring);
11169
11170 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060011171 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011172 case PyUnicode_1BYTE_KIND:
11173 iresult = ucs1lib_count(
11174 ((Py_UCS1*)buf1) + start, end - start,
11175 buf2, len2, PY_SSIZE_T_MAX
11176 );
11177 break;
11178 case PyUnicode_2BYTE_KIND:
11179 iresult = ucs2lib_count(
11180 ((Py_UCS2*)buf1) + start, end - start,
11181 buf2, len2, PY_SSIZE_T_MAX
11182 );
11183 break;
11184 case PyUnicode_4BYTE_KIND:
11185 iresult = ucs4lib_count(
11186 ((Py_UCS4*)buf1) + start, end - start,
11187 buf2, len2, PY_SSIZE_T_MAX
11188 );
11189 break;
11190 default:
11191 assert(0); iresult = 0;
11192 }
11193
11194 result = PyLong_FromSsize_t(iresult);
11195
11196 if (kind1 != kind)
11197 PyMem_Free(buf1);
11198 if (kind2 != kind)
11199 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011200
11201 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011202
Guido van Rossumd57fd912000-03-10 22:53:23 +000011203 return result;
11204}
11205
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011206PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011207 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011209Encode S using the codec registered for encoding. Default encoding\n\
11210is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011211handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011212a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11213'xmlcharrefreplace' as well as any other name registered with\n\
11214codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011215
11216static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011217unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011219 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011220 char *encoding = NULL;
11221 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011222
Benjamin Peterson308d6372009-09-18 21:42:35 +000011223 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11224 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011226 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011227}
11228
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011229PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011230 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011231\n\
11232Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011233If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011234
11235static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011236unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011237{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011238 Py_ssize_t i, j, line_pos, src_len, incr;
11239 Py_UCS4 ch;
11240 PyObject *u;
11241 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011242 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011243 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011244 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011245
11246 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011247 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011248
Antoine Pitrou22425222011-10-04 19:10:51 +020011249 if (PyUnicode_READY(self) == -1)
11250 return NULL;
11251
Thomas Wouters7e474022000-07-16 12:04:32 +000011252 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011253 src_len = PyUnicode_GET_LENGTH(self);
11254 i = j = line_pos = 0;
11255 kind = PyUnicode_KIND(self);
11256 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011257 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011258 for (; i < src_len; i++) {
11259 ch = PyUnicode_READ(kind, src_data, i);
11260 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011261 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011262 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011263 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011264 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011265 goto overflow;
11266 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011267 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011268 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011269 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011270 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011271 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011272 goto overflow;
11273 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011274 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011275 if (ch == '\n' || ch == '\r')
11276 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011277 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011278 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011279 if (!found)
11280 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011281
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011283 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011284 if (!u)
11285 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011286 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011287
Antoine Pitroue71d5742011-10-04 15:55:09 +020011288 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011289
Antoine Pitroue71d5742011-10-04 15:55:09 +020011290 for (; i < src_len; i++) {
11291 ch = PyUnicode_READ(kind, src_data, i);
11292 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011293 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011294 incr = tabsize - (line_pos % tabsize);
11295 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011296 FILL(kind, dest_data, ' ', j, incr);
11297 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011298 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011299 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011300 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011301 line_pos++;
11302 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011303 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011304 if (ch == '\n' || ch == '\r')
11305 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011306 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011307 }
11308 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011309 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011310
Antoine Pitroue71d5742011-10-04 15:55:09 +020011311 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011312 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11313 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011314}
11315
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011316PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011317 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011318\n\
11319Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011320such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011321arguments start and end are interpreted as in slice notation.\n\
11322\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011323Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324
11325static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011326unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011327{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011328 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011329 Py_ssize_t start;
11330 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011331 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011332
Jesus Ceaac451502011-04-20 17:09:23 +020011333 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11334 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011335 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011336
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011337 if (PyUnicode_READY(self) == -1)
11338 return NULL;
11339 if (PyUnicode_READY(substring) == -1)
11340 return NULL;
11341
Victor Stinner7931d9a2011-11-04 00:22:48 +010011342 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343
11344 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011345
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011346 if (result == -2)
11347 return NULL;
11348
Christian Heimes217cfd12007-12-02 14:31:20 +000011349 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350}
11351
11352static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011353unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011354{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011355 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11356 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011357 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011358 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011359}
11360
Guido van Rossumc2504932007-09-18 19:42:40 +000011361/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011362 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011363static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011364unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011365{
Guido van Rossumc2504932007-09-18 19:42:40 +000011366 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011367 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011368
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011369#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011370 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011371#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011372 if (_PyUnicode_HASH(self) != -1)
11373 return _PyUnicode_HASH(self);
11374 if (PyUnicode_READY(self) == -1)
11375 return -1;
11376 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011377 /*
11378 We make the hash of the empty string be 0, rather than using
11379 (prefix ^ suffix), since this slightly obfuscates the hash secret
11380 */
11381 if (len == 0) {
11382 _PyUnicode_HASH(self) = 0;
11383 return 0;
11384 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011385
11386 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011387#define HASH(P) \
11388 x ^= (Py_uhash_t) *P << 7; \
11389 while (--len >= 0) \
11390 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011391
Georg Brandl2fb477c2012-02-21 00:33:36 +010011392 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011393 switch (PyUnicode_KIND(self)) {
11394 case PyUnicode_1BYTE_KIND: {
11395 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11396 HASH(c);
11397 break;
11398 }
11399 case PyUnicode_2BYTE_KIND: {
11400 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11401 HASH(s);
11402 break;
11403 }
11404 default: {
11405 Py_UCS4 *l;
11406 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11407 "Impossible switch case in unicode_hash");
11408 l = PyUnicode_4BYTE_DATA(self);
11409 HASH(l);
11410 break;
11411 }
11412 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011413 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11414 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011415
Guido van Rossumc2504932007-09-18 19:42:40 +000011416 if (x == -1)
11417 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011418 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011419 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011421#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011422
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011423PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011424 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011425\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011426Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011427
11428static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011429unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011430{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011431 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011432 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011433 Py_ssize_t start;
11434 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435
Jesus Ceaac451502011-04-20 17:09:23 +020011436 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11437 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011438 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011440 if (PyUnicode_READY(self) == -1)
11441 return NULL;
11442 if (PyUnicode_READY(substring) == -1)
11443 return NULL;
11444
Victor Stinner7931d9a2011-11-04 00:22:48 +010011445 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011446
11447 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011448
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011449 if (result == -2)
11450 return NULL;
11451
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452 if (result < 0) {
11453 PyErr_SetString(PyExc_ValueError, "substring not found");
11454 return NULL;
11455 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011456
Christian Heimes217cfd12007-12-02 14:31:20 +000011457 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011458}
11459
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011460PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011461 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011463Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011464at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011465
11466static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011467unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011468{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011469 Py_ssize_t i, length;
11470 int kind;
11471 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011472 int cased;
11473
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011474 if (PyUnicode_READY(self) == -1)
11475 return NULL;
11476 length = PyUnicode_GET_LENGTH(self);
11477 kind = PyUnicode_KIND(self);
11478 data = PyUnicode_DATA(self);
11479
Guido van Rossumd57fd912000-03-10 22:53:23 +000011480 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011481 if (length == 1)
11482 return PyBool_FromLong(
11483 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011485 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011486 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011487 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011488
Guido van Rossumd57fd912000-03-10 22:53:23 +000011489 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011490 for (i = 0; i < length; i++) {
11491 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011492
Benjamin Peterson29060642009-01-31 22:14:21 +000011493 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11494 return PyBool_FromLong(0);
11495 else if (!cased && Py_UNICODE_ISLOWER(ch))
11496 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011498 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499}
11500
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011501PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011502 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011503\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011504Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011505at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011506
11507static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011508unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011509{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011510 Py_ssize_t i, length;
11511 int kind;
11512 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011513 int cased;
11514
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011515 if (PyUnicode_READY(self) == -1)
11516 return NULL;
11517 length = PyUnicode_GET_LENGTH(self);
11518 kind = PyUnicode_KIND(self);
11519 data = PyUnicode_DATA(self);
11520
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011522 if (length == 1)
11523 return PyBool_FromLong(
11524 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011525
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011526 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011527 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011528 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011529
Guido van Rossumd57fd912000-03-10 22:53:23 +000011530 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011531 for (i = 0; i < length; i++) {
11532 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011533
Benjamin Peterson29060642009-01-31 22:14:21 +000011534 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11535 return PyBool_FromLong(0);
11536 else if (!cased && Py_UNICODE_ISUPPER(ch))
11537 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011539 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540}
11541
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011542PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011543 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011544\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011545Return True if S is a titlecased string and there is at least one\n\
11546character in S, i.e. upper- and titlecase characters may only\n\
11547follow uncased characters and lowercase characters only cased ones.\n\
11548Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549
11550static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011551unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011552{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011553 Py_ssize_t i, length;
11554 int kind;
11555 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011556 int cased, previous_is_cased;
11557
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011558 if (PyUnicode_READY(self) == -1)
11559 return NULL;
11560 length = PyUnicode_GET_LENGTH(self);
11561 kind = PyUnicode_KIND(self);
11562 data = PyUnicode_DATA(self);
11563
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011565 if (length == 1) {
11566 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11567 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11568 (Py_UNICODE_ISUPPER(ch) != 0));
11569 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011571 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011572 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011573 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011574
Guido van Rossumd57fd912000-03-10 22:53:23 +000011575 cased = 0;
11576 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011577 for (i = 0; i < length; i++) {
11578 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011579
Benjamin Peterson29060642009-01-31 22:14:21 +000011580 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11581 if (previous_is_cased)
11582 return PyBool_FromLong(0);
11583 previous_is_cased = 1;
11584 cased = 1;
11585 }
11586 else if (Py_UNICODE_ISLOWER(ch)) {
11587 if (!previous_is_cased)
11588 return PyBool_FromLong(0);
11589 previous_is_cased = 1;
11590 cased = 1;
11591 }
11592 else
11593 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011594 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011595 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011596}
11597
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011598PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011599 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011600\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011601Return True if all characters in S are whitespace\n\
11602and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011603
11604static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011605unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011607 Py_ssize_t i, length;
11608 int kind;
11609 void *data;
11610
11611 if (PyUnicode_READY(self) == -1)
11612 return NULL;
11613 length = PyUnicode_GET_LENGTH(self);
11614 kind = PyUnicode_KIND(self);
11615 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011616
Guido van Rossumd57fd912000-03-10 22:53:23 +000011617 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011618 if (length == 1)
11619 return PyBool_FromLong(
11620 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011621
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011622 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011623 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011624 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011625
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011626 for (i = 0; i < length; i++) {
11627 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011628 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011629 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011630 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011631 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011632}
11633
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011634PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011635 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011636\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011637Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011638and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011639
11640static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011641unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011642{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011643 Py_ssize_t i, length;
11644 int kind;
11645 void *data;
11646
11647 if (PyUnicode_READY(self) == -1)
11648 return NULL;
11649 length = PyUnicode_GET_LENGTH(self);
11650 kind = PyUnicode_KIND(self);
11651 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011652
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011653 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011654 if (length == 1)
11655 return PyBool_FromLong(
11656 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011657
11658 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011659 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011660 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011661
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011662 for (i = 0; i < length; i++) {
11663 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011664 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011665 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011666 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011667}
11668
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011669PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011670 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011671\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011672Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011673and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011674
11675static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011676unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011677{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011678 int kind;
11679 void *data;
11680 Py_ssize_t len, i;
11681
11682 if (PyUnicode_READY(self) == -1)
11683 return NULL;
11684
11685 kind = PyUnicode_KIND(self);
11686 data = PyUnicode_DATA(self);
11687 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011688
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011689 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690 if (len == 1) {
11691 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11692 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11693 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011694
11695 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011696 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011697 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011698
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011699 for (i = 0; i < len; i++) {
11700 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011701 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011702 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011703 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011704 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011705}
11706
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011707PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011708 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011709\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011710Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011711False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011712
11713static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011714unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011715{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011716 Py_ssize_t i, length;
11717 int kind;
11718 void *data;
11719
11720 if (PyUnicode_READY(self) == -1)
11721 return NULL;
11722 length = PyUnicode_GET_LENGTH(self);
11723 kind = PyUnicode_KIND(self);
11724 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011725
Guido van Rossumd57fd912000-03-10 22:53:23 +000011726 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011727 if (length == 1)
11728 return PyBool_FromLong(
11729 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011730
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011731 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011732 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011733 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011734
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011735 for (i = 0; i < length; i++) {
11736 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011737 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011738 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011739 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011740}
11741
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011742PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011743 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011744\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011745Return True if all characters in S are digits\n\
11746and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011747
11748static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011749unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011750{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011751 Py_ssize_t i, length;
11752 int kind;
11753 void *data;
11754
11755 if (PyUnicode_READY(self) == -1)
11756 return NULL;
11757 length = PyUnicode_GET_LENGTH(self);
11758 kind = PyUnicode_KIND(self);
11759 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011760
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011762 if (length == 1) {
11763 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11764 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11765 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011766
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011767 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011768 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011769 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011770
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011771 for (i = 0; i < length; i++) {
11772 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011773 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011775 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011776}
11777
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011778PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011779 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011780\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011781Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011782False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011783
11784static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011785unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011786{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011787 Py_ssize_t i, length;
11788 int kind;
11789 void *data;
11790
11791 if (PyUnicode_READY(self) == -1)
11792 return NULL;
11793 length = PyUnicode_GET_LENGTH(self);
11794 kind = PyUnicode_KIND(self);
11795 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011796
Guido van Rossumd57fd912000-03-10 22:53:23 +000011797 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011798 if (length == 1)
11799 return PyBool_FromLong(
11800 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011801
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011802 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011803 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011804 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011806 for (i = 0; i < length; i++) {
11807 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011808 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011809 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011810 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011811}
11812
Martin v. Löwis47383402007-08-15 07:32:56 +000011813int
11814PyUnicode_IsIdentifier(PyObject *self)
11815{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011816 int kind;
11817 void *data;
11818 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011819 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011820
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011821 if (PyUnicode_READY(self) == -1) {
11822 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011823 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011824 }
11825
11826 /* Special case for empty strings */
11827 if (PyUnicode_GET_LENGTH(self) == 0)
11828 return 0;
11829 kind = PyUnicode_KIND(self);
11830 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011831
11832 /* PEP 3131 says that the first character must be in
11833 XID_Start and subsequent characters in XID_Continue,
11834 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011835 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011836 letters, digits, underscore). However, given the current
11837 definition of XID_Start and XID_Continue, it is sufficient
11838 to check just for these, except that _ must be allowed
11839 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011840 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011841 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011842 return 0;
11843
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011844 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011845 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011846 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011847 return 1;
11848}
11849
11850PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011851 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011852\n\
11853Return True if S is a valid identifier according\n\
11854to the language definition.");
11855
11856static PyObject*
11857unicode_isidentifier(PyObject *self)
11858{
11859 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11860}
11861
Georg Brandl559e5d72008-06-11 18:37:52 +000011862PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011863 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011864\n\
11865Return True if all characters in S are considered\n\
11866printable in repr() or S is empty, False otherwise.");
11867
11868static PyObject*
11869unicode_isprintable(PyObject *self)
11870{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011871 Py_ssize_t i, length;
11872 int kind;
11873 void *data;
11874
11875 if (PyUnicode_READY(self) == -1)
11876 return NULL;
11877 length = PyUnicode_GET_LENGTH(self);
11878 kind = PyUnicode_KIND(self);
11879 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011880
11881 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011882 if (length == 1)
11883 return PyBool_FromLong(
11884 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011885
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011886 for (i = 0; i < length; i++) {
11887 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011888 Py_RETURN_FALSE;
11889 }
11890 }
11891 Py_RETURN_TRUE;
11892}
11893
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011894PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011895 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011896\n\
11897Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011898iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011899
11900static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011901unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011902{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011903 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011904}
11905
Martin v. Löwis18e16552006-02-15 17:27:45 +000011906static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011907unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011908{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011909 if (PyUnicode_READY(self) == -1)
11910 return -1;
11911 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011912}
11913
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011914PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011915 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011916\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011917Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011918done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011919
11920static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011921unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011922{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011923 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011924 Py_UCS4 fillchar = ' ';
11925
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011926 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011927 return NULL;
11928
Benjamin Petersonbac79492012-01-14 13:34:47 -050011929 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011930 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011931
Victor Stinnerc4b49542011-12-11 22:44:26 +010011932 if (PyUnicode_GET_LENGTH(self) >= width)
11933 return unicode_result_unchanged(self);
11934
11935 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011936}
11937
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011938PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011939 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011940\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011941Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011942
11943static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011944unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011946 if (PyUnicode_READY(self) == -1)
11947 return NULL;
11948 if (PyUnicode_IS_ASCII(self))
11949 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011950 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011951}
11952
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011953#define LEFTSTRIP 0
11954#define RIGHTSTRIP 1
11955#define BOTHSTRIP 2
11956
11957/* Arrays indexed by above */
11958static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11959
11960#define STRIPNAME(i) (stripformat[i]+3)
11961
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011962/* externally visible for str.strip(unicode) */
11963PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011964_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011965{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011966 void *data;
11967 int kind;
11968 Py_ssize_t i, j, len;
11969 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011970
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011971 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11972 return NULL;
11973
11974 kind = PyUnicode_KIND(self);
11975 data = PyUnicode_DATA(self);
11976 len = PyUnicode_GET_LENGTH(self);
11977 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11978 PyUnicode_DATA(sepobj),
11979 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011980
Benjamin Peterson14339b62009-01-31 16:36:08 +000011981 i = 0;
11982 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011983 while (i < len &&
11984 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011985 i++;
11986 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011987 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011988
Benjamin Peterson14339b62009-01-31 16:36:08 +000011989 j = len;
11990 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011991 do {
11992 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011993 } while (j >= i &&
11994 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011995 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011996 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011997
Victor Stinner7931d9a2011-11-04 00:22:48 +010011998 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011999}
12000
12001PyObject*
12002PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12003{
12004 unsigned char *data;
12005 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012006 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012007
Victor Stinnerde636f32011-10-01 03:55:54 +020012008 if (PyUnicode_READY(self) == -1)
12009 return NULL;
12010
12011 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
12012
Victor Stinner12bab6d2011-10-01 01:53:49 +020012013 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Victor Stinnerc4b49542011-12-11 22:44:26 +010012014 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012015
Victor Stinner12bab6d2011-10-01 01:53:49 +020012016 length = end - start;
12017 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020012018 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012019
Victor Stinnerde636f32011-10-01 03:55:54 +020012020 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012021 PyErr_SetString(PyExc_IndexError, "string index out of range");
12022 return NULL;
12023 }
12024
Victor Stinnerb9275c12011-10-05 14:01:42 +020012025 if (PyUnicode_IS_ASCII(self)) {
12026 kind = PyUnicode_KIND(self);
12027 data = PyUnicode_1BYTE_DATA(self);
12028 return unicode_fromascii(data + start, length);
12029 }
12030 else {
12031 kind = PyUnicode_KIND(self);
12032 data = PyUnicode_1BYTE_DATA(self);
12033 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012034 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012035 length);
12036 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012037}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012038
12039static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012040do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012041{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012042 int kind;
12043 void *data;
12044 Py_ssize_t len, i, j;
12045
12046 if (PyUnicode_READY(self) == -1)
12047 return NULL;
12048
12049 kind = PyUnicode_KIND(self);
12050 data = PyUnicode_DATA(self);
12051 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012052
Benjamin Peterson14339b62009-01-31 16:36:08 +000012053 i = 0;
12054 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012055 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012056 i++;
12057 }
12058 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012059
Benjamin Peterson14339b62009-01-31 16:36:08 +000012060 j = len;
12061 if (striptype != LEFTSTRIP) {
12062 do {
12063 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012064 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012065 j++;
12066 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012067
Victor Stinner7931d9a2011-11-04 00:22:48 +010012068 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012069}
12070
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012071
12072static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012073do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012074{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012075 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012076
Benjamin Peterson14339b62009-01-31 16:36:08 +000012077 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
12078 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012079
Benjamin Peterson14339b62009-01-31 16:36:08 +000012080 if (sep != NULL && sep != Py_None) {
12081 if (PyUnicode_Check(sep))
12082 return _PyUnicode_XStrip(self, striptype, sep);
12083 else {
12084 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012085 "%s arg must be None or str",
12086 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012087 return NULL;
12088 }
12089 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012090
Benjamin Peterson14339b62009-01-31 16:36:08 +000012091 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012092}
12093
12094
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012095PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012096 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012097\n\
12098Return a copy of the string S with leading and trailing\n\
12099whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012100If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012101
12102static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012103unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012104{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012105 if (PyTuple_GET_SIZE(args) == 0)
12106 return do_strip(self, BOTHSTRIP); /* Common case */
12107 else
12108 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012109}
12110
12111
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012112PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012113 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012114\n\
12115Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012116If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012117
12118static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012119unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012120{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012121 if (PyTuple_GET_SIZE(args) == 0)
12122 return do_strip(self, LEFTSTRIP); /* Common case */
12123 else
12124 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012125}
12126
12127
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012128PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012129 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012130\n\
12131Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012132If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012133
12134static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012135unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012136{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012137 if (PyTuple_GET_SIZE(args) == 0)
12138 return do_strip(self, RIGHTSTRIP); /* Common case */
12139 else
12140 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012141}
12142
12143
Guido van Rossumd57fd912000-03-10 22:53:23 +000012144static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012145unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012146{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012147 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012148 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012149
Georg Brandl222de0f2009-04-12 12:01:50 +000012150 if (len < 1) {
12151 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020012152 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000012153 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012154
Victor Stinnerc4b49542011-12-11 22:44:26 +010012155 /* no repeat, return original string */
12156 if (len == 1)
12157 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012158
Benjamin Petersonbac79492012-01-14 13:34:47 -050012159 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012160 return NULL;
12161
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012162 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012163 PyErr_SetString(PyExc_OverflowError,
12164 "repeated string is too long");
12165 return NULL;
12166 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012167 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012168
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012169 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012170 if (!u)
12171 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012172 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012173
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012174 if (PyUnicode_GET_LENGTH(str) == 1) {
12175 const int kind = PyUnicode_KIND(str);
12176 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012177 if (kind == PyUnicode_1BYTE_KIND) {
12178 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012179 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012180 }
12181 else if (kind == PyUnicode_2BYTE_KIND) {
12182 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012183 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012184 ucs2[n] = fill_char;
12185 } else {
12186 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12187 assert(kind == PyUnicode_4BYTE_KIND);
12188 for (n = 0; n < len; ++n)
12189 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012190 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012191 }
12192 else {
12193 /* number of characters copied this far */
12194 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012195 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012196 char *to = (char *) PyUnicode_DATA(u);
12197 Py_MEMCPY(to, PyUnicode_DATA(str),
12198 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012199 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012200 n = (done <= nchars-done) ? done : nchars-done;
12201 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012202 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012203 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012204 }
12205
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012206 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012207 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012208}
12209
Alexander Belopolsky40018472011-02-26 01:02:56 +000012210PyObject *
12211PyUnicode_Replace(PyObject *obj,
12212 PyObject *subobj,
12213 PyObject *replobj,
12214 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012215{
12216 PyObject *self;
12217 PyObject *str1;
12218 PyObject *str2;
12219 PyObject *result;
12220
12221 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012222 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012223 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012224 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012225 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012226 Py_DECREF(self);
12227 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012228 }
12229 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012230 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012231 Py_DECREF(self);
12232 Py_DECREF(str1);
12233 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012234 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012235 if (PyUnicode_READY(self) == -1 ||
12236 PyUnicode_READY(str1) == -1 ||
12237 PyUnicode_READY(str2) == -1)
12238 result = NULL;
12239 else
12240 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241 Py_DECREF(self);
12242 Py_DECREF(str1);
12243 Py_DECREF(str2);
12244 return result;
12245}
12246
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012247PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012248 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012249\n\
12250Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012251old replaced by new. If the optional argument count is\n\
12252given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012253
12254static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012255unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012256{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012257 PyObject *str1;
12258 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012259 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012260 PyObject *result;
12261
Martin v. Löwis18e16552006-02-15 17:27:45 +000012262 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012264 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012265 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012266 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012267 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012268 return NULL;
12269 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012270 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012271 Py_DECREF(str1);
12272 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012273 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012274 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12275 result = NULL;
12276 else
12277 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012278
12279 Py_DECREF(str1);
12280 Py_DECREF(str2);
12281 return result;
12282}
12283
Alexander Belopolsky40018472011-02-26 01:02:56 +000012284static PyObject *
12285unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012286{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012287 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012288 Py_ssize_t isize;
12289 Py_ssize_t osize, squote, dquote, i, o;
12290 Py_UCS4 max, quote;
12291 int ikind, okind;
12292 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012293
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012294 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012295 return NULL;
12296
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012297 isize = PyUnicode_GET_LENGTH(unicode);
12298 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012299
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012300 /* Compute length of output, quote characters, and
12301 maximum character */
12302 osize = 2; /* quotes */
12303 max = 127;
12304 squote = dquote = 0;
12305 ikind = PyUnicode_KIND(unicode);
12306 for (i = 0; i < isize; i++) {
12307 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12308 switch (ch) {
12309 case '\'': squote++; osize++; break;
12310 case '"': dquote++; osize++; break;
12311 case '\\': case '\t': case '\r': case '\n':
12312 osize += 2; break;
12313 default:
12314 /* Fast-path ASCII */
12315 if (ch < ' ' || ch == 0x7f)
12316 osize += 4; /* \xHH */
12317 else if (ch < 0x7f)
12318 osize++;
12319 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12320 osize++;
12321 max = ch > max ? ch : max;
12322 }
12323 else if (ch < 0x100)
12324 osize += 4; /* \xHH */
12325 else if (ch < 0x10000)
12326 osize += 6; /* \uHHHH */
12327 else
12328 osize += 10; /* \uHHHHHHHH */
12329 }
12330 }
12331
12332 quote = '\'';
12333 if (squote) {
12334 if (dquote)
12335 /* Both squote and dquote present. Use squote,
12336 and escape them */
12337 osize += squote;
12338 else
12339 quote = '"';
12340 }
12341
12342 repr = PyUnicode_New(osize, max);
12343 if (repr == NULL)
12344 return NULL;
12345 okind = PyUnicode_KIND(repr);
12346 odata = PyUnicode_DATA(repr);
12347
12348 PyUnicode_WRITE(okind, odata, 0, quote);
12349 PyUnicode_WRITE(okind, odata, osize-1, quote);
12350
12351 for (i = 0, o = 1; i < isize; i++) {
12352 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012353
12354 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355 if ((ch == quote) || (ch == '\\')) {
12356 PyUnicode_WRITE(okind, odata, o++, '\\');
12357 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012358 continue;
12359 }
12360
Benjamin Peterson29060642009-01-31 22:14:21 +000012361 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012362 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012363 PyUnicode_WRITE(okind, odata, o++, '\\');
12364 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012365 }
12366 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012367 PyUnicode_WRITE(okind, odata, o++, '\\');
12368 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012369 }
12370 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012371 PyUnicode_WRITE(okind, odata, o++, '\\');
12372 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012373 }
12374
12375 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012376 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012377 PyUnicode_WRITE(okind, odata, o++, '\\');
12378 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012379 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12380 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012381 }
12382
Georg Brandl559e5d72008-06-11 18:37:52 +000012383 /* Copy ASCII characters as-is */
12384 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012385 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012386 }
12387
Benjamin Peterson29060642009-01-31 22:14:21 +000012388 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012389 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012390 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012391 (categories Z* and C* except ASCII space)
12392 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012393 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012394 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012395 if (ch <= 0xff) {
12396 PyUnicode_WRITE(okind, odata, o++, '\\');
12397 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012398 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12399 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012400 }
12401 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012402 else if (ch >= 0x10000) {
12403 PyUnicode_WRITE(okind, odata, o++, '\\');
12404 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012405 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12406 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12407 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12408 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12409 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12410 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12411 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12412 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012413 }
12414 /* Map 16-bit characters to '\uxxxx' */
12415 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012416 PyUnicode_WRITE(okind, odata, o++, '\\');
12417 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012418 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12419 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12420 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12421 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012422 }
12423 }
12424 /* Copy characters as-is */
12425 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012426 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012427 }
12428 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012429 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012430 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012431 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012432 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012433}
12434
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012435PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012436 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012437\n\
12438Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012439such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012440arguments start and end are interpreted as in slice notation.\n\
12441\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012442Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012443
12444static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012445unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012446{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012447 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012448 Py_ssize_t start;
12449 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012450 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012451
Jesus Ceaac451502011-04-20 17:09:23 +020012452 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12453 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012454 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012455
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012456 if (PyUnicode_READY(self) == -1)
12457 return NULL;
12458 if (PyUnicode_READY(substring) == -1)
12459 return NULL;
12460
Victor Stinner7931d9a2011-11-04 00:22:48 +010012461 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012462
12463 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012464
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012465 if (result == -2)
12466 return NULL;
12467
Christian Heimes217cfd12007-12-02 14:31:20 +000012468 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012469}
12470
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012471PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012472 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012473\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012474Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012475
12476static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012477unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012478{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012479 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012480 Py_ssize_t start;
12481 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012482 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012483
Jesus Ceaac451502011-04-20 17:09:23 +020012484 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12485 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012486 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012487
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012488 if (PyUnicode_READY(self) == -1)
12489 return NULL;
12490 if (PyUnicode_READY(substring) == -1)
12491 return NULL;
12492
Victor Stinner7931d9a2011-11-04 00:22:48 +010012493 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012494
12495 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012496
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012497 if (result == -2)
12498 return NULL;
12499
Guido van Rossumd57fd912000-03-10 22:53:23 +000012500 if (result < 0) {
12501 PyErr_SetString(PyExc_ValueError, "substring not found");
12502 return NULL;
12503 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012504
Christian Heimes217cfd12007-12-02 14:31:20 +000012505 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012506}
12507
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012508PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012509 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012510\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012511Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012512done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012513
12514static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012515unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012516{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012517 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012518 Py_UCS4 fillchar = ' ';
12519
Victor Stinnere9a29352011-10-01 02:14:59 +020012520 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012521 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012522
Benjamin Petersonbac79492012-01-14 13:34:47 -050012523 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012524 return NULL;
12525
Victor Stinnerc4b49542011-12-11 22:44:26 +010012526 if (PyUnicode_GET_LENGTH(self) >= width)
12527 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012528
Victor Stinnerc4b49542011-12-11 22:44:26 +010012529 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012530}
12531
Alexander Belopolsky40018472011-02-26 01:02:56 +000012532PyObject *
12533PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012534{
12535 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012536
Guido van Rossumd57fd912000-03-10 22:53:23 +000012537 s = PyUnicode_FromObject(s);
12538 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012539 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012540 if (sep != NULL) {
12541 sep = PyUnicode_FromObject(sep);
12542 if (sep == NULL) {
12543 Py_DECREF(s);
12544 return NULL;
12545 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012546 }
12547
Victor Stinner9310abb2011-10-05 00:59:23 +020012548 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012549
12550 Py_DECREF(s);
12551 Py_XDECREF(sep);
12552 return result;
12553}
12554
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012555PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012556 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012557\n\
12558Return a list of the words in S, using sep as the\n\
12559delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012560splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012561whitespace string is a separator and empty strings are\n\
12562removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012563
12564static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012565unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012566{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012567 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012568 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012569 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012570
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012571 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12572 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012573 return NULL;
12574
12575 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012576 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012577 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012578 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012579 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012580 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012581}
12582
Thomas Wouters477c8d52006-05-27 19:21:47 +000012583PyObject *
12584PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12585{
12586 PyObject* str_obj;
12587 PyObject* sep_obj;
12588 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012589 int kind1, kind2, kind;
12590 void *buf1 = NULL, *buf2 = NULL;
12591 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012592
12593 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012594 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012595 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012596 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012597 if (!sep_obj) {
12598 Py_DECREF(str_obj);
12599 return NULL;
12600 }
12601 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12602 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012603 Py_DECREF(str_obj);
12604 return NULL;
12605 }
12606
Victor Stinner14f8f022011-10-05 20:58:25 +020012607 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012608 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012609 kind = Py_MAX(kind1, kind2);
12610 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012611 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012612 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012613 if (!buf1)
12614 goto onError;
12615 buf2 = PyUnicode_DATA(sep_obj);
12616 if (kind2 != kind)
12617 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12618 if (!buf2)
12619 goto onError;
12620 len1 = PyUnicode_GET_LENGTH(str_obj);
12621 len2 = PyUnicode_GET_LENGTH(sep_obj);
12622
Benjamin Petersonead6b532011-12-20 17:23:42 -060012623 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012624 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012625 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12626 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12627 else
12628 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012629 break;
12630 case PyUnicode_2BYTE_KIND:
12631 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12632 break;
12633 case PyUnicode_4BYTE_KIND:
12634 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12635 break;
12636 default:
12637 assert(0);
12638 out = 0;
12639 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012640
12641 Py_DECREF(sep_obj);
12642 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012643 if (kind1 != kind)
12644 PyMem_Free(buf1);
12645 if (kind2 != kind)
12646 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012647
12648 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012649 onError:
12650 Py_DECREF(sep_obj);
12651 Py_DECREF(str_obj);
12652 if (kind1 != kind && buf1)
12653 PyMem_Free(buf1);
12654 if (kind2 != kind && buf2)
12655 PyMem_Free(buf2);
12656 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012657}
12658
12659
12660PyObject *
12661PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12662{
12663 PyObject* str_obj;
12664 PyObject* sep_obj;
12665 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012666 int kind1, kind2, kind;
12667 void *buf1 = NULL, *buf2 = NULL;
12668 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012669
12670 str_obj = PyUnicode_FromObject(str_in);
12671 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012672 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012673 sep_obj = PyUnicode_FromObject(sep_in);
12674 if (!sep_obj) {
12675 Py_DECREF(str_obj);
12676 return NULL;
12677 }
12678
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012679 kind1 = PyUnicode_KIND(str_in);
12680 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012681 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012682 buf1 = PyUnicode_DATA(str_in);
12683 if (kind1 != kind)
12684 buf1 = _PyUnicode_AsKind(str_in, kind);
12685 if (!buf1)
12686 goto onError;
12687 buf2 = PyUnicode_DATA(sep_obj);
12688 if (kind2 != kind)
12689 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12690 if (!buf2)
12691 goto onError;
12692 len1 = PyUnicode_GET_LENGTH(str_obj);
12693 len2 = PyUnicode_GET_LENGTH(sep_obj);
12694
Benjamin Petersonead6b532011-12-20 17:23:42 -060012695 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012696 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012697 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12698 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12699 else
12700 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012701 break;
12702 case PyUnicode_2BYTE_KIND:
12703 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12704 break;
12705 case PyUnicode_4BYTE_KIND:
12706 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12707 break;
12708 default:
12709 assert(0);
12710 out = 0;
12711 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012712
12713 Py_DECREF(sep_obj);
12714 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012715 if (kind1 != kind)
12716 PyMem_Free(buf1);
12717 if (kind2 != kind)
12718 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012719
12720 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012721 onError:
12722 Py_DECREF(sep_obj);
12723 Py_DECREF(str_obj);
12724 if (kind1 != kind && buf1)
12725 PyMem_Free(buf1);
12726 if (kind2 != kind && buf2)
12727 PyMem_Free(buf2);
12728 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012729}
12730
12731PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012732 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012733\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012734Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012735the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012736found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012737
12738static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012739unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012740{
Victor Stinner9310abb2011-10-05 00:59:23 +020012741 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012742}
12743
12744PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012745 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012746\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012747Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012748the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012749separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012750
12751static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012752unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012753{
Victor Stinner9310abb2011-10-05 00:59:23 +020012754 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012755}
12756
Alexander Belopolsky40018472011-02-26 01:02:56 +000012757PyObject *
12758PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012759{
12760 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012761
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012762 s = PyUnicode_FromObject(s);
12763 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012764 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012765 if (sep != NULL) {
12766 sep = PyUnicode_FromObject(sep);
12767 if (sep == NULL) {
12768 Py_DECREF(s);
12769 return NULL;
12770 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012771 }
12772
Victor Stinner9310abb2011-10-05 00:59:23 +020012773 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012774
12775 Py_DECREF(s);
12776 Py_XDECREF(sep);
12777 return result;
12778}
12779
12780PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012781 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012782\n\
12783Return a list of the words in S, using sep as the\n\
12784delimiter string, starting at the end of the string and\n\
12785working to the front. If maxsplit is given, at most maxsplit\n\
12786splits are done. If sep is not specified, any whitespace string\n\
12787is a separator.");
12788
12789static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012790unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012791{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012792 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012793 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012794 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012795
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012796 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12797 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012798 return NULL;
12799
12800 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012801 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012802 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012803 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012804 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012805 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012806}
12807
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012808PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012809 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012810\n\
12811Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012812Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012813is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012814
12815static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012816unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012817{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012818 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012819 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012820
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012821 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12822 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012823 return NULL;
12824
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012825 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012826}
12827
12828static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012829PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012830{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012831 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012832}
12833
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012834PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012835 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012836\n\
12837Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012838and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012839
12840static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012841unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012842{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012843 if (PyUnicode_READY(self) == -1)
12844 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012845 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012846}
12847
Georg Brandlceee0772007-11-27 23:48:05 +000012848PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012849 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012850\n\
12851Return a translation table usable for str.translate().\n\
12852If there is only one argument, it must be a dictionary mapping Unicode\n\
12853ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012854Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012855If there are two arguments, they must be strings of equal length, and\n\
12856in the resulting dictionary, each character in x will be mapped to the\n\
12857character at the same position in y. If there is a third argument, it\n\
12858must be a string, whose characters will be mapped to None in the result.");
12859
12860static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012861unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012862{
12863 PyObject *x, *y = NULL, *z = NULL;
12864 PyObject *new = NULL, *key, *value;
12865 Py_ssize_t i = 0;
12866 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012867
Georg Brandlceee0772007-11-27 23:48:05 +000012868 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12869 return NULL;
12870 new = PyDict_New();
12871 if (!new)
12872 return NULL;
12873 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012874 int x_kind, y_kind, z_kind;
12875 void *x_data, *y_data, *z_data;
12876
Georg Brandlceee0772007-11-27 23:48:05 +000012877 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012878 if (!PyUnicode_Check(x)) {
12879 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12880 "be a string if there is a second argument");
12881 goto err;
12882 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012883 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012884 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12885 "arguments must have equal length");
12886 goto err;
12887 }
12888 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012889 x_kind = PyUnicode_KIND(x);
12890 y_kind = PyUnicode_KIND(y);
12891 x_data = PyUnicode_DATA(x);
12892 y_data = PyUnicode_DATA(y);
12893 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12894 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012895 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012896 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012897 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012898 if (!value) {
12899 Py_DECREF(key);
12900 goto err;
12901 }
Georg Brandlceee0772007-11-27 23:48:05 +000012902 res = PyDict_SetItem(new, key, value);
12903 Py_DECREF(key);
12904 Py_DECREF(value);
12905 if (res < 0)
12906 goto err;
12907 }
12908 /* create entries for deleting chars in z */
12909 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012910 z_kind = PyUnicode_KIND(z);
12911 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012912 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012913 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012914 if (!key)
12915 goto err;
12916 res = PyDict_SetItem(new, key, Py_None);
12917 Py_DECREF(key);
12918 if (res < 0)
12919 goto err;
12920 }
12921 }
12922 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012923 int kind;
12924 void *data;
12925
Georg Brandlceee0772007-11-27 23:48:05 +000012926 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012927 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012928 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12929 "to maketrans it must be a dict");
12930 goto err;
12931 }
12932 /* copy entries into the new dict, converting string keys to int keys */
12933 while (PyDict_Next(x, &i, &key, &value)) {
12934 if (PyUnicode_Check(key)) {
12935 /* convert string keys to integer keys */
12936 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012937 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012938 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12939 "table must be of length 1");
12940 goto err;
12941 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012942 kind = PyUnicode_KIND(key);
12943 data = PyUnicode_DATA(key);
12944 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012945 if (!newkey)
12946 goto err;
12947 res = PyDict_SetItem(new, newkey, value);
12948 Py_DECREF(newkey);
12949 if (res < 0)
12950 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012951 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012952 /* just keep integer keys */
12953 if (PyDict_SetItem(new, key, value) < 0)
12954 goto err;
12955 } else {
12956 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12957 "be strings or integers");
12958 goto err;
12959 }
12960 }
12961 }
12962 return new;
12963 err:
12964 Py_DECREF(new);
12965 return NULL;
12966}
12967
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012968PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012969 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012970\n\
12971Return a copy of the string S, where all characters have been mapped\n\
12972through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012973Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012974Unmapped characters are left untouched. Characters mapped to None\n\
12975are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012976
12977static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012978unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012979{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012980 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012981}
12982
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012983PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012984 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012985\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012986Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012987
12988static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012989unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012990{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012991 if (PyUnicode_READY(self) == -1)
12992 return NULL;
12993 if (PyUnicode_IS_ASCII(self))
12994 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012995 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012996}
12997
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012998PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012999 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013000\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013001Pad a numeric string S with zeros on the left, to fill a field\n\
13002of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013003
13004static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013005unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013006{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013007 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013008 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013009 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013010 int kind;
13011 void *data;
13012 Py_UCS4 chr;
13013
Martin v. Löwis18e16552006-02-15 17:27:45 +000013014 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013015 return NULL;
13016
Benjamin Petersonbac79492012-01-14 13:34:47 -050013017 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013018 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013019
Victor Stinnerc4b49542011-12-11 22:44:26 +010013020 if (PyUnicode_GET_LENGTH(self) >= width)
13021 return unicode_result_unchanged(self);
13022
13023 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013024
13025 u = pad(self, fill, 0, '0');
13026
Walter Dörwald068325e2002-04-15 13:36:47 +000013027 if (u == NULL)
13028 return NULL;
13029
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013030 kind = PyUnicode_KIND(u);
13031 data = PyUnicode_DATA(u);
13032 chr = PyUnicode_READ(kind, data, fill);
13033
13034 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013035 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013036 PyUnicode_WRITE(kind, data, 0, chr);
13037 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013038 }
13039
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013040 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013041 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013042}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013043
13044#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013045static PyObject *
13046unicode__decimal2ascii(PyObject *self)
13047{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013048 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013049}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013050#endif
13051
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013052PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013053 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013054\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013055Return True if S starts with the specified prefix, False otherwise.\n\
13056With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013057With optional end, stop comparing S at that position.\n\
13058prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013059
13060static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013061unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013062 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013063{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013064 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013065 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013066 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013067 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013068 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013069
Jesus Ceaac451502011-04-20 17:09:23 +020013070 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013071 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013072 if (PyTuple_Check(subobj)) {
13073 Py_ssize_t i;
13074 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013075 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013076 if (substring == NULL)
13077 return NULL;
13078 result = tailmatch(self, substring, start, end, -1);
13079 Py_DECREF(substring);
13080 if (result) {
13081 Py_RETURN_TRUE;
13082 }
13083 }
13084 /* nothing matched */
13085 Py_RETURN_FALSE;
13086 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013087 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013088 if (substring == NULL) {
13089 if (PyErr_ExceptionMatches(PyExc_TypeError))
13090 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13091 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013092 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013093 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013094 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013095 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013096 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013097}
13098
13099
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013100PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013101 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013102\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013103Return True if S ends with the specified suffix, False otherwise.\n\
13104With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013105With optional end, stop comparing S at that position.\n\
13106suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013107
13108static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013109unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013110 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013111{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013112 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013113 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013114 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013115 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013116 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013117
Jesus Ceaac451502011-04-20 17:09:23 +020013118 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013119 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013120 if (PyTuple_Check(subobj)) {
13121 Py_ssize_t i;
13122 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013123 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013124 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013125 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013126 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013127 result = tailmatch(self, substring, start, end, +1);
13128 Py_DECREF(substring);
13129 if (result) {
13130 Py_RETURN_TRUE;
13131 }
13132 }
13133 Py_RETURN_FALSE;
13134 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013135 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013136 if (substring == NULL) {
13137 if (PyErr_ExceptionMatches(PyExc_TypeError))
13138 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13139 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013140 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013141 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013142 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013143 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013144 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013145}
13146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013147#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013148
13149PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013150 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013151\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013152Return a formatted version of S, using substitutions from args and kwargs.\n\
13153The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013154
Eric Smith27bbca62010-11-04 17:06:58 +000013155PyDoc_STRVAR(format_map__doc__,
13156 "S.format_map(mapping) -> str\n\
13157\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013158Return a formatted version of S, using substitutions from mapping.\n\
13159The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013160
Eric Smith4a7d76d2008-05-30 18:10:19 +000013161static PyObject *
13162unicode__format__(PyObject* self, PyObject* args)
13163{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013164 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013165
13166 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13167 return NULL;
13168
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013169 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013170 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013171 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013172}
13173
Eric Smith8c663262007-08-25 02:26:07 +000013174PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013175 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013176\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013177Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013178
13179static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013180unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013181{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013182 Py_ssize_t size;
13183
13184 /* If it's a compact object, account for base structure +
13185 character data. */
13186 if (PyUnicode_IS_COMPACT_ASCII(v))
13187 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13188 else if (PyUnicode_IS_COMPACT(v))
13189 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013190 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013191 else {
13192 /* If it is a two-block object, account for base object, and
13193 for character block if present. */
13194 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013195 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013196 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013197 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013198 }
13199 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013200 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013201 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013202 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013203 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013204 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013205
13206 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013207}
13208
13209PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013210 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013211
13212static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013213unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013214{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013215 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013216 if (!copy)
13217 return NULL;
13218 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013219}
13220
Guido van Rossumd57fd912000-03-10 22:53:23 +000013221static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013222 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013223 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013224 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13225 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013226 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13227 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013228 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013229 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13230 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13231 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13232 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13233 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013234 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013235 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13236 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13237 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013238 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013239 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13240 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13241 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013242 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013243 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013244 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013245 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013246 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13247 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13248 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13249 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13250 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13251 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13252 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13253 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13254 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13255 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13256 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13257 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13258 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13259 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013260 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013261 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013262 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013263 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013264 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013265 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013266 {"maketrans", (PyCFunction) unicode_maketrans,
13267 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013268 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013269#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013270 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013271 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013272#endif
13273
Benjamin Peterson14339b62009-01-31 16:36:08 +000013274 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013275 {NULL, NULL}
13276};
13277
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013278static PyObject *
13279unicode_mod(PyObject *v, PyObject *w)
13280{
Brian Curtindfc80e32011-08-10 20:28:54 -050013281 if (!PyUnicode_Check(v))
13282 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013283 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013284}
13285
13286static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013287 0, /*nb_add*/
13288 0, /*nb_subtract*/
13289 0, /*nb_multiply*/
13290 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013291};
13292
Guido van Rossumd57fd912000-03-10 22:53:23 +000013293static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013294 (lenfunc) unicode_length, /* sq_length */
13295 PyUnicode_Concat, /* sq_concat */
13296 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13297 (ssizeargfunc) unicode_getitem, /* sq_item */
13298 0, /* sq_slice */
13299 0, /* sq_ass_item */
13300 0, /* sq_ass_slice */
13301 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013302};
13303
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013304static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013305unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013306{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013307 if (PyUnicode_READY(self) == -1)
13308 return NULL;
13309
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013310 if (PyIndex_Check(item)) {
13311 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013312 if (i == -1 && PyErr_Occurred())
13313 return NULL;
13314 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013315 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013316 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013317 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013318 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013319 PyObject *result;
13320 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013321 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013322 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013323
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013324 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013325 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013326 return NULL;
13327 }
13328
13329 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013330 Py_INCREF(unicode_empty);
13331 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013332 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013333 slicelength == PyUnicode_GET_LENGTH(self)) {
13334 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013335 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013336 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013337 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013338 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013339 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013340 src_kind = PyUnicode_KIND(self);
13341 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013342 if (!PyUnicode_IS_ASCII(self)) {
13343 kind_limit = kind_maxchar_limit(src_kind);
13344 max_char = 0;
13345 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13346 ch = PyUnicode_READ(src_kind, src_data, cur);
13347 if (ch > max_char) {
13348 max_char = ch;
13349 if (max_char >= kind_limit)
13350 break;
13351 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013352 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013353 }
Victor Stinner55c99112011-10-13 01:17:06 +020013354 else
13355 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013356 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013357 if (result == NULL)
13358 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013359 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013360 dest_data = PyUnicode_DATA(result);
13361
13362 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013363 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13364 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013365 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013366 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013367 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013368 } else {
13369 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13370 return NULL;
13371 }
13372}
13373
13374static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013375 (lenfunc)unicode_length, /* mp_length */
13376 (binaryfunc)unicode_subscript, /* mp_subscript */
13377 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013378};
13379
Guido van Rossumd57fd912000-03-10 22:53:23 +000013380
Guido van Rossumd57fd912000-03-10 22:53:23 +000013381/* Helpers for PyUnicode_Format() */
13382
13383static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013384getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013385{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013386 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013387 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013388 (*p_argidx)++;
13389 if (arglen < 0)
13390 return args;
13391 else
13392 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013393 }
13394 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013395 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013396 return NULL;
13397}
13398
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013399/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013400
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013401static PyObject *
13402formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013403{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013404 char *p;
13405 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013406 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013407
Guido van Rossumd57fd912000-03-10 22:53:23 +000013408 x = PyFloat_AsDouble(v);
13409 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013410 return NULL;
13411
Guido van Rossumd57fd912000-03-10 22:53:23 +000013412 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013413 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013414
Eric Smith0923d1d2009-04-16 20:16:10 +000013415 p = PyOS_double_to_string(x, type, prec,
13416 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013417 if (p == NULL)
13418 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013419 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013420 PyMem_Free(p);
13421 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013422}
13423
Tim Peters38fd5b62000-09-21 05:43:11 +000013424static PyObject*
13425formatlong(PyObject *val, int flags, int prec, int type)
13426{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013427 char *buf;
13428 int len;
13429 PyObject *str; /* temporary string object. */
13430 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013431
Benjamin Peterson14339b62009-01-31 16:36:08 +000013432 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13433 if (!str)
13434 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013435 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013436 Py_DECREF(str);
13437 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013438}
13439
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013440static Py_UCS4
13441formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013442{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013443 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013444 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013445 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013446 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013447 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013448 goto onError;
13449 }
13450 else {
13451 /* Integer input truncated to a character */
13452 long x;
13453 x = PyLong_AsLong(v);
13454 if (x == -1 && PyErr_Occurred())
13455 goto onError;
13456
Victor Stinner8faf8212011-12-08 22:14:11 +010013457 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013458 PyErr_SetString(PyExc_OverflowError,
13459 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013460 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013461 }
13462
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013463 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013464 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013465
Benjamin Peterson29060642009-01-31 22:14:21 +000013466 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013467 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013468 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013469 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013470}
13471
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013472static int
13473repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13474{
13475 int r;
13476 assert(count > 0);
13477 assert(PyUnicode_Check(obj));
13478 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013479 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013480 if (repeated == NULL)
13481 return -1;
13482 r = _PyAccu_Accumulate(acc, repeated);
13483 Py_DECREF(repeated);
13484 return r;
13485 }
13486 else {
13487 do {
13488 if (_PyAccu_Accumulate(acc, obj))
13489 return -1;
13490 } while (--count);
13491 return 0;
13492 }
13493}
13494
Alexander Belopolsky40018472011-02-26 01:02:56 +000013495PyObject *
13496PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013497{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013498 void *fmt;
13499 int fmtkind;
13500 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013501 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013502 int r;
13503 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013504 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013505 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013506 PyObject *temp = NULL;
13507 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013508 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013509 _PyAccu acc;
13510 static PyObject *plus, *minus, *blank, *zero, *percent;
13511
13512 if (!plus && !(plus = get_latin1_char('+')))
13513 return NULL;
13514 if (!minus && !(minus = get_latin1_char('-')))
13515 return NULL;
13516 if (!blank && !(blank = get_latin1_char(' ')))
13517 return NULL;
13518 if (!zero && !(zero = get_latin1_char('0')))
13519 return NULL;
13520 if (!percent && !(percent = get_latin1_char('%')))
13521 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013522
Guido van Rossumd57fd912000-03-10 22:53:23 +000013523 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013524 PyErr_BadInternalCall();
13525 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013526 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013527 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013528 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013529 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013530 if (PyUnicode_READY(uformat) == -1)
13531 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013532 if (_PyAccu_Init(&acc))
13533 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013534 fmt = PyUnicode_DATA(uformat);
13535 fmtkind = PyUnicode_KIND(uformat);
13536 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13537 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013538
Guido van Rossumd57fd912000-03-10 22:53:23 +000013539 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013540 arglen = PyTuple_Size(args);
13541 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013542 }
13543 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013544 arglen = -1;
13545 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013546 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013547 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013548 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013549 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013550
13551 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013552 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013553 PyObject *nonfmt;
13554 Py_ssize_t nonfmtpos;
13555 nonfmtpos = fmtpos++;
13556 while (fmtcnt >= 0 &&
13557 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13558 fmtpos++;
13559 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013560 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013561 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013562 if (nonfmt == NULL)
13563 goto onError;
13564 r = _PyAccu_Accumulate(&acc, nonfmt);
13565 Py_DECREF(nonfmt);
13566 if (r)
13567 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013568 }
13569 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013570 /* Got a format specifier */
13571 int flags = 0;
13572 Py_ssize_t width = -1;
13573 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013574 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013575 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013576 int isnumok;
13577 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013578 void *pbuf = NULL;
13579 Py_ssize_t pindex, len;
13580 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013581
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013582 fmtpos++;
13583 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13584 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013585 Py_ssize_t keylen;
13586 PyObject *key;
13587 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013588
Benjamin Peterson29060642009-01-31 22:14:21 +000013589 if (dict == NULL) {
13590 PyErr_SetString(PyExc_TypeError,
13591 "format requires a mapping");
13592 goto onError;
13593 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013594 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013595 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013596 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013597 /* Skip over balanced parentheses */
13598 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013599 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013600 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013601 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013602 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013603 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013604 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013605 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013606 if (fmtcnt < 0 || pcount > 0) {
13607 PyErr_SetString(PyExc_ValueError,
13608 "incomplete format key");
13609 goto onError;
13610 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013611 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013612 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013613 if (key == NULL)
13614 goto onError;
13615 if (args_owned) {
13616 Py_DECREF(args);
13617 args_owned = 0;
13618 }
13619 args = PyObject_GetItem(dict, key);
13620 Py_DECREF(key);
13621 if (args == NULL) {
13622 goto onError;
13623 }
13624 args_owned = 1;
13625 arglen = -1;
13626 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013627 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013628 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013629 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013630 case '-': flags |= F_LJUST; continue;
13631 case '+': flags |= F_SIGN; continue;
13632 case ' ': flags |= F_BLANK; continue;
13633 case '#': flags |= F_ALT; continue;
13634 case '0': flags |= F_ZERO; continue;
13635 }
13636 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013637 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013638 if (c == '*') {
13639 v = getnextarg(args, arglen, &argidx);
13640 if (v == NULL)
13641 goto onError;
13642 if (!PyLong_Check(v)) {
13643 PyErr_SetString(PyExc_TypeError,
13644 "* wants int");
13645 goto onError;
13646 }
13647 width = PyLong_AsLong(v);
13648 if (width == -1 && PyErr_Occurred())
13649 goto onError;
13650 if (width < 0) {
13651 flags |= F_LJUST;
13652 width = -width;
13653 }
13654 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013655 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013656 }
13657 else if (c >= '0' && c <= '9') {
13658 width = c - '0';
13659 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013660 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013661 if (c < '0' || c > '9')
13662 break;
13663 if ((width*10) / 10 != width) {
13664 PyErr_SetString(PyExc_ValueError,
13665 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013666 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013667 }
13668 width = width*10 + (c - '0');
13669 }
13670 }
13671 if (c == '.') {
13672 prec = 0;
13673 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013674 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013675 if (c == '*') {
13676 v = getnextarg(args, arglen, &argidx);
13677 if (v == NULL)
13678 goto onError;
13679 if (!PyLong_Check(v)) {
13680 PyErr_SetString(PyExc_TypeError,
13681 "* wants int");
13682 goto onError;
13683 }
13684 prec = PyLong_AsLong(v);
13685 if (prec == -1 && PyErr_Occurred())
13686 goto onError;
13687 if (prec < 0)
13688 prec = 0;
13689 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013690 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013691 }
13692 else if (c >= '0' && c <= '9') {
13693 prec = c - '0';
13694 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013695 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013696 if (c < '0' || c > '9')
13697 break;
13698 if ((prec*10) / 10 != prec) {
13699 PyErr_SetString(PyExc_ValueError,
13700 "prec too big");
13701 goto onError;
13702 }
13703 prec = prec*10 + (c - '0');
13704 }
13705 }
13706 } /* prec */
13707 if (fmtcnt >= 0) {
13708 if (c == 'h' || c == 'l' || c == 'L') {
13709 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013710 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013711 }
13712 }
13713 if (fmtcnt < 0) {
13714 PyErr_SetString(PyExc_ValueError,
13715 "incomplete format");
13716 goto onError;
13717 }
13718 if (c != '%') {
13719 v = getnextarg(args, arglen, &argidx);
13720 if (v == NULL)
13721 goto onError;
13722 }
13723 sign = 0;
13724 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013725 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013726 switch (c) {
13727
13728 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013729 _PyAccu_Accumulate(&acc, percent);
13730 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013731
13732 case 's':
13733 case 'r':
13734 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013735 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013736 temp = v;
13737 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013738 }
13739 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013740 if (c == 's')
13741 temp = PyObject_Str(v);
13742 else if (c == 'r')
13743 temp = PyObject_Repr(v);
13744 else
13745 temp = PyObject_ASCII(v);
13746 if (temp == NULL)
13747 goto onError;
13748 if (PyUnicode_Check(temp))
13749 /* nothing to do */;
13750 else {
13751 Py_DECREF(temp);
13752 PyErr_SetString(PyExc_TypeError,
13753 "%s argument has non-string str()");
13754 goto onError;
13755 }
13756 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013757 if (PyUnicode_READY(temp) == -1) {
13758 Py_CLEAR(temp);
13759 goto onError;
13760 }
13761 pbuf = PyUnicode_DATA(temp);
13762 kind = PyUnicode_KIND(temp);
13763 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013764 if (prec >= 0 && len > prec)
13765 len = prec;
13766 break;
13767
13768 case 'i':
13769 case 'd':
13770 case 'u':
13771 case 'o':
13772 case 'x':
13773 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013774 isnumok = 0;
13775 if (PyNumber_Check(v)) {
13776 PyObject *iobj=NULL;
13777
13778 if (PyLong_Check(v)) {
13779 iobj = v;
13780 Py_INCREF(iobj);
13781 }
13782 else {
13783 iobj = PyNumber_Long(v);
13784 }
13785 if (iobj!=NULL) {
13786 if (PyLong_Check(iobj)) {
13787 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013788 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013789 Py_DECREF(iobj);
13790 if (!temp)
13791 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013792 if (PyUnicode_READY(temp) == -1) {
13793 Py_CLEAR(temp);
13794 goto onError;
13795 }
13796 pbuf = PyUnicode_DATA(temp);
13797 kind = PyUnicode_KIND(temp);
13798 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013799 sign = 1;
13800 }
13801 else {
13802 Py_DECREF(iobj);
13803 }
13804 }
13805 }
13806 if (!isnumok) {
13807 PyErr_Format(PyExc_TypeError,
13808 "%%%c format: a number is required, "
13809 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13810 goto onError;
13811 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013812 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013813 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013814 fillobj = zero;
13815 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013816 break;
13817
13818 case 'e':
13819 case 'E':
13820 case 'f':
13821 case 'F':
13822 case 'g':
13823 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013824 temp = formatfloat(v, flags, prec, c);
13825 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013826 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013827 if (PyUnicode_READY(temp) == -1) {
13828 Py_CLEAR(temp);
13829 goto onError;
13830 }
13831 pbuf = PyUnicode_DATA(temp);
13832 kind = PyUnicode_KIND(temp);
13833 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013834 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013835 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013836 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013837 fillobj = zero;
13838 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013839 break;
13840
13841 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013842 {
13843 Py_UCS4 ch = formatchar(v);
13844 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013845 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013846 temp = _PyUnicode_FromUCS4(&ch, 1);
13847 if (temp == NULL)
13848 goto onError;
13849 pbuf = PyUnicode_DATA(temp);
13850 kind = PyUnicode_KIND(temp);
13851 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013852 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013853 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013854
13855 default:
13856 PyErr_Format(PyExc_ValueError,
13857 "unsupported format character '%c' (0x%x) "
13858 "at index %zd",
13859 (31<=c && c<=126) ? (char)c : '?',
13860 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013861 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013862 goto onError;
13863 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013864 /* pbuf is initialized here. */
13865 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013866 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013867 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13868 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013869 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013870 pindex++;
13871 }
13872 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13873 signobj = plus;
13874 len--;
13875 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013876 }
13877 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013878 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013879 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013880 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013881 else
13882 sign = 0;
13883 }
13884 if (width < len)
13885 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013886 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013887 if (fill != ' ') {
13888 assert(signobj != NULL);
13889 if (_PyAccu_Accumulate(&acc, signobj))
13890 goto onError;
13891 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013892 if (width > len)
13893 width--;
13894 }
13895 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013896 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013897 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013898 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013899 second = get_latin1_char(
13900 PyUnicode_READ(kind, pbuf, pindex + 1));
13901 pindex += 2;
13902 if (second == NULL ||
13903 _PyAccu_Accumulate(&acc, zero) ||
13904 _PyAccu_Accumulate(&acc, second))
13905 goto onError;
13906 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013907 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013908 width -= 2;
13909 if (width < 0)
13910 width = 0;
13911 len -= 2;
13912 }
13913 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013914 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013915 if (repeat_accumulate(&acc, fillobj, width - len))
13916 goto onError;
13917 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013918 }
13919 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013920 if (sign) {
13921 assert(signobj != NULL);
13922 if (_PyAccu_Accumulate(&acc, signobj))
13923 goto onError;
13924 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013925 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013926 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13927 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013928 second = get_latin1_char(
13929 PyUnicode_READ(kind, pbuf, pindex + 1));
13930 pindex += 2;
13931 if (second == NULL ||
13932 _PyAccu_Accumulate(&acc, zero) ||
13933 _PyAccu_Accumulate(&acc, second))
13934 goto onError;
13935 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013936 }
13937 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013938 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013939 if (temp != NULL) {
13940 assert(pbuf == PyUnicode_DATA(temp));
13941 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013942 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013943 else {
13944 const char *p = (const char *) pbuf;
13945 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013946 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013947 v = PyUnicode_FromKindAndData(kind, p, len);
13948 }
13949 if (v == NULL)
13950 goto onError;
13951 r = _PyAccu_Accumulate(&acc, v);
13952 Py_DECREF(v);
13953 if (r)
13954 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013955 if (width > len && repeat_accumulate(&acc, blank, width - len))
13956 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013957 if (dict && (argidx < arglen) && c != '%') {
13958 PyErr_SetString(PyExc_TypeError,
13959 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013960 goto onError;
13961 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013962 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013963 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013964 } /* until end */
13965 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013966 PyErr_SetString(PyExc_TypeError,
13967 "not all arguments converted during string formatting");
13968 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013969 }
13970
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013971 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013972 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013973 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013974 }
13975 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013976 Py_XDECREF(temp);
13977 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013978 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013979
Benjamin Peterson29060642009-01-31 22:14:21 +000013980 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013981 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013982 Py_XDECREF(temp);
13983 Py_XDECREF(second);
13984 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013985 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013986 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013987 }
13988 return NULL;
13989}
13990
Jeremy Hylton938ace62002-07-17 16:30:39 +000013991static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013992unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13993
Tim Peters6d6c1a32001-08-02 04:15:00 +000013994static PyObject *
13995unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13996{
Benjamin Peterson29060642009-01-31 22:14:21 +000013997 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013998 static char *kwlist[] = {"object", "encoding", "errors", 0};
13999 char *encoding = NULL;
14000 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014001
Benjamin Peterson14339b62009-01-31 16:36:08 +000014002 if (type != &PyUnicode_Type)
14003 return unicode_subtype_new(type, args, kwds);
14004 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014005 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014006 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010014007 if (x == NULL) {
14008 Py_INCREF(unicode_empty);
14009 return unicode_empty;
14010 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014011 if (encoding == NULL && errors == NULL)
14012 return PyObject_Str(x);
14013 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014014 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014015}
14016
Guido van Rossume023fe02001-08-30 03:12:59 +000014017static PyObject *
14018unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14019{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014020 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014021 Py_ssize_t length, char_size;
14022 int share_wstr, share_utf8;
14023 unsigned int kind;
14024 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014025
Benjamin Peterson14339b62009-01-31 16:36:08 +000014026 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014027
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014028 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014029 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014030 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014031 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014032 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014033 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014034 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014035 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014036
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014037 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014038 if (self == NULL) {
14039 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014040 return NULL;
14041 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014042 kind = PyUnicode_KIND(unicode);
14043 length = PyUnicode_GET_LENGTH(unicode);
14044
14045 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014046#ifdef Py_DEBUG
14047 _PyUnicode_HASH(self) = -1;
14048#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014049 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014050#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014051 _PyUnicode_STATE(self).interned = 0;
14052 _PyUnicode_STATE(self).kind = kind;
14053 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014054 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014055 _PyUnicode_STATE(self).ready = 1;
14056 _PyUnicode_WSTR(self) = NULL;
14057 _PyUnicode_UTF8_LENGTH(self) = 0;
14058 _PyUnicode_UTF8(self) = NULL;
14059 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014060 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014061
14062 share_utf8 = 0;
14063 share_wstr = 0;
14064 if (kind == PyUnicode_1BYTE_KIND) {
14065 char_size = 1;
14066 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14067 share_utf8 = 1;
14068 }
14069 else if (kind == PyUnicode_2BYTE_KIND) {
14070 char_size = 2;
14071 if (sizeof(wchar_t) == 2)
14072 share_wstr = 1;
14073 }
14074 else {
14075 assert(kind == PyUnicode_4BYTE_KIND);
14076 char_size = 4;
14077 if (sizeof(wchar_t) == 4)
14078 share_wstr = 1;
14079 }
14080
14081 /* Ensure we won't overflow the length. */
14082 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14083 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014084 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014085 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014086 data = PyObject_MALLOC((length + 1) * char_size);
14087 if (data == NULL) {
14088 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014089 goto onError;
14090 }
14091
Victor Stinnerc3c74152011-10-02 20:39:55 +020014092 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014093 if (share_utf8) {
14094 _PyUnicode_UTF8_LENGTH(self) = length;
14095 _PyUnicode_UTF8(self) = data;
14096 }
14097 if (share_wstr) {
14098 _PyUnicode_WSTR_LENGTH(self) = length;
14099 _PyUnicode_WSTR(self) = (wchar_t *)data;
14100 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014101
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014102 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014103 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014104 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014105#ifdef Py_DEBUG
14106 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14107#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014108 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014109 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014110
14111onError:
14112 Py_DECREF(unicode);
14113 Py_DECREF(self);
14114 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014115}
14116
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014117PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000014118 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014119\n\
Collin Winterd474ce82007-08-07 19:42:11 +000014120Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000014121encoding defaults to the current default string encoding.\n\
14122errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014123
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014124static PyObject *unicode_iter(PyObject *seq);
14125
Guido van Rossumd57fd912000-03-10 22:53:23 +000014126PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014127 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014128 "str", /* tp_name */
14129 sizeof(PyUnicodeObject), /* tp_size */
14130 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014131 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014132 (destructor)unicode_dealloc, /* tp_dealloc */
14133 0, /* tp_print */
14134 0, /* tp_getattr */
14135 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014136 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014137 unicode_repr, /* tp_repr */
14138 &unicode_as_number, /* tp_as_number */
14139 &unicode_as_sequence, /* tp_as_sequence */
14140 &unicode_as_mapping, /* tp_as_mapping */
14141 (hashfunc) unicode_hash, /* tp_hash*/
14142 0, /* tp_call*/
14143 (reprfunc) unicode_str, /* tp_str */
14144 PyObject_GenericGetAttr, /* tp_getattro */
14145 0, /* tp_setattro */
14146 0, /* tp_as_buffer */
14147 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014148 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014149 unicode_doc, /* tp_doc */
14150 0, /* tp_traverse */
14151 0, /* tp_clear */
14152 PyUnicode_RichCompare, /* tp_richcompare */
14153 0, /* tp_weaklistoffset */
14154 unicode_iter, /* tp_iter */
14155 0, /* tp_iternext */
14156 unicode_methods, /* tp_methods */
14157 0, /* tp_members */
14158 0, /* tp_getset */
14159 &PyBaseObject_Type, /* tp_base */
14160 0, /* tp_dict */
14161 0, /* tp_descr_get */
14162 0, /* tp_descr_set */
14163 0, /* tp_dictoffset */
14164 0, /* tp_init */
14165 0, /* tp_alloc */
14166 unicode_new, /* tp_new */
14167 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014168};
14169
14170/* Initialize the Unicode implementation */
14171
Victor Stinner3a50e702011-10-18 21:21:00 +020014172int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014173{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014174 int i;
14175
Thomas Wouters477c8d52006-05-27 19:21:47 +000014176 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014177 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014178 0x000A, /* LINE FEED */
14179 0x000D, /* CARRIAGE RETURN */
14180 0x001C, /* FILE SEPARATOR */
14181 0x001D, /* GROUP SEPARATOR */
14182 0x001E, /* RECORD SEPARATOR */
14183 0x0085, /* NEXT LINE */
14184 0x2028, /* LINE SEPARATOR */
14185 0x2029, /* PARAGRAPH SEPARATOR */
14186 };
14187
Fred Drakee4315f52000-05-09 19:53:39 +000014188 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014189 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014190 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014191 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014192 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014193
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014194 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014195 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014196 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014197 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014198
14199 /* initialize the linebreak bloom filter */
14200 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014201 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014202 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014203
14204 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014205
14206#ifdef HAVE_MBCS
14207 winver.dwOSVersionInfoSize = sizeof(winver);
14208 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14209 PyErr_SetFromWindowsErr(0);
14210 return -1;
14211 }
14212#endif
14213 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014214}
14215
14216/* Finalize the Unicode implementation */
14217
Christian Heimesa156e092008-02-16 07:38:31 +000014218int
14219PyUnicode_ClearFreeList(void)
14220{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014221 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014222}
14223
Guido van Rossumd57fd912000-03-10 22:53:23 +000014224void
Thomas Wouters78890102000-07-22 19:25:51 +000014225_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014226{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014227 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014228
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014229 Py_XDECREF(unicode_empty);
14230 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014231
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014232 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014233 if (unicode_latin1[i]) {
14234 Py_DECREF(unicode_latin1[i]);
14235 unicode_latin1[i] = NULL;
14236 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014237 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014238 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014239 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014240}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014241
Walter Dörwald16807132007-05-25 13:52:07 +000014242void
14243PyUnicode_InternInPlace(PyObject **p)
14244{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014245 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014246 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014247#ifdef Py_DEBUG
14248 assert(s != NULL);
14249 assert(_PyUnicode_CHECK(s));
14250#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014251 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014252 return;
14253#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014254 /* If it's a subclass, we don't really know what putting
14255 it in the interned dict might do. */
14256 if (!PyUnicode_CheckExact(s))
14257 return;
14258 if (PyUnicode_CHECK_INTERNED(s))
14259 return;
14260 if (interned == NULL) {
14261 interned = PyDict_New();
14262 if (interned == NULL) {
14263 PyErr_Clear(); /* Don't leave an exception */
14264 return;
14265 }
14266 }
14267 /* It might be that the GetItem call fails even
14268 though the key is present in the dictionary,
14269 namely when this happens during a stack overflow. */
14270 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014271 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014272 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014273
Benjamin Peterson29060642009-01-31 22:14:21 +000014274 if (t) {
14275 Py_INCREF(t);
14276 Py_DECREF(*p);
14277 *p = t;
14278 return;
14279 }
Walter Dörwald16807132007-05-25 13:52:07 +000014280
Benjamin Peterson14339b62009-01-31 16:36:08 +000014281 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014282 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014283 PyErr_Clear();
14284 PyThreadState_GET()->recursion_critical = 0;
14285 return;
14286 }
14287 PyThreadState_GET()->recursion_critical = 0;
14288 /* The two references in interned are not counted by refcnt.
14289 The deallocator will take care of this */
14290 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014291 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014292}
14293
14294void
14295PyUnicode_InternImmortal(PyObject **p)
14296{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014297 PyUnicode_InternInPlace(p);
14298 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014299 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014300 Py_INCREF(*p);
14301 }
Walter Dörwald16807132007-05-25 13:52:07 +000014302}
14303
14304PyObject *
14305PyUnicode_InternFromString(const char *cp)
14306{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014307 PyObject *s = PyUnicode_FromString(cp);
14308 if (s == NULL)
14309 return NULL;
14310 PyUnicode_InternInPlace(&s);
14311 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014312}
14313
Alexander Belopolsky40018472011-02-26 01:02:56 +000014314void
14315_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014316{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014317 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014318 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014319 Py_ssize_t i, n;
14320 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014321
Benjamin Peterson14339b62009-01-31 16:36:08 +000014322 if (interned == NULL || !PyDict_Check(interned))
14323 return;
14324 keys = PyDict_Keys(interned);
14325 if (keys == NULL || !PyList_Check(keys)) {
14326 PyErr_Clear();
14327 return;
14328 }
Walter Dörwald16807132007-05-25 13:52:07 +000014329
Benjamin Peterson14339b62009-01-31 16:36:08 +000014330 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14331 detector, interned unicode strings are not forcibly deallocated;
14332 rather, we give them their stolen references back, and then clear
14333 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014334
Benjamin Peterson14339b62009-01-31 16:36:08 +000014335 n = PyList_GET_SIZE(keys);
14336 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014337 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014338 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014339 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014340 if (PyUnicode_READY(s) == -1) {
14341 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014342 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014343 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014344 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014345 case SSTATE_NOT_INTERNED:
14346 /* XXX Shouldn't happen */
14347 break;
14348 case SSTATE_INTERNED_IMMORTAL:
14349 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014350 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014351 break;
14352 case SSTATE_INTERNED_MORTAL:
14353 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014354 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014355 break;
14356 default:
14357 Py_FatalError("Inconsistent interned string state.");
14358 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014359 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014360 }
14361 fprintf(stderr, "total size of all interned strings: "
14362 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14363 "mortal/immortal\n", mortal_size, immortal_size);
14364 Py_DECREF(keys);
14365 PyDict_Clear(interned);
14366 Py_DECREF(interned);
14367 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014368}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014369
14370
14371/********************* Unicode Iterator **************************/
14372
14373typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014374 PyObject_HEAD
14375 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014376 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014377} unicodeiterobject;
14378
14379static void
14380unicodeiter_dealloc(unicodeiterobject *it)
14381{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014382 _PyObject_GC_UNTRACK(it);
14383 Py_XDECREF(it->it_seq);
14384 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014385}
14386
14387static int
14388unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14389{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014390 Py_VISIT(it->it_seq);
14391 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014392}
14393
14394static PyObject *
14395unicodeiter_next(unicodeiterobject *it)
14396{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014397 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014398
Benjamin Peterson14339b62009-01-31 16:36:08 +000014399 assert(it != NULL);
14400 seq = it->it_seq;
14401 if (seq == NULL)
14402 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014403 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014404
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014405 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14406 int kind = PyUnicode_KIND(seq);
14407 void *data = PyUnicode_DATA(seq);
14408 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14409 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014410 if (item != NULL)
14411 ++it->it_index;
14412 return item;
14413 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014414
Benjamin Peterson14339b62009-01-31 16:36:08 +000014415 Py_DECREF(seq);
14416 it->it_seq = NULL;
14417 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014418}
14419
14420static PyObject *
14421unicodeiter_len(unicodeiterobject *it)
14422{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014423 Py_ssize_t len = 0;
14424 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014425 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014426 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014427}
14428
14429PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14430
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014431static PyObject *
14432unicodeiter_reduce(unicodeiterobject *it)
14433{
14434 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014435 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014436 it->it_seq, it->it_index);
14437 } else {
14438 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14439 if (u == NULL)
14440 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014441 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014442 }
14443}
14444
14445PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14446
14447static PyObject *
14448unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14449{
14450 Py_ssize_t index = PyLong_AsSsize_t(state);
14451 if (index == -1 && PyErr_Occurred())
14452 return NULL;
14453 if (index < 0)
14454 index = 0;
14455 it->it_index = index;
14456 Py_RETURN_NONE;
14457}
14458
14459PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14460
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014461static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014462 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014463 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014464 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14465 reduce_doc},
14466 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14467 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014468 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014469};
14470
14471PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014472 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14473 "str_iterator", /* tp_name */
14474 sizeof(unicodeiterobject), /* tp_basicsize */
14475 0, /* tp_itemsize */
14476 /* methods */
14477 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14478 0, /* tp_print */
14479 0, /* tp_getattr */
14480 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014481 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014482 0, /* tp_repr */
14483 0, /* tp_as_number */
14484 0, /* tp_as_sequence */
14485 0, /* tp_as_mapping */
14486 0, /* tp_hash */
14487 0, /* tp_call */
14488 0, /* tp_str */
14489 PyObject_GenericGetAttr, /* tp_getattro */
14490 0, /* tp_setattro */
14491 0, /* tp_as_buffer */
14492 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14493 0, /* tp_doc */
14494 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14495 0, /* tp_clear */
14496 0, /* tp_richcompare */
14497 0, /* tp_weaklistoffset */
14498 PyObject_SelfIter, /* tp_iter */
14499 (iternextfunc)unicodeiter_next, /* tp_iternext */
14500 unicodeiter_methods, /* tp_methods */
14501 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014502};
14503
14504static PyObject *
14505unicode_iter(PyObject *seq)
14506{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014507 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014508
Benjamin Peterson14339b62009-01-31 16:36:08 +000014509 if (!PyUnicode_Check(seq)) {
14510 PyErr_BadInternalCall();
14511 return NULL;
14512 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014513 if (PyUnicode_READY(seq) == -1)
14514 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014515 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14516 if (it == NULL)
14517 return NULL;
14518 it->it_index = 0;
14519 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014520 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014521 _PyObject_GC_TRACK(it);
14522 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014523}
14524
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014525
14526size_t
14527Py_UNICODE_strlen(const Py_UNICODE *u)
14528{
14529 int res = 0;
14530 while(*u++)
14531 res++;
14532 return res;
14533}
14534
14535Py_UNICODE*
14536Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14537{
14538 Py_UNICODE *u = s1;
14539 while ((*u++ = *s2++));
14540 return s1;
14541}
14542
14543Py_UNICODE*
14544Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14545{
14546 Py_UNICODE *u = s1;
14547 while ((*u++ = *s2++))
14548 if (n-- == 0)
14549 break;
14550 return s1;
14551}
14552
14553Py_UNICODE*
14554Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14555{
14556 Py_UNICODE *u1 = s1;
14557 u1 += Py_UNICODE_strlen(u1);
14558 Py_UNICODE_strcpy(u1, s2);
14559 return s1;
14560}
14561
14562int
14563Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14564{
14565 while (*s1 && *s2 && *s1 == *s2)
14566 s1++, s2++;
14567 if (*s1 && *s2)
14568 return (*s1 < *s2) ? -1 : +1;
14569 if (*s1)
14570 return 1;
14571 if (*s2)
14572 return -1;
14573 return 0;
14574}
14575
14576int
14577Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14578{
14579 register Py_UNICODE u1, u2;
14580 for (; n != 0; n--) {
14581 u1 = *s1;
14582 u2 = *s2;
14583 if (u1 != u2)
14584 return (u1 < u2) ? -1 : +1;
14585 if (u1 == '\0')
14586 return 0;
14587 s1++;
14588 s2++;
14589 }
14590 return 0;
14591}
14592
14593Py_UNICODE*
14594Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14595{
14596 const Py_UNICODE *p;
14597 for (p = s; *p; p++)
14598 if (*p == c)
14599 return (Py_UNICODE*)p;
14600 return NULL;
14601}
14602
14603Py_UNICODE*
14604Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14605{
14606 const Py_UNICODE *p;
14607 p = s + Py_UNICODE_strlen(s);
14608 while (p != s) {
14609 p--;
14610 if (*p == c)
14611 return (Py_UNICODE*)p;
14612 }
14613 return NULL;
14614}
Victor Stinner331ea922010-08-10 16:37:20 +000014615
Victor Stinner71133ff2010-09-01 23:43:53 +000014616Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014617PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014618{
Victor Stinner577db2c2011-10-11 22:12:48 +020014619 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014620 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014621
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014622 if (!PyUnicode_Check(unicode)) {
14623 PyErr_BadArgument();
14624 return NULL;
14625 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014626 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014627 if (u == NULL)
14628 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014629 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014630 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014631 PyErr_NoMemory();
14632 return NULL;
14633 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014634 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014635 size *= sizeof(Py_UNICODE);
14636 copy = PyMem_Malloc(size);
14637 if (copy == NULL) {
14638 PyErr_NoMemory();
14639 return NULL;
14640 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014641 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014642 return copy;
14643}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014644
Georg Brandl66c221e2010-10-14 07:04:07 +000014645/* A _string module, to export formatter_parser and formatter_field_name_split
14646 to the string.Formatter class implemented in Python. */
14647
14648static PyMethodDef _string_methods[] = {
14649 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14650 METH_O, PyDoc_STR("split the argument as a field name")},
14651 {"formatter_parser", (PyCFunction) formatter_parser,
14652 METH_O, PyDoc_STR("parse the argument as a format string")},
14653 {NULL, NULL}
14654};
14655
14656static struct PyModuleDef _string_module = {
14657 PyModuleDef_HEAD_INIT,
14658 "_string",
14659 PyDoc_STR("string helper module"),
14660 0,
14661 _string_methods,
14662 NULL,
14663 NULL,
14664 NULL,
14665 NULL
14666};
14667
14668PyMODINIT_FUNC
14669PyInit__string(void)
14670{
14671 return PyModule_Create(&_string_module);
14672}
14673
14674
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014675#ifdef __cplusplus
14676}
14677#endif