blob: 01748be3e8f8b9eeb79ed5638f074d6382e0dc96 [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 Stinner15e9ed22012-02-22 13:36:20 +01001001 assert(maxchar <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001002 kind_state = PyUnicode_4BYTE_KIND;
1003 char_size = 4;
1004 if (sizeof(wchar_t) == 4)
1005 is_sharing = 1;
1006 }
1007
1008 /* Ensure we won't overflow the size. */
1009 if (size < 0) {
1010 PyErr_SetString(PyExc_SystemError,
1011 "Negative size passed to PyUnicode_New");
1012 return NULL;
1013 }
1014 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1015 return PyErr_NoMemory();
1016
1017 /* Duplicated allocation code from _PyObject_New() instead of a call to
1018 * PyObject_New() so we are able to allocate space for the object and
1019 * it's data buffer.
1020 */
1021 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1022 if (obj == NULL)
1023 return PyErr_NoMemory();
1024 obj = PyObject_INIT(obj, &PyUnicode_Type);
1025 if (obj == NULL)
1026 return NULL;
1027
1028 unicode = (PyCompactUnicodeObject *)obj;
1029 if (is_ascii)
1030 data = ((PyASCIIObject*)obj) + 1;
1031 else
1032 data = unicode + 1;
1033 _PyUnicode_LENGTH(unicode) = size;
1034 _PyUnicode_HASH(unicode) = -1;
1035 _PyUnicode_STATE(unicode).interned = 0;
1036 _PyUnicode_STATE(unicode).kind = kind_state;
1037 _PyUnicode_STATE(unicode).compact = 1;
1038 _PyUnicode_STATE(unicode).ready = 1;
1039 _PyUnicode_STATE(unicode).ascii = is_ascii;
1040 if (is_ascii) {
1041 ((char*)data)[size] = 0;
1042 _PyUnicode_WSTR(unicode) = NULL;
1043 }
1044 else if (kind_state == PyUnicode_1BYTE_KIND) {
1045 ((char*)data)[size] = 0;
1046 _PyUnicode_WSTR(unicode) = NULL;
1047 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001048 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001049 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001050 }
1051 else {
1052 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 if (kind_state == PyUnicode_2BYTE_KIND)
1055 ((Py_UCS2*)data)[size] = 0;
1056 else /* kind_state == PyUnicode_4BYTE_KIND */
1057 ((Py_UCS4*)data)[size] = 0;
1058 if (is_sharing) {
1059 _PyUnicode_WSTR_LENGTH(unicode) = size;
1060 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1061 }
1062 else {
1063 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1064 _PyUnicode_WSTR(unicode) = NULL;
1065 }
1066 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01001067 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001068 return obj;
1069}
1070
1071#if SIZEOF_WCHAR_T == 2
1072/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1073 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001074 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001075
1076 This function assumes that unicode can hold one more code point than wstr
1077 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001078static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001079unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001080 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001081{
1082 const wchar_t *iter;
1083 Py_UCS4 *ucs4_out;
1084
Victor Stinner910337b2011-10-03 03:20:16 +02001085 assert(unicode != NULL);
1086 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001087 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1088 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1089
1090 for (iter = begin; iter < end; ) {
1091 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1092 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001093 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1094 && (iter+1) < end
1095 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001096 {
Victor Stinner551ac952011-11-29 22:58:13 +01001097 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001098 iter += 2;
1099 }
1100 else {
1101 *ucs4_out++ = *iter;
1102 iter++;
1103 }
1104 }
1105 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1106 _PyUnicode_GET_LENGTH(unicode)));
1107
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001108}
1109#endif
1110
Victor Stinnercd9950f2011-10-02 00:34:53 +02001111static int
Victor Stinner488fa492011-12-12 00:01:39 +01001112unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001113{
Victor Stinner488fa492011-12-12 00:01:39 +01001114 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001115 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001116 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001117 return -1;
1118 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001119 return 0;
1120}
1121
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001122static int
1123_copy_characters(PyObject *to, Py_ssize_t to_start,
1124 PyObject *from, Py_ssize_t from_start,
1125 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001126{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001127 unsigned int from_kind, to_kind;
1128 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001129 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001130
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001131 assert(PyUnicode_Check(from));
1132 assert(PyUnicode_Check(to));
1133 assert(PyUnicode_IS_READY(from));
1134 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001135
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001136 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1137 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1138 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001139
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001140 if (how_many == 0)
1141 return 0;
1142
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001143 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001144 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001145 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001146 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001147
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001148#ifdef Py_DEBUG
1149 if (!check_maxchar
1150 && (from_kind > to_kind
1151 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001152 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001153 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1154 Py_UCS4 ch;
1155 Py_ssize_t i;
1156 for (i=0; i < how_many; i++) {
1157 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1158 assert(ch <= to_maxchar);
1159 }
1160 }
1161#endif
1162 fast = (from_kind == to_kind);
1163 if (check_maxchar
1164 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1165 {
1166 /* deny latin1 => ascii */
1167 fast = 0;
1168 }
1169
1170 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001171 Py_MEMCPY((char*)to_data + to_kind * to_start,
1172 (char*)from_data + from_kind * from_start,
1173 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001174 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001175 else if (from_kind == PyUnicode_1BYTE_KIND
1176 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001177 {
1178 _PyUnicode_CONVERT_BYTES(
1179 Py_UCS1, Py_UCS2,
1180 PyUnicode_1BYTE_DATA(from) + from_start,
1181 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1182 PyUnicode_2BYTE_DATA(to) + to_start
1183 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001184 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001185 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001186 && to_kind == PyUnicode_4BYTE_KIND)
1187 {
1188 _PyUnicode_CONVERT_BYTES(
1189 Py_UCS1, Py_UCS4,
1190 PyUnicode_1BYTE_DATA(from) + from_start,
1191 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1192 PyUnicode_4BYTE_DATA(to) + to_start
1193 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001194 }
1195 else if (from_kind == PyUnicode_2BYTE_KIND
1196 && to_kind == PyUnicode_4BYTE_KIND)
1197 {
1198 _PyUnicode_CONVERT_BYTES(
1199 Py_UCS2, Py_UCS4,
1200 PyUnicode_2BYTE_DATA(from) + from_start,
1201 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1202 PyUnicode_4BYTE_DATA(to) + to_start
1203 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001204 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001205 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001206 /* check if max_char(from substring) <= max_char(to) */
1207 if (from_kind > to_kind
1208 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001209 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001210 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001211 /* slow path to check for character overflow */
1212 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001213 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001214 Py_ssize_t i;
1215
Victor Stinner56c161a2011-10-06 02:47:11 +02001216#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001217 for (i=0; i < how_many; i++) {
1218 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001219 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001220 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1221 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001222#else
1223 if (!check_maxchar) {
1224 for (i=0; i < how_many; i++) {
1225 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1226 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1227 }
1228 }
1229 else {
1230 for (i=0; i < how_many; i++) {
1231 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1232 if (ch > to_maxchar)
1233 return 1;
1234 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1235 }
1236 }
1237#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001238 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001239 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001240 assert(0 && "inconsistent state");
1241 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001242 }
1243 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001244 return 0;
1245}
1246
1247static void
1248copy_characters(PyObject *to, Py_ssize_t to_start,
1249 PyObject *from, Py_ssize_t from_start,
1250 Py_ssize_t how_many)
1251{
1252 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1253}
1254
1255Py_ssize_t
1256PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1257 PyObject *from, Py_ssize_t from_start,
1258 Py_ssize_t how_many)
1259{
1260 int err;
1261
1262 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1263 PyErr_BadInternalCall();
1264 return -1;
1265 }
1266
Benjamin Petersonbac79492012-01-14 13:34:47 -05001267 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001268 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001269 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001270 return -1;
1271
1272 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1273 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1274 PyErr_Format(PyExc_SystemError,
1275 "Cannot write %zi characters at %zi "
1276 "in a string of %zi characters",
1277 how_many, to_start, PyUnicode_GET_LENGTH(to));
1278 return -1;
1279 }
1280
1281 if (how_many == 0)
1282 return 0;
1283
Victor Stinner488fa492011-12-12 00:01:39 +01001284 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001285 return -1;
1286
1287 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1288 if (err) {
1289 PyErr_Format(PyExc_SystemError,
1290 "Cannot copy %s characters "
1291 "into a string of %s characters",
1292 unicode_kind_name(from),
1293 unicode_kind_name(to));
1294 return -1;
1295 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001296 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001297}
1298
Victor Stinner17222162011-09-28 22:15:37 +02001299/* Find the maximum code point and count the number of surrogate pairs so a
1300 correct string length can be computed before converting a string to UCS4.
1301 This function counts single surrogates as a character and not as a pair.
1302
1303 Return 0 on success, or -1 on error. */
1304static int
1305find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1306 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001307{
1308 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001309 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001310
Victor Stinnerc53be962011-10-02 21:33:54 +02001311 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001312 *num_surrogates = 0;
1313 *maxchar = 0;
1314
1315 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001317 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1318 && (iter+1) < end
1319 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001321 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001322 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001323 iter += 2;
1324 }
1325 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001326#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001327 {
1328 ch = *iter;
1329 iter++;
1330 }
1331 if (ch > *maxchar) {
1332 *maxchar = ch;
1333 if (*maxchar > MAX_UNICODE) {
1334 PyErr_Format(PyExc_ValueError,
1335 "character U+%x is not in range [U+0000; U+10ffff]",
1336 ch);
1337 return -1;
1338 }
1339 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001340 }
1341 return 0;
1342}
1343
1344#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001345static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001346#endif
1347
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001348int
1349_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350{
1351 wchar_t *end;
1352 Py_UCS4 maxchar = 0;
1353 Py_ssize_t num_surrogates;
1354#if SIZEOF_WCHAR_T == 2
1355 Py_ssize_t length_wo_surrogates;
1356#endif
1357
Georg Brandl7597add2011-10-05 16:36:47 +02001358 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001359 strings were created using _PyObject_New() and where no canonical
1360 representation (the str field) has been set yet aka strings
1361 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001362 assert(_PyUnicode_CHECK(unicode));
1363 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001364 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001365 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001366 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001367 /* Actually, it should neither be interned nor be anything else: */
1368 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001369
1370#ifdef Py_DEBUG
1371 ++unicode_ready_calls;
1372#endif
1373
1374 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001375 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001376 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001377 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001378
1379 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001380 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1381 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001382 PyErr_NoMemory();
1383 return -1;
1384 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001385 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001386 _PyUnicode_WSTR(unicode), end,
1387 PyUnicode_1BYTE_DATA(unicode));
1388 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1389 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1390 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1391 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001392 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001393 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001394 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001395 }
1396 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001397 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001398 _PyUnicode_UTF8(unicode) = NULL;
1399 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001400 }
1401 PyObject_FREE(_PyUnicode_WSTR(unicode));
1402 _PyUnicode_WSTR(unicode) = NULL;
1403 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1404 }
1405 /* In this case we might have to convert down from 4-byte native
1406 wchar_t to 2-byte unicode. */
1407 else if (maxchar < 65536) {
1408 assert(num_surrogates == 0 &&
1409 "FindMaxCharAndNumSurrogatePairs() messed up");
1410
Victor Stinner506f5922011-09-28 22:34:18 +02001411#if SIZEOF_WCHAR_T == 2
1412 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001413 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001414 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1415 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1416 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001417 _PyUnicode_UTF8(unicode) = NULL;
1418 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001419#else
1420 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001421 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001422 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001423 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001424 PyErr_NoMemory();
1425 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001426 }
Victor Stinner506f5922011-09-28 22:34:18 +02001427 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1428 _PyUnicode_WSTR(unicode), end,
1429 PyUnicode_2BYTE_DATA(unicode));
1430 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1431 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1432 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001433 _PyUnicode_UTF8(unicode) = NULL;
1434 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001435 PyObject_FREE(_PyUnicode_WSTR(unicode));
1436 _PyUnicode_WSTR(unicode) = NULL;
1437 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1438#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001439 }
1440 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1441 else {
1442#if SIZEOF_WCHAR_T == 2
1443 /* in case the native representation is 2-bytes, we need to allocate a
1444 new normalized 4-byte version. */
1445 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001446 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1447 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001448 PyErr_NoMemory();
1449 return -1;
1450 }
1451 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1452 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001453 _PyUnicode_UTF8(unicode) = NULL;
1454 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001455 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1456 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001457 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001458 PyObject_FREE(_PyUnicode_WSTR(unicode));
1459 _PyUnicode_WSTR(unicode) = NULL;
1460 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1461#else
1462 assert(num_surrogates == 0);
1463
Victor Stinnerc3c74152011-10-02 20:39:55 +02001464 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001465 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001466 _PyUnicode_UTF8(unicode) = NULL;
1467 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001468 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1469#endif
1470 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1471 }
1472 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001473 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001474 return 0;
1475}
1476
Alexander Belopolsky40018472011-02-26 01:02:56 +00001477static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001478unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001479{
Walter Dörwald16807132007-05-25 13:52:07 +00001480 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001481 case SSTATE_NOT_INTERNED:
1482 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001483
Benjamin Peterson29060642009-01-31 22:14:21 +00001484 case SSTATE_INTERNED_MORTAL:
1485 /* revive dead object temporarily for DelItem */
1486 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001487 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001488 Py_FatalError(
1489 "deletion of interned string failed");
1490 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001491
Benjamin Peterson29060642009-01-31 22:14:21 +00001492 case SSTATE_INTERNED_IMMORTAL:
1493 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001494
Benjamin Peterson29060642009-01-31 22:14:21 +00001495 default:
1496 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001497 }
1498
Victor Stinner03490912011-10-03 23:45:12 +02001499 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001500 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001501 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001502 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001503 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1504 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001505
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001506 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001507}
1508
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001509#ifdef Py_DEBUG
1510static int
1511unicode_is_singleton(PyObject *unicode)
1512{
1513 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1514 if (unicode == unicode_empty)
1515 return 1;
1516 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1517 {
1518 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1519 if (ch < 256 && unicode_latin1[ch] == unicode)
1520 return 1;
1521 }
1522 return 0;
1523}
1524#endif
1525
Alexander Belopolsky40018472011-02-26 01:02:56 +00001526static int
Victor Stinner488fa492011-12-12 00:01:39 +01001527unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001528{
Victor Stinner488fa492011-12-12 00:01:39 +01001529 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001530 if (Py_REFCNT(unicode) != 1)
1531 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001532 if (_PyUnicode_HASH(unicode) != -1)
1533 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001534 if (PyUnicode_CHECK_INTERNED(unicode))
1535 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001536 if (!PyUnicode_CheckExact(unicode))
1537 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001538#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001539 /* singleton refcount is greater than 1 */
1540 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001541#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001542 return 1;
1543}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001544
Victor Stinnerfe226c02011-10-03 03:52:20 +02001545static int
1546unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1547{
1548 PyObject *unicode;
1549 Py_ssize_t old_length;
1550
1551 assert(p_unicode != NULL);
1552 unicode = *p_unicode;
1553
1554 assert(unicode != NULL);
1555 assert(PyUnicode_Check(unicode));
1556 assert(0 <= length);
1557
Victor Stinner910337b2011-10-03 03:20:16 +02001558 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001559 old_length = PyUnicode_WSTR_LENGTH(unicode);
1560 else
1561 old_length = PyUnicode_GET_LENGTH(unicode);
1562 if (old_length == length)
1563 return 0;
1564
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001565 if (length == 0) {
1566 Py_DECREF(*p_unicode);
1567 *p_unicode = unicode_empty;
1568 Py_INCREF(*p_unicode);
1569 return 0;
1570 }
1571
Victor Stinner488fa492011-12-12 00:01:39 +01001572 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001573 PyObject *copy = resize_copy(unicode, length);
1574 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001575 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001576 Py_DECREF(*p_unicode);
1577 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001578 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001579 }
1580
Victor Stinnerfe226c02011-10-03 03:52:20 +02001581 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001582 PyObject *new_unicode = resize_compact(unicode, length);
1583 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001584 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001585 *p_unicode = new_unicode;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001586 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001587 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001588 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001589 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001590}
1591
Alexander Belopolsky40018472011-02-26 01:02:56 +00001592int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001593PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001594{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001595 PyObject *unicode;
1596 if (p_unicode == NULL) {
1597 PyErr_BadInternalCall();
1598 return -1;
1599 }
1600 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001601 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001602 {
1603 PyErr_BadInternalCall();
1604 return -1;
1605 }
1606 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001607}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001608
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001609static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001610unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001611{
1612 PyObject *result;
1613 assert(PyUnicode_IS_READY(*p_unicode));
1614 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1615 return 0;
1616 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1617 maxchar);
1618 if (result == NULL)
1619 return -1;
1620 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1621 PyUnicode_GET_LENGTH(*p_unicode));
1622 Py_DECREF(*p_unicode);
1623 *p_unicode = result;
1624 return 0;
1625}
1626
1627static int
1628unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1629 Py_UCS4 ch)
1630{
Victor Stinner15e9ed22012-02-22 13:36:20 +01001631 assert(ch <= MAX_UNICODE);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001632 if (unicode_widen(p_unicode, ch) < 0)
1633 return -1;
1634 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1635 PyUnicode_DATA(*p_unicode),
1636 (*pos)++, ch);
1637 return 0;
1638}
1639
Victor Stinnerc5166102012-02-22 13:55:02 +01001640/* Copy a ASCII or latin1 char* string into a Python Unicode string.
1641 Return the length of the input string.
1642
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001643 WARNING: The function doesn't copy the terminating null character and
1644 doesn't check the maximum character (may write a latin1 character in an
1645 ASCII string). */
Victor Stinnerc5166102012-02-22 13:55:02 +01001646static Py_ssize_t
1647unicode_write_cstr(PyObject *unicode, Py_ssize_t index, const char *str)
1648{
1649 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1650 void *data = PyUnicode_DATA(unicode);
1651
1652 switch (kind) {
1653 case PyUnicode_1BYTE_KIND: {
1654 Py_ssize_t len = strlen(str);
1655 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001656 memcpy((char *) data + index, str, len);
Victor Stinnerc5166102012-02-22 13:55:02 +01001657 return len;
1658 }
1659 case PyUnicode_2BYTE_KIND: {
1660 Py_UCS2 *start = (Py_UCS2 *)data + index;
1661 Py_UCS2 *ucs2 = start;
1662 assert(index <= PyUnicode_GET_LENGTH(unicode));
1663
1664 for (; *str; ++ucs2, ++str)
1665 *ucs2 = (Py_UCS2)*str;
1666
1667 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
1668 return ucs2 - start;
1669 }
1670 default: {
1671 Py_UCS4 *start = (Py_UCS4 *)data + index;
1672 Py_UCS4 *ucs4 = start;
1673 assert(kind == PyUnicode_4BYTE_KIND);
1674 assert(index <= PyUnicode_GET_LENGTH(unicode));
1675
1676 for (; *str; ++ucs4, ++str)
1677 *ucs4 = (Py_UCS4)*str;
1678
1679 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
1680 return ucs4 - start;
1681 }
1682 }
1683}
1684
1685
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001686static PyObject*
1687get_latin1_char(unsigned char ch)
1688{
Victor Stinnera464fc12011-10-02 20:39:30 +02001689 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001690 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001691 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001692 if (!unicode)
1693 return NULL;
1694 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001695 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001696 unicode_latin1[ch] = unicode;
1697 }
1698 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001699 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001700}
1701
Alexander Belopolsky40018472011-02-26 01:02:56 +00001702PyObject *
1703PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001704{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001705 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001706 Py_UCS4 maxchar = 0;
1707 Py_ssize_t num_surrogates;
1708
1709 if (u == NULL)
1710 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001711
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001712 /* If the Unicode data is known at construction time, we can apply
1713 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001714
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001715 /* Optimization for empty strings */
1716 if (size == 0 && unicode_empty != NULL) {
1717 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001718 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001719 }
Tim Petersced69f82003-09-16 20:30:58 +00001720
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001721 /* Single character Unicode objects in the Latin-1 range are
1722 shared when using this constructor */
1723 if (size == 1 && *u < 256)
1724 return get_latin1_char((unsigned char)*u);
1725
1726 /* If not empty and not single character, copy the Unicode data
1727 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001728 if (find_maxchar_surrogates(u, u + size,
1729 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001730 return NULL;
1731
Victor Stinner8faf8212011-12-08 22:14:11 +01001732 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001733 if (!unicode)
1734 return NULL;
1735
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001736 switch (PyUnicode_KIND(unicode)) {
1737 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001738 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001739 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1740 break;
1741 case PyUnicode_2BYTE_KIND:
1742#if Py_UNICODE_SIZE == 2
1743 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1744#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001745 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001746 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1747#endif
1748 break;
1749 case PyUnicode_4BYTE_KIND:
1750#if SIZEOF_WCHAR_T == 2
1751 /* This is the only case which has to process surrogates, thus
1752 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001753 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001754#else
1755 assert(num_surrogates == 0);
1756 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1757#endif
1758 break;
1759 default:
1760 assert(0 && "Impossible state");
1761 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001762
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001763 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001764}
1765
Alexander Belopolsky40018472011-02-26 01:02:56 +00001766PyObject *
1767PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001768{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001769 if (size < 0) {
1770 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001771 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001772 return NULL;
1773 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001774 if (u != NULL)
1775 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1776 else
1777 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001778}
1779
Alexander Belopolsky40018472011-02-26 01:02:56 +00001780PyObject *
1781PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001782{
1783 size_t size = strlen(u);
1784 if (size > PY_SSIZE_T_MAX) {
1785 PyErr_SetString(PyExc_OverflowError, "input too long");
1786 return NULL;
1787 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001788 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001789}
1790
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001791PyObject *
1792_PyUnicode_FromId(_Py_Identifier *id)
1793{
1794 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001795 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1796 strlen(id->string),
1797 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001798 if (!id->object)
1799 return NULL;
1800 PyUnicode_InternInPlace(&id->object);
1801 assert(!id->next);
1802 id->next = static_strings;
1803 static_strings = id;
1804 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001805 return id->object;
1806}
1807
1808void
1809_PyUnicode_ClearStaticStrings()
1810{
1811 _Py_Identifier *i;
1812 for (i = static_strings; i; i = i->next) {
1813 Py_DECREF(i->object);
1814 i->object = NULL;
1815 i->next = NULL;
1816 }
1817}
1818
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001819/* Internal function, don't check maximum character */
1820
Victor Stinnere57b1c02011-09-28 22:20:48 +02001821static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001822unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001823{
Victor Stinner785938e2011-12-11 20:09:03 +01001824 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001825 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001826#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001827 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001828#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001829 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001830 }
Victor Stinner785938e2011-12-11 20:09:03 +01001831 unicode = PyUnicode_New(size, 127);
1832 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001833 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001834 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1835 assert(_PyUnicode_CheckConsistency(unicode, 1));
1836 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001837}
1838
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001839static Py_UCS4
1840kind_maxchar_limit(unsigned int kind)
1841{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001842 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001843 case PyUnicode_1BYTE_KIND:
1844 return 0x80;
1845 case PyUnicode_2BYTE_KIND:
1846 return 0x100;
1847 case PyUnicode_4BYTE_KIND:
1848 return 0x10000;
1849 default:
1850 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001851 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001852 }
1853}
1854
Victor Stinner702c7342011-10-05 13:50:52 +02001855static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001856_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001857{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001858 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001859 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001860
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001861 if (size == 0) {
1862 Py_INCREF(unicode_empty);
1863 return unicode_empty;
1864 }
1865 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001866 if (size == 1)
1867 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001868
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001869 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001870 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001871 if (!res)
1872 return NULL;
1873 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001874 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001875 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001876}
1877
Victor Stinnere57b1c02011-09-28 22:20:48 +02001878static PyObject*
1879_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001880{
1881 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001882 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001883
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001884 if (size == 0) {
1885 Py_INCREF(unicode_empty);
1886 return unicode_empty;
1887 }
1888 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001889 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001890 return get_latin1_char((unsigned char)u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001891
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001892 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001893 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001894 if (!res)
1895 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001896 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001897 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001898 else {
1899 _PyUnicode_CONVERT_BYTES(
1900 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1901 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001902 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001903 return res;
1904}
1905
Victor Stinnere57b1c02011-09-28 22:20:48 +02001906static PyObject*
1907_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001908{
1909 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001910 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001911
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001912 if (size == 0) {
1913 Py_INCREF(unicode_empty);
1914 return unicode_empty;
1915 }
1916 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001917 if (size == 1 && u[0] < 256)
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001918 return get_latin1_char((unsigned char)u[0]);
1919
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001920 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001921 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001922 if (!res)
1923 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001924 if (max_char < 256)
1925 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1926 PyUnicode_1BYTE_DATA(res));
1927 else if (max_char < 0x10000)
1928 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1929 PyUnicode_2BYTE_DATA(res));
1930 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001931 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001932 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001933 return res;
1934}
1935
1936PyObject*
1937PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1938{
Victor Stinnercfed46e2011-11-22 01:29:14 +01001939 if (size < 0) {
1940 PyErr_SetString(PyExc_ValueError, "size must be positive");
1941 return NULL;
1942 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06001943 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001944 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001945 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001946 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001947 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001948 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001949 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001950 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02001951 PyErr_SetString(PyExc_SystemError, "invalid kind");
1952 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001953 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001954}
1955
Victor Stinner25a4b292011-10-06 12:31:55 +02001956/* Ensure that a string uses the most efficient storage, if it is not the
1957 case: create a new string with of the right kind. Write NULL into *p_unicode
1958 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001959static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001960unicode_adjust_maxchar(PyObject **p_unicode)
1961{
1962 PyObject *unicode, *copy;
1963 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001964 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001965 unsigned int kind;
1966
1967 assert(p_unicode != NULL);
1968 unicode = *p_unicode;
1969 assert(PyUnicode_IS_READY(unicode));
1970 if (PyUnicode_IS_ASCII(unicode))
1971 return;
1972
1973 len = PyUnicode_GET_LENGTH(unicode);
1974 kind = PyUnicode_KIND(unicode);
1975 if (kind == PyUnicode_1BYTE_KIND) {
1976 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001977 max_char = ucs1lib_find_max_char(u, u + len);
1978 if (max_char >= 128)
1979 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001980 }
1981 else if (kind == PyUnicode_2BYTE_KIND) {
1982 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001983 max_char = ucs2lib_find_max_char(u, u + len);
1984 if (max_char >= 256)
1985 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001986 }
1987 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001988 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001989 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001990 max_char = ucs4lib_find_max_char(u, u + len);
1991 if (max_char >= 0x10000)
1992 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001993 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001994 copy = PyUnicode_New(len, max_char);
1995 copy_characters(copy, 0, unicode, 0, len);
1996 Py_DECREF(unicode);
1997 *p_unicode = copy;
1998}
1999
Victor Stinner034f6cf2011-09-30 02:26:44 +02002000PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002001_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002002{
Victor Stinner87af4f22011-11-21 23:03:47 +01002003 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002004 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002005
Victor Stinner034f6cf2011-09-30 02:26:44 +02002006 if (!PyUnicode_Check(unicode)) {
2007 PyErr_BadInternalCall();
2008 return NULL;
2009 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002010 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002011 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002012
Victor Stinner87af4f22011-11-21 23:03:47 +01002013 length = PyUnicode_GET_LENGTH(unicode);
2014 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002015 if (!copy)
2016 return NULL;
2017 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2018
Victor Stinner87af4f22011-11-21 23:03:47 +01002019 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2020 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002021 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002022 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002023}
2024
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002025
Victor Stinnerbc603d12011-10-02 01:00:40 +02002026/* Widen Unicode objects to larger buffers. Don't write terminating null
2027 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002028
2029void*
2030_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2031{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002032 Py_ssize_t len;
2033 void *result;
2034 unsigned int skind;
2035
Benjamin Petersonbac79492012-01-14 13:34:47 -05002036 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002037 return NULL;
2038
2039 len = PyUnicode_GET_LENGTH(s);
2040 skind = PyUnicode_KIND(s);
2041 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002042 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002043 return NULL;
2044 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002045 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002046 case PyUnicode_2BYTE_KIND:
2047 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2048 if (!result)
2049 return PyErr_NoMemory();
2050 assert(skind == PyUnicode_1BYTE_KIND);
2051 _PyUnicode_CONVERT_BYTES(
2052 Py_UCS1, Py_UCS2,
2053 PyUnicode_1BYTE_DATA(s),
2054 PyUnicode_1BYTE_DATA(s) + len,
2055 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002056 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002057 case PyUnicode_4BYTE_KIND:
2058 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2059 if (!result)
2060 return PyErr_NoMemory();
2061 if (skind == PyUnicode_2BYTE_KIND) {
2062 _PyUnicode_CONVERT_BYTES(
2063 Py_UCS2, Py_UCS4,
2064 PyUnicode_2BYTE_DATA(s),
2065 PyUnicode_2BYTE_DATA(s) + len,
2066 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002067 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002068 else {
2069 assert(skind == PyUnicode_1BYTE_KIND);
2070 _PyUnicode_CONVERT_BYTES(
2071 Py_UCS1, Py_UCS4,
2072 PyUnicode_1BYTE_DATA(s),
2073 PyUnicode_1BYTE_DATA(s) + len,
2074 result);
2075 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002076 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002077 default:
2078 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002079 }
Victor Stinner01698042011-10-04 00:04:26 +02002080 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002081 return NULL;
2082}
2083
2084static Py_UCS4*
2085as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2086 int copy_null)
2087{
2088 int kind;
2089 void *data;
2090 Py_ssize_t len, targetlen;
2091 if (PyUnicode_READY(string) == -1)
2092 return NULL;
2093 kind = PyUnicode_KIND(string);
2094 data = PyUnicode_DATA(string);
2095 len = PyUnicode_GET_LENGTH(string);
2096 targetlen = len;
2097 if (copy_null)
2098 targetlen++;
2099 if (!target) {
2100 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2101 PyErr_NoMemory();
2102 return NULL;
2103 }
2104 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2105 if (!target) {
2106 PyErr_NoMemory();
2107 return NULL;
2108 }
2109 }
2110 else {
2111 if (targetsize < targetlen) {
2112 PyErr_Format(PyExc_SystemError,
2113 "string is longer than the buffer");
2114 if (copy_null && 0 < targetsize)
2115 target[0] = 0;
2116 return NULL;
2117 }
2118 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002119 if (kind == PyUnicode_1BYTE_KIND) {
2120 Py_UCS1 *start = (Py_UCS1 *) data;
2121 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002122 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002123 else if (kind == PyUnicode_2BYTE_KIND) {
2124 Py_UCS2 *start = (Py_UCS2 *) data;
2125 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2126 }
2127 else {
2128 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002129 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002130 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002131 if (copy_null)
2132 target[len] = 0;
2133 return target;
2134}
2135
2136Py_UCS4*
2137PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2138 int copy_null)
2139{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002140 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002141 PyErr_BadInternalCall();
2142 return NULL;
2143 }
2144 return as_ucs4(string, target, targetsize, copy_null);
2145}
2146
2147Py_UCS4*
2148PyUnicode_AsUCS4Copy(PyObject *string)
2149{
2150 return as_ucs4(string, NULL, 0, 1);
2151}
2152
2153#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002154
Alexander Belopolsky40018472011-02-26 01:02:56 +00002155PyObject *
2156PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002157{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002158 if (w == NULL) {
Victor Stinner382955f2011-12-11 21:44:00 +01002159 if (size == 0) {
2160 Py_INCREF(unicode_empty);
2161 return unicode_empty;
2162 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002163 PyErr_BadInternalCall();
2164 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002165 }
2166
Martin v. Löwis790465f2008-04-05 20:41:37 +00002167 if (size == -1) {
2168 size = wcslen(w);
2169 }
2170
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002171 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002172}
2173
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002174#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002175
Walter Dörwald346737f2007-05-31 10:44:43 +00002176static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002177makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2178 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002179{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002180 *fmt++ = '%';
2181 if (width) {
2182 if (zeropad)
2183 *fmt++ = '0';
2184 fmt += sprintf(fmt, "%d", width);
2185 }
2186 if (precision)
2187 fmt += sprintf(fmt, ".%d", precision);
2188 if (longflag)
2189 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002190 else if (longlongflag) {
2191 /* longlongflag should only ever be nonzero on machines with
2192 HAVE_LONG_LONG defined */
2193#ifdef HAVE_LONG_LONG
2194 char *f = PY_FORMAT_LONG_LONG;
2195 while (*f)
2196 *fmt++ = *f++;
2197#else
2198 /* we shouldn't ever get here */
2199 assert(0);
2200 *fmt++ = 'l';
2201#endif
2202 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002203 else if (size_tflag) {
2204 char *f = PY_FORMAT_SIZE_T;
2205 while (*f)
2206 *fmt++ = *f++;
2207 }
2208 *fmt++ = c;
2209 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002210}
2211
Victor Stinner96865452011-03-01 23:44:09 +00002212/* helper for PyUnicode_FromFormatV() */
2213
2214static const char*
2215parse_format_flags(const char *f,
2216 int *p_width, int *p_precision,
2217 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2218{
2219 int width, precision, longflag, longlongflag, size_tflag;
2220
2221 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2222 f++;
2223 width = 0;
2224 while (Py_ISDIGIT((unsigned)*f))
2225 width = (width*10) + *f++ - '0';
2226 precision = 0;
2227 if (*f == '.') {
2228 f++;
2229 while (Py_ISDIGIT((unsigned)*f))
2230 precision = (precision*10) + *f++ - '0';
2231 if (*f == '%') {
2232 /* "%.3%s" => f points to "3" */
2233 f--;
2234 }
2235 }
2236 if (*f == '\0') {
2237 /* bogus format "%.1" => go backward, f points to "1" */
2238 f--;
2239 }
2240 if (p_width != NULL)
2241 *p_width = width;
2242 if (p_precision != NULL)
2243 *p_precision = precision;
2244
2245 /* Handle %ld, %lu, %lld and %llu. */
2246 longflag = 0;
2247 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002248 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002249
2250 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002251 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002252 longflag = 1;
2253 ++f;
2254 }
2255#ifdef HAVE_LONG_LONG
2256 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002257 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002258 longlongflag = 1;
2259 f += 2;
2260 }
2261#endif
2262 }
2263 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002264 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002265 size_tflag = 1;
2266 ++f;
2267 }
2268 if (p_longflag != NULL)
2269 *p_longflag = longflag;
2270 if (p_longlongflag != NULL)
2271 *p_longlongflag = longlongflag;
2272 if (p_size_tflag != NULL)
2273 *p_size_tflag = size_tflag;
2274 return f;
2275}
2276
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002277/* maximum number of characters required for output of %ld. 21 characters
2278 allows for 64-bit integers (in decimal) and an optional sign. */
2279#define MAX_LONG_CHARS 21
2280/* maximum number of characters required for output of %lld.
2281 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2282 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2283#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2284
Walter Dörwaldd2034312007-05-18 16:29:38 +00002285PyObject *
2286PyUnicode_FromFormatV(const char *format, va_list vargs)
2287{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002288 va_list count;
2289 Py_ssize_t callcount = 0;
2290 PyObject **callresults = NULL;
2291 PyObject **callresult = NULL;
2292 Py_ssize_t n = 0;
2293 int width = 0;
2294 int precision = 0;
2295 int zeropad;
2296 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002297 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002298 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002299 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002300 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2301 Py_UCS4 argmaxchar;
2302 Py_ssize_t numbersize = 0;
2303 char *numberresults = NULL;
2304 char *numberresult = NULL;
2305 Py_ssize_t i;
2306 int kind;
2307 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002308
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002309 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002310 /* step 1: count the number of %S/%R/%A/%s format specifications
2311 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2312 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002313 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002314 * also estimate a upper bound for all the number formats in the string,
2315 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002316 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002317 for (f = format; *f; f++) {
2318 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002319 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002320 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2321 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2322 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2323 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002324
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002325 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002326#ifdef HAVE_LONG_LONG
2327 if (longlongflag) {
2328 if (width < MAX_LONG_LONG_CHARS)
2329 width = MAX_LONG_LONG_CHARS;
2330 }
2331 else
2332#endif
2333 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2334 including sign. Decimal takes the most space. This
2335 isn't enough for octal. If a width is specified we
2336 need more (which we allocate later). */
2337 if (width < MAX_LONG_CHARS)
2338 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002339
2340 /* account for the size + '\0' to separate numbers
2341 inside of the numberresults buffer */
2342 numbersize += (width + 1);
2343 }
2344 }
2345 else if ((unsigned char)*f > 127) {
2346 PyErr_Format(PyExc_ValueError,
2347 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2348 "string, got a non-ASCII byte: 0x%02x",
2349 (unsigned char)*f);
2350 return NULL;
2351 }
2352 }
2353 /* step 2: allocate memory for the results of
2354 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2355 if (callcount) {
2356 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2357 if (!callresults) {
2358 PyErr_NoMemory();
2359 return NULL;
2360 }
2361 callresult = callresults;
2362 }
2363 /* step 2.5: allocate memory for the results of formating numbers */
2364 if (numbersize) {
2365 numberresults = PyObject_Malloc(numbersize);
2366 if (!numberresults) {
2367 PyErr_NoMemory();
2368 goto fail;
2369 }
2370 numberresult = numberresults;
2371 }
2372
2373 /* step 3: format numbers and figure out how large a buffer we need */
2374 for (f = format; *f; f++) {
2375 if (*f == '%') {
2376 const char* p;
2377 int longflag;
2378 int longlongflag;
2379 int size_tflag;
2380 int numprinted;
2381
2382 p = f;
2383 zeropad = (f[1] == '0');
2384 f = parse_format_flags(f, &width, &precision,
2385 &longflag, &longlongflag, &size_tflag);
2386 switch (*f) {
2387 case 'c':
2388 {
2389 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002390 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002391 n++;
2392 break;
2393 }
2394 case '%':
2395 n++;
2396 break;
2397 case 'i':
2398 case 'd':
2399 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2400 width, precision, *f);
2401 if (longflag)
2402 numprinted = sprintf(numberresult, fmt,
2403 va_arg(count, long));
2404#ifdef HAVE_LONG_LONG
2405 else if (longlongflag)
2406 numprinted = sprintf(numberresult, fmt,
2407 va_arg(count, PY_LONG_LONG));
2408#endif
2409 else if (size_tflag)
2410 numprinted = sprintf(numberresult, fmt,
2411 va_arg(count, Py_ssize_t));
2412 else
2413 numprinted = sprintf(numberresult, fmt,
2414 va_arg(count, int));
2415 n += numprinted;
2416 /* advance by +1 to skip over the '\0' */
2417 numberresult += (numprinted + 1);
2418 assert(*(numberresult - 1) == '\0');
2419 assert(*(numberresult - 2) != '\0');
2420 assert(numprinted >= 0);
2421 assert(numberresult <= numberresults + numbersize);
2422 break;
2423 case 'u':
2424 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2425 width, precision, 'u');
2426 if (longflag)
2427 numprinted = sprintf(numberresult, fmt,
2428 va_arg(count, unsigned long));
2429#ifdef HAVE_LONG_LONG
2430 else if (longlongflag)
2431 numprinted = sprintf(numberresult, fmt,
2432 va_arg(count, unsigned PY_LONG_LONG));
2433#endif
2434 else if (size_tflag)
2435 numprinted = sprintf(numberresult, fmt,
2436 va_arg(count, size_t));
2437 else
2438 numprinted = sprintf(numberresult, fmt,
2439 va_arg(count, unsigned int));
2440 n += numprinted;
2441 numberresult += (numprinted + 1);
2442 assert(*(numberresult - 1) == '\0');
2443 assert(*(numberresult - 2) != '\0');
2444 assert(numprinted >= 0);
2445 assert(numberresult <= numberresults + numbersize);
2446 break;
2447 case 'x':
2448 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2449 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2450 n += numprinted;
2451 numberresult += (numprinted + 1);
2452 assert(*(numberresult - 1) == '\0');
2453 assert(*(numberresult - 2) != '\0');
2454 assert(numprinted >= 0);
2455 assert(numberresult <= numberresults + numbersize);
2456 break;
2457 case 'p':
2458 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2459 /* %p is ill-defined: ensure leading 0x. */
2460 if (numberresult[1] == 'X')
2461 numberresult[1] = 'x';
2462 else if (numberresult[1] != 'x') {
2463 memmove(numberresult + 2, numberresult,
2464 strlen(numberresult) + 1);
2465 numberresult[0] = '0';
2466 numberresult[1] = 'x';
2467 numprinted += 2;
2468 }
2469 n += numprinted;
2470 numberresult += (numprinted + 1);
2471 assert(*(numberresult - 1) == '\0');
2472 assert(*(numberresult - 2) != '\0');
2473 assert(numprinted >= 0);
2474 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002475 break;
2476 case 's':
2477 {
2478 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002479 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002480 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002481 if (!str)
2482 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002483 /* since PyUnicode_DecodeUTF8 returns already flexible
2484 unicode objects, there is no need to call ready on them */
2485 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002486 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002488 /* Remember the str and switch to the next slot */
2489 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002490 break;
2491 }
2492 case 'U':
2493 {
2494 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002495 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002496 if (PyUnicode_READY(obj) == -1)
2497 goto fail;
2498 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002499 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002500 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002501 break;
2502 }
2503 case 'V':
2504 {
2505 PyObject *obj = va_arg(count, PyObject *);
2506 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002507 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002508 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002509 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002510 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002511 if (PyUnicode_READY(obj) == -1)
2512 goto fail;
2513 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002514 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002515 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002516 *callresult++ = NULL;
2517 }
2518 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002519 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002520 if (!str_obj)
2521 goto fail;
Benjamin Petersonbac79492012-01-14 13:34:47 -05002522 if (PyUnicode_READY(str_obj) == -1) {
Victor Stinnere1335c72011-10-04 20:53:03 +02002523 Py_DECREF(str_obj);
2524 goto fail;
2525 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002526 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002527 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002528 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002529 *callresult++ = str_obj;
2530 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002531 break;
2532 }
2533 case 'S':
2534 {
2535 PyObject *obj = va_arg(count, PyObject *);
2536 PyObject *str;
2537 assert(obj);
2538 str = PyObject_Str(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002539 if (!str)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002540 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002541 if (PyUnicode_READY(str) == -1) {
2542 Py_DECREF(str);
2543 goto fail;
2544 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002545 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002546 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002547 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002548 /* Remember the str and switch to the next slot */
2549 *callresult++ = str;
2550 break;
2551 }
2552 case 'R':
2553 {
2554 PyObject *obj = va_arg(count, PyObject *);
2555 PyObject *repr;
2556 assert(obj);
2557 repr = PyObject_Repr(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002558 if (!repr)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002559 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002560 if (PyUnicode_READY(repr) == -1) {
2561 Py_DECREF(repr);
2562 goto fail;
2563 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002564 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002565 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002566 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002567 /* Remember the repr and switch to the next slot */
2568 *callresult++ = repr;
2569 break;
2570 }
2571 case 'A':
2572 {
2573 PyObject *obj = va_arg(count, PyObject *);
2574 PyObject *ascii;
2575 assert(obj);
2576 ascii = PyObject_ASCII(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002577 if (!ascii)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002578 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002579 if (PyUnicode_READY(ascii) == -1) {
2580 Py_DECREF(ascii);
2581 goto fail;
2582 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002583 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002584 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002585 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002586 /* Remember the repr and switch to the next slot */
2587 *callresult++ = ascii;
2588 break;
2589 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002590 default:
2591 /* if we stumble upon an unknown
2592 formatting code, copy the rest of
2593 the format string to the output
2594 string. (we cannot just skip the
2595 code, since there's no way to know
2596 what's in the argument list) */
2597 n += strlen(p);
2598 goto expand;
2599 }
2600 } else
2601 n++;
2602 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002603 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002604 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002605 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002606 we don't have to resize the string.
2607 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002608 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002609 if (!string)
2610 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002611 kind = PyUnicode_KIND(string);
2612 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002613 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002614 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002615
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002616 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002617 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002618 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002619
2620 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002621 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2622 /* checking for == because the last argument could be a empty
2623 string, which causes i to point to end, the assert at the end of
2624 the loop */
2625 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002626
Benjamin Peterson14339b62009-01-31 16:36:08 +00002627 switch (*f) {
2628 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002629 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002630 const int ordinal = va_arg(vargs, int);
2631 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002632 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002633 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002634 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002635 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002636 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002637 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002638 case 'p':
Victor Stinnerc5166102012-02-22 13:55:02 +01002639 {
2640 Py_ssize_t written;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002641 /* unused, since we already have the result */
2642 if (*f == 'p')
2643 (void) va_arg(vargs, void *);
2644 else
2645 (void) va_arg(vargs, int);
2646 /* extract the result from numberresults and append. */
Victor Stinnerc5166102012-02-22 13:55:02 +01002647 written = unicode_write_cstr(string, i, numberresult);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002648 /* skip over the separating '\0' */
Victor Stinnerc5166102012-02-22 13:55:02 +01002649 i += written;
2650 numberresult += written;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002651 assert(*numberresult == '\0');
2652 numberresult++;
2653 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002654 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002655 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002656 case 's':
2657 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002658 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002659 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002660 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002661 size = PyUnicode_GET_LENGTH(*callresult);
2662 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002663 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002664 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002665 /* We're done with the unicode()/repr() => forget it */
2666 Py_DECREF(*callresult);
2667 /* switch to next unicode()/repr() result */
2668 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002669 break;
2670 }
2671 case 'U':
2672 {
2673 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002674 Py_ssize_t size;
2675 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2676 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002677 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002678 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002679 break;
2680 }
2681 case 'V':
2682 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002683 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002684 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002685 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002686 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002687 size = PyUnicode_GET_LENGTH(obj);
2688 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002689 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002690 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002691 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002692 size = PyUnicode_GET_LENGTH(*callresult);
2693 assert(PyUnicode_KIND(*callresult) <=
2694 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002695 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002696 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002697 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002698 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002699 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002700 break;
2701 }
2702 case 'S':
2703 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002704 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002705 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002706 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002707 /* unused, since we already have the result */
2708 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002709 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002710 copy_characters(string, i, *callresult, 0, size);
2711 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002712 /* We're done with the unicode()/repr() => forget it */
2713 Py_DECREF(*callresult);
2714 /* switch to next unicode()/repr() result */
2715 ++callresult;
2716 break;
2717 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002718 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002719 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002720 break;
2721 default:
Victor Stinnerc5166102012-02-22 13:55:02 +01002722 i += unicode_write_cstr(string, i, p);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002723 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002724 goto end;
2725 }
Victor Stinner1205f272010-09-11 00:54:47 +00002726 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002727 else {
2728 assert(i < PyUnicode_GET_LENGTH(string));
2729 PyUnicode_WRITE(kind, data, i++, *f);
2730 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002731 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002732 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002733
Benjamin Peterson29060642009-01-31 22:14:21 +00002734 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002735 if (callresults)
2736 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002737 if (numberresults)
2738 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002739 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002740 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002741 if (callresults) {
2742 PyObject **callresult2 = callresults;
2743 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002744 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002745 ++callresult2;
2746 }
2747 PyObject_Free(callresults);
2748 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002749 if (numberresults)
2750 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002751 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002752}
2753
Walter Dörwaldd2034312007-05-18 16:29:38 +00002754PyObject *
2755PyUnicode_FromFormat(const char *format, ...)
2756{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002757 PyObject* ret;
2758 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002759
2760#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002761 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002762#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002763 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002764#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002765 ret = PyUnicode_FromFormatV(format, vargs);
2766 va_end(vargs);
2767 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002768}
2769
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002770#ifdef HAVE_WCHAR_H
2771
Victor Stinner5593d8a2010-10-02 11:11:27 +00002772/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2773 convert a Unicode object to a wide character string.
2774
Victor Stinnerd88d9832011-09-06 02:00:05 +02002775 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002776 character) required to convert the unicode object. Ignore size argument.
2777
Victor Stinnerd88d9832011-09-06 02:00:05 +02002778 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002779 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002780 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002781static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002782unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002783 wchar_t *w,
2784 Py_ssize_t size)
2785{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002786 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002787 const wchar_t *wstr;
2788
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002789 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002790 if (wstr == NULL)
2791 return -1;
2792
Victor Stinner5593d8a2010-10-02 11:11:27 +00002793 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002794 if (size > res)
2795 size = res + 1;
2796 else
2797 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002798 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002799 return res;
2800 }
2801 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002802 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002803}
2804
2805Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002806PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002807 wchar_t *w,
2808 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002809{
2810 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002811 PyErr_BadInternalCall();
2812 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002813 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002814 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002815}
2816
Victor Stinner137c34c2010-09-29 10:25:54 +00002817wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002818PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002819 Py_ssize_t *size)
2820{
2821 wchar_t* buffer;
2822 Py_ssize_t buflen;
2823
2824 if (unicode == NULL) {
2825 PyErr_BadInternalCall();
2826 return NULL;
2827 }
2828
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002829 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002830 if (buflen == -1)
2831 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002832 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002833 PyErr_NoMemory();
2834 return NULL;
2835 }
2836
Victor Stinner137c34c2010-09-29 10:25:54 +00002837 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2838 if (buffer == NULL) {
2839 PyErr_NoMemory();
2840 return NULL;
2841 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002842 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002843 if (buflen == -1)
2844 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002845 if (size != NULL)
2846 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002847 return buffer;
2848}
2849
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002850#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002851
Alexander Belopolsky40018472011-02-26 01:02:56 +00002852PyObject *
2853PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002854{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002855 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002856 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002857 PyErr_SetString(PyExc_ValueError,
2858 "chr() arg not in range(0x110000)");
2859 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002860 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002861
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002862 if (ordinal < 256)
2863 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002864
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002865 v = PyUnicode_New(1, ordinal);
2866 if (v == NULL)
2867 return NULL;
2868 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002869 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002870 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002871}
2872
Alexander Belopolsky40018472011-02-26 01:02:56 +00002873PyObject *
2874PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002875{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002876 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002877 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002878 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002879 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002880 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002881 Py_INCREF(obj);
2882 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002883 }
2884 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002885 /* For a Unicode subtype that's not a Unicode object,
2886 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002887 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002888 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002889 PyErr_Format(PyExc_TypeError,
2890 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002891 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002892 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002893}
2894
Alexander Belopolsky40018472011-02-26 01:02:56 +00002895PyObject *
2896PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002897 const char *encoding,
2898 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002899{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002900 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002901 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002902
Guido van Rossumd57fd912000-03-10 22:53:23 +00002903 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002904 PyErr_BadInternalCall();
2905 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002906 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002907
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002908 /* Decoding bytes objects is the most common case and should be fast */
2909 if (PyBytes_Check(obj)) {
2910 if (PyBytes_GET_SIZE(obj) == 0) {
2911 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002912 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002913 }
2914 else {
2915 v = PyUnicode_Decode(
2916 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2917 encoding, errors);
2918 }
2919 return v;
2920 }
2921
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002922 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002923 PyErr_SetString(PyExc_TypeError,
2924 "decoding str is not supported");
2925 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002926 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002927
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002928 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2929 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2930 PyErr_Format(PyExc_TypeError,
2931 "coercing to str: need bytes, bytearray "
2932 "or buffer-like object, %.80s found",
2933 Py_TYPE(obj)->tp_name);
2934 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002935 }
Tim Petersced69f82003-09-16 20:30:58 +00002936
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002937 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002938 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002939 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002940 }
Tim Petersced69f82003-09-16 20:30:58 +00002941 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002942 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002943
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002944 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002945 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002946}
2947
Victor Stinner600d3be2010-06-10 12:00:55 +00002948/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002949 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2950 1 on success. */
2951static int
2952normalize_encoding(const char *encoding,
2953 char *lower,
2954 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002955{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002956 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002957 char *l;
2958 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002959
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002960 if (encoding == NULL) {
2961 strcpy(lower, "utf-8");
2962 return 1;
2963 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002964 e = encoding;
2965 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002966 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002967 while (*e) {
2968 if (l == l_end)
2969 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002970 if (Py_ISUPPER(*e)) {
2971 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002972 }
2973 else if (*e == '_') {
2974 *l++ = '-';
2975 e++;
2976 }
2977 else {
2978 *l++ = *e++;
2979 }
2980 }
2981 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002982 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002983}
2984
Alexander Belopolsky40018472011-02-26 01:02:56 +00002985PyObject *
2986PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002987 Py_ssize_t size,
2988 const char *encoding,
2989 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002990{
2991 PyObject *buffer = NULL, *unicode;
2992 Py_buffer info;
2993 char lower[11]; /* Enough for any encoding shortcut */
2994
Fred Drakee4315f52000-05-09 19:53:39 +00002995 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002996 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002997 if ((strcmp(lower, "utf-8") == 0) ||
2998 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002999 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003000 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003001 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003002 (strcmp(lower, "iso-8859-1") == 0))
3003 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003004#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003005 else if (strcmp(lower, "mbcs") == 0)
3006 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003007#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003008 else if (strcmp(lower, "ascii") == 0)
3009 return PyUnicode_DecodeASCII(s, size, errors);
3010 else if (strcmp(lower, "utf-16") == 0)
3011 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3012 else if (strcmp(lower, "utf-32") == 0)
3013 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3014 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003015
3016 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003017 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003018 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003019 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003020 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003021 if (buffer == NULL)
3022 goto onError;
3023 unicode = PyCodec_Decode(buffer, encoding, errors);
3024 if (unicode == NULL)
3025 goto onError;
3026 if (!PyUnicode_Check(unicode)) {
3027 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003028 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003029 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003030 Py_DECREF(unicode);
3031 goto onError;
3032 }
3033 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003034 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003035
Benjamin Peterson29060642009-01-31 22:14:21 +00003036 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003037 Py_XDECREF(buffer);
3038 return NULL;
3039}
3040
Alexander Belopolsky40018472011-02-26 01:02:56 +00003041PyObject *
3042PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003043 const char *encoding,
3044 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003045{
3046 PyObject *v;
3047
3048 if (!PyUnicode_Check(unicode)) {
3049 PyErr_BadArgument();
3050 goto onError;
3051 }
3052
3053 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003054 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003055
3056 /* Decode via the codec registry */
3057 v = PyCodec_Decode(unicode, encoding, errors);
3058 if (v == NULL)
3059 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003060 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003061
Benjamin Peterson29060642009-01-31 22:14:21 +00003062 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003063 return NULL;
3064}
3065
Alexander Belopolsky40018472011-02-26 01:02:56 +00003066PyObject *
3067PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003068 const char *encoding,
3069 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003070{
3071 PyObject *v;
3072
3073 if (!PyUnicode_Check(unicode)) {
3074 PyErr_BadArgument();
3075 goto onError;
3076 }
3077
3078 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003079 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003080
3081 /* Decode via the codec registry */
3082 v = PyCodec_Decode(unicode, encoding, errors);
3083 if (v == NULL)
3084 goto onError;
3085 if (!PyUnicode_Check(v)) {
3086 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003087 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003088 Py_TYPE(v)->tp_name);
3089 Py_DECREF(v);
3090 goto onError;
3091 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003092 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003093
Benjamin Peterson29060642009-01-31 22:14:21 +00003094 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003095 return NULL;
3096}
3097
Alexander Belopolsky40018472011-02-26 01:02:56 +00003098PyObject *
3099PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003100 Py_ssize_t size,
3101 const char *encoding,
3102 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003103{
3104 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003105
Guido van Rossumd57fd912000-03-10 22:53:23 +00003106 unicode = PyUnicode_FromUnicode(s, size);
3107 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003108 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003109 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3110 Py_DECREF(unicode);
3111 return v;
3112}
3113
Alexander Belopolsky40018472011-02-26 01:02:56 +00003114PyObject *
3115PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003116 const char *encoding,
3117 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003118{
3119 PyObject *v;
3120
3121 if (!PyUnicode_Check(unicode)) {
3122 PyErr_BadArgument();
3123 goto onError;
3124 }
3125
3126 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003127 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003128
3129 /* Encode via the codec registry */
3130 v = PyCodec_Encode(unicode, encoding, errors);
3131 if (v == NULL)
3132 goto onError;
3133 return v;
3134
Benjamin Peterson29060642009-01-31 22:14:21 +00003135 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003136 return NULL;
3137}
3138
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003139static size_t
3140wcstombs_errorpos(const wchar_t *wstr)
3141{
3142 size_t len;
3143#if SIZEOF_WCHAR_T == 2
3144 wchar_t buf[3];
3145#else
3146 wchar_t buf[2];
3147#endif
3148 char outbuf[MB_LEN_MAX];
3149 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003150
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003151#if SIZEOF_WCHAR_T == 2
3152 buf[2] = 0;
3153#else
3154 buf[1] = 0;
3155#endif
3156 start = wstr;
3157 while (*wstr != L'\0')
3158 {
3159 previous = wstr;
3160#if SIZEOF_WCHAR_T == 2
3161 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3162 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3163 {
3164 buf[0] = wstr[0];
3165 buf[1] = wstr[1];
3166 wstr += 2;
3167 }
3168 else {
3169 buf[0] = *wstr;
3170 buf[1] = 0;
3171 wstr++;
3172 }
3173#else
3174 buf[0] = *wstr;
3175 wstr++;
3176#endif
3177 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003178 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003179 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003180 }
3181
3182 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003183 return 0;
3184}
3185
Victor Stinner1b579672011-12-17 05:47:23 +01003186static int
3187locale_error_handler(const char *errors, int *surrogateescape)
3188{
3189 if (errors == NULL) {
3190 *surrogateescape = 0;
3191 return 0;
3192 }
3193
3194 if (strcmp(errors, "strict") == 0) {
3195 *surrogateescape = 0;
3196 return 0;
3197 }
3198 if (strcmp(errors, "surrogateescape") == 0) {
3199 *surrogateescape = 1;
3200 return 0;
3201 }
3202 PyErr_Format(PyExc_ValueError,
3203 "only 'strict' and 'surrogateescape' error handlers "
3204 "are supported, not '%s'",
3205 errors);
3206 return -1;
3207}
3208
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003209PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003210PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003211{
3212 Py_ssize_t wlen, wlen2;
3213 wchar_t *wstr;
3214 PyObject *bytes = NULL;
3215 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003216 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003217 PyObject *exc;
3218 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003219 int surrogateescape;
3220
3221 if (locale_error_handler(errors, &surrogateescape) < 0)
3222 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003223
3224 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3225 if (wstr == NULL)
3226 return NULL;
3227
3228 wlen2 = wcslen(wstr);
3229 if (wlen2 != wlen) {
3230 PyMem_Free(wstr);
3231 PyErr_SetString(PyExc_TypeError, "embedded null character");
3232 return NULL;
3233 }
3234
3235 if (surrogateescape) {
3236 /* locale encoding with surrogateescape */
3237 char *str;
3238
3239 str = _Py_wchar2char(wstr, &error_pos);
3240 if (str == NULL) {
3241 if (error_pos == (size_t)-1) {
3242 PyErr_NoMemory();
3243 PyMem_Free(wstr);
3244 return NULL;
3245 }
3246 else {
3247 goto encode_error;
3248 }
3249 }
3250 PyMem_Free(wstr);
3251
3252 bytes = PyBytes_FromString(str);
3253 PyMem_Free(str);
3254 }
3255 else {
3256 size_t len, len2;
3257
3258 len = wcstombs(NULL, wstr, 0);
3259 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003260 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003261 goto encode_error;
3262 }
3263
3264 bytes = PyBytes_FromStringAndSize(NULL, len);
3265 if (bytes == NULL) {
3266 PyMem_Free(wstr);
3267 return NULL;
3268 }
3269
3270 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3271 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003272 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003273 goto encode_error;
3274 }
3275 PyMem_Free(wstr);
3276 }
3277 return bytes;
3278
3279encode_error:
3280 errmsg = strerror(errno);
3281 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003282
3283 if (error_pos == (size_t)-1)
3284 error_pos = wcstombs_errorpos(wstr);
3285
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003286 PyMem_Free(wstr);
3287 Py_XDECREF(bytes);
3288
Victor Stinner2f197072011-12-17 07:08:30 +01003289 if (errmsg != NULL) {
3290 size_t errlen;
3291 wstr = _Py_char2wchar(errmsg, &errlen);
3292 if (wstr != NULL) {
3293 reason = PyUnicode_FromWideChar(wstr, errlen);
3294 PyMem_Free(wstr);
3295 } else
3296 errmsg = NULL;
3297 }
3298 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003299 reason = PyUnicode_FromString(
3300 "wcstombs() encountered an unencodable "
3301 "wide character");
3302 if (reason == NULL)
3303 return NULL;
3304
3305 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3306 "locale", unicode,
3307 (Py_ssize_t)error_pos,
3308 (Py_ssize_t)(error_pos+1),
3309 reason);
3310 Py_DECREF(reason);
3311 if (exc != NULL) {
3312 PyCodec_StrictErrors(exc);
3313 Py_XDECREF(exc);
3314 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003315 return NULL;
3316}
3317
Victor Stinnerad158722010-10-27 00:25:46 +00003318PyObject *
3319PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003320{
Victor Stinner99b95382011-07-04 14:23:54 +02003321#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003322 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003323#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003324 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003325#else
Victor Stinner793b5312011-04-27 00:24:21 +02003326 PyInterpreterState *interp = PyThreadState_GET()->interp;
3327 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3328 cannot use it to encode and decode filenames before it is loaded. Load
3329 the Python codec requires to encode at least its own filename. Use the C
3330 version of the locale codec until the codec registry is initialized and
3331 the Python codec is loaded.
3332
3333 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3334 cannot only rely on it: check also interp->fscodec_initialized for
3335 subinterpreters. */
3336 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003337 return PyUnicode_AsEncodedString(unicode,
3338 Py_FileSystemDefaultEncoding,
3339 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003340 }
3341 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003342 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003343 }
Victor Stinnerad158722010-10-27 00:25:46 +00003344#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003345}
3346
Alexander Belopolsky40018472011-02-26 01:02:56 +00003347PyObject *
3348PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003349 const char *encoding,
3350 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003351{
3352 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003353 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003354
Guido van Rossumd57fd912000-03-10 22:53:23 +00003355 if (!PyUnicode_Check(unicode)) {
3356 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003357 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003358 }
Fred Drakee4315f52000-05-09 19:53:39 +00003359
Fred Drakee4315f52000-05-09 19:53:39 +00003360 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003361 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003362 if ((strcmp(lower, "utf-8") == 0) ||
3363 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003364 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003365 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003366 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003367 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003368 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003369 }
Victor Stinner37296e82010-06-10 13:36:23 +00003370 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003371 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003372 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003373 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003374#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003375 else if (strcmp(lower, "mbcs") == 0)
3376 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003377#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003378 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003379 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003380 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003381
3382 /* Encode via the codec registry */
3383 v = PyCodec_Encode(unicode, encoding, errors);
3384 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003385 return NULL;
3386
3387 /* The normal path */
3388 if (PyBytes_Check(v))
3389 return v;
3390
3391 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003392 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003393 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003394 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003395
3396 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3397 "encoder %s returned bytearray instead of bytes",
3398 encoding);
3399 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003400 Py_DECREF(v);
3401 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003402 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003403
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003404 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3405 Py_DECREF(v);
3406 return b;
3407 }
3408
3409 PyErr_Format(PyExc_TypeError,
3410 "encoder did not return a bytes object (type=%.400s)",
3411 Py_TYPE(v)->tp_name);
3412 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003413 return NULL;
3414}
3415
Alexander Belopolsky40018472011-02-26 01:02:56 +00003416PyObject *
3417PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003418 const char *encoding,
3419 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003420{
3421 PyObject *v;
3422
3423 if (!PyUnicode_Check(unicode)) {
3424 PyErr_BadArgument();
3425 goto onError;
3426 }
3427
3428 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003429 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003430
3431 /* Encode via the codec registry */
3432 v = PyCodec_Encode(unicode, encoding, errors);
3433 if (v == NULL)
3434 goto onError;
3435 if (!PyUnicode_Check(v)) {
3436 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003437 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003438 Py_TYPE(v)->tp_name);
3439 Py_DECREF(v);
3440 goto onError;
3441 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003442 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003443
Benjamin Peterson29060642009-01-31 22:14:21 +00003444 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003445 return NULL;
3446}
3447
Victor Stinner2f197072011-12-17 07:08:30 +01003448static size_t
3449mbstowcs_errorpos(const char *str, size_t len)
3450{
3451#ifdef HAVE_MBRTOWC
3452 const char *start = str;
3453 mbstate_t mbs;
3454 size_t converted;
3455 wchar_t ch;
3456
3457 memset(&mbs, 0, sizeof mbs);
3458 while (len)
3459 {
3460 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3461 if (converted == 0)
3462 /* Reached end of string */
3463 break;
3464 if (converted == (size_t)-1 || converted == (size_t)-2) {
3465 /* Conversion error or incomplete character */
3466 return str - start;
3467 }
3468 else {
3469 str += converted;
3470 len -= converted;
3471 }
3472 }
3473 /* failed to find the undecodable byte sequence */
3474 return 0;
3475#endif
3476 return 0;
3477}
3478
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003479PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003480PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003481 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003482{
3483 wchar_t smallbuf[256];
3484 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3485 wchar_t *wstr;
3486 size_t wlen, wlen2;
3487 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003488 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003489 size_t error_pos;
3490 char *errmsg;
3491 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003492
3493 if (locale_error_handler(errors, &surrogateescape) < 0)
3494 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003495
3496 if (str[len] != '\0' || len != strlen(str)) {
3497 PyErr_SetString(PyExc_TypeError, "embedded null character");
3498 return NULL;
3499 }
3500
3501 if (surrogateescape)
3502 {
3503 wstr = _Py_char2wchar(str, &wlen);
3504 if (wstr == NULL) {
3505 if (wlen == (size_t)-1)
3506 PyErr_NoMemory();
3507 else
3508 PyErr_SetFromErrno(PyExc_OSError);
3509 return NULL;
3510 }
3511
3512 unicode = PyUnicode_FromWideChar(wstr, wlen);
3513 PyMem_Free(wstr);
3514 }
3515 else {
3516#ifndef HAVE_BROKEN_MBSTOWCS
3517 wlen = mbstowcs(NULL, str, 0);
3518#else
3519 wlen = len;
3520#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003521 if (wlen == (size_t)-1)
3522 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003523 if (wlen+1 <= smallbuf_len) {
3524 wstr = smallbuf;
3525 }
3526 else {
3527 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3528 return PyErr_NoMemory();
3529
3530 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3531 if (!wstr)
3532 return PyErr_NoMemory();
3533 }
3534
3535 /* This shouldn't fail now */
3536 wlen2 = mbstowcs(wstr, str, wlen+1);
3537 if (wlen2 == (size_t)-1) {
3538 if (wstr != smallbuf)
3539 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003540 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003541 }
3542#ifdef HAVE_BROKEN_MBSTOWCS
3543 assert(wlen2 == wlen);
3544#endif
3545 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3546 if (wstr != smallbuf)
3547 PyMem_Free(wstr);
3548 }
3549 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003550
3551decode_error:
3552 errmsg = strerror(errno);
3553 assert(errmsg != NULL);
3554
3555 error_pos = mbstowcs_errorpos(str, len);
3556 if (errmsg != NULL) {
3557 size_t errlen;
3558 wstr = _Py_char2wchar(errmsg, &errlen);
3559 if (wstr != NULL) {
3560 reason = PyUnicode_FromWideChar(wstr, errlen);
3561 PyMem_Free(wstr);
3562 } else
3563 errmsg = NULL;
3564 }
3565 if (errmsg == NULL)
3566 reason = PyUnicode_FromString(
3567 "mbstowcs() encountered an invalid multibyte sequence");
3568 if (reason == NULL)
3569 return NULL;
3570
3571 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3572 "locale", str, len,
3573 (Py_ssize_t)error_pos,
3574 (Py_ssize_t)(error_pos+1),
3575 reason);
3576 Py_DECREF(reason);
3577 if (exc != NULL) {
3578 PyCodec_StrictErrors(exc);
3579 Py_XDECREF(exc);
3580 }
3581 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003582}
3583
3584PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003585PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003586{
3587 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003588 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003589}
3590
3591
3592PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003593PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003594 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003595 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3596}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003597
Christian Heimes5894ba72007-11-04 11:43:14 +00003598PyObject*
3599PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3600{
Victor Stinner99b95382011-07-04 14:23:54 +02003601#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003602 return PyUnicode_DecodeMBCS(s, size, NULL);
3603#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003604 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003605#else
Victor Stinner793b5312011-04-27 00:24:21 +02003606 PyInterpreterState *interp = PyThreadState_GET()->interp;
3607 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3608 cannot use it to encode and decode filenames before it is loaded. Load
3609 the Python codec requires to encode at least its own filename. Use the C
3610 version of the locale codec until the codec registry is initialized and
3611 the Python codec is loaded.
3612
3613 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3614 cannot only rely on it: check also interp->fscodec_initialized for
3615 subinterpreters. */
3616 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003617 return PyUnicode_Decode(s, size,
3618 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003619 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003620 }
3621 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003622 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003623 }
Victor Stinnerad158722010-10-27 00:25:46 +00003624#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003625}
3626
Martin v. Löwis011e8422009-05-05 04:43:17 +00003627
3628int
Antoine Pitrou13348842012-01-29 18:36:34 +01003629_PyUnicode_HasNULChars(PyObject* s)
3630{
3631 static PyObject *nul = NULL;
3632
3633 if (nul == NULL)
3634 nul = PyUnicode_FromStringAndSize("\0", 1);
3635 if (nul == NULL)
3636 return -1;
3637 return PyUnicode_Contains(s, nul);
3638}
3639
3640
3641int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003642PyUnicode_FSConverter(PyObject* arg, void* addr)
3643{
3644 PyObject *output = NULL;
3645 Py_ssize_t size;
3646 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003647 if (arg == NULL) {
3648 Py_DECREF(*(PyObject**)addr);
3649 return 1;
3650 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003651 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003652 output = arg;
3653 Py_INCREF(output);
3654 }
3655 else {
3656 arg = PyUnicode_FromObject(arg);
3657 if (!arg)
3658 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003659 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003660 Py_DECREF(arg);
3661 if (!output)
3662 return 0;
3663 if (!PyBytes_Check(output)) {
3664 Py_DECREF(output);
3665 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3666 return 0;
3667 }
3668 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003669 size = PyBytes_GET_SIZE(output);
3670 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003671 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003672 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003673 Py_DECREF(output);
3674 return 0;
3675 }
3676 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003677 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003678}
3679
3680
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003681int
3682PyUnicode_FSDecoder(PyObject* arg, void* addr)
3683{
3684 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003685 if (arg == NULL) {
3686 Py_DECREF(*(PyObject**)addr);
3687 return 1;
3688 }
3689 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003690 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003691 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003692 output = arg;
3693 Py_INCREF(output);
3694 }
3695 else {
3696 arg = PyBytes_FromObject(arg);
3697 if (!arg)
3698 return 0;
3699 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3700 PyBytes_GET_SIZE(arg));
3701 Py_DECREF(arg);
3702 if (!output)
3703 return 0;
3704 if (!PyUnicode_Check(output)) {
3705 Py_DECREF(output);
3706 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3707 return 0;
3708 }
3709 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003710 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003711 Py_DECREF(output);
3712 return 0;
3713 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003714 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003715 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003716 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3717 Py_DECREF(output);
3718 return 0;
3719 }
3720 *(PyObject**)addr = output;
3721 return Py_CLEANUP_SUPPORTED;
3722}
3723
3724
Martin v. Löwis5b222132007-06-10 09:51:05 +00003725char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003726PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003727{
Christian Heimesf3863112007-11-22 07:46:41 +00003728 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003729
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003730 if (!PyUnicode_Check(unicode)) {
3731 PyErr_BadArgument();
3732 return NULL;
3733 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003734 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003735 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003736
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003737 if (PyUnicode_UTF8(unicode) == NULL) {
3738 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003739 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3740 if (bytes == NULL)
3741 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003742 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3743 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003744 Py_DECREF(bytes);
3745 return NULL;
3746 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003747 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3748 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3749 PyBytes_AS_STRING(bytes),
3750 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003751 Py_DECREF(bytes);
3752 }
3753
3754 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003755 *psize = PyUnicode_UTF8_LENGTH(unicode);
3756 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003757}
3758
3759char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003760PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003761{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003762 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3763}
3764
3765#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003766static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003767#endif
3768
3769
3770Py_UNICODE *
3771PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3772{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003773 const unsigned char *one_byte;
3774#if SIZEOF_WCHAR_T == 4
3775 const Py_UCS2 *two_bytes;
3776#else
3777 const Py_UCS4 *four_bytes;
3778 const Py_UCS4 *ucs4_end;
3779 Py_ssize_t num_surrogates;
3780#endif
3781 wchar_t *w;
3782 wchar_t *wchar_end;
3783
3784 if (!PyUnicode_Check(unicode)) {
3785 PyErr_BadArgument();
3786 return NULL;
3787 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003788 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003789 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003790 assert(_PyUnicode_KIND(unicode) != 0);
3791 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003792
3793#ifdef Py_DEBUG
3794 ++unicode_as_unicode_calls;
3795#endif
3796
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003797 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003798#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003799 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3800 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003801 num_surrogates = 0;
3802
3803 for (; four_bytes < ucs4_end; ++four_bytes) {
3804 if (*four_bytes > 0xFFFF)
3805 ++num_surrogates;
3806 }
3807
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003808 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3809 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3810 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003811 PyErr_NoMemory();
3812 return NULL;
3813 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003814 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003815
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003816 w = _PyUnicode_WSTR(unicode);
3817 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3818 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003819 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3820 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003821 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003822 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003823 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3824 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003825 }
3826 else
3827 *w = *four_bytes;
3828
3829 if (w > wchar_end) {
3830 assert(0 && "Miscalculated string end");
3831 }
3832 }
3833 *w = 0;
3834#else
3835 /* sizeof(wchar_t) == 4 */
3836 Py_FatalError("Impossible unicode object state, wstr and str "
3837 "should share memory already.");
3838 return NULL;
3839#endif
3840 }
3841 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003842 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3843 (_PyUnicode_LENGTH(unicode) + 1));
3844 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003845 PyErr_NoMemory();
3846 return NULL;
3847 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003848 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3849 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3850 w = _PyUnicode_WSTR(unicode);
3851 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003852
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003853 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3854 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003855 for (; w < wchar_end; ++one_byte, ++w)
3856 *w = *one_byte;
3857 /* null-terminate the wstr */
3858 *w = 0;
3859 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003860 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003861#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003862 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003863 for (; w < wchar_end; ++two_bytes, ++w)
3864 *w = *two_bytes;
3865 /* null-terminate the wstr */
3866 *w = 0;
3867#else
3868 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003869 PyObject_FREE(_PyUnicode_WSTR(unicode));
3870 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003871 Py_FatalError("Impossible unicode object state, wstr "
3872 "and str should share memory already.");
3873 return NULL;
3874#endif
3875 }
3876 else {
3877 assert(0 && "This should never happen.");
3878 }
3879 }
3880 }
3881 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003882 *size = PyUnicode_WSTR_LENGTH(unicode);
3883 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003884}
3885
Alexander Belopolsky40018472011-02-26 01:02:56 +00003886Py_UNICODE *
3887PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003888{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003889 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003890}
3891
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003892
Alexander Belopolsky40018472011-02-26 01:02:56 +00003893Py_ssize_t
3894PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003895{
3896 if (!PyUnicode_Check(unicode)) {
3897 PyErr_BadArgument();
3898 goto onError;
3899 }
3900 return PyUnicode_GET_SIZE(unicode);
3901
Benjamin Peterson29060642009-01-31 22:14:21 +00003902 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003903 return -1;
3904}
3905
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003906Py_ssize_t
3907PyUnicode_GetLength(PyObject *unicode)
3908{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003909 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003910 PyErr_BadArgument();
3911 return -1;
3912 }
3913
3914 return PyUnicode_GET_LENGTH(unicode);
3915}
3916
3917Py_UCS4
3918PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3919{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003920 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3921 PyErr_BadArgument();
3922 return (Py_UCS4)-1;
3923 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003924 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003925 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003926 return (Py_UCS4)-1;
3927 }
3928 return PyUnicode_READ_CHAR(unicode, index);
3929}
3930
3931int
3932PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3933{
3934 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003935 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003936 return -1;
3937 }
Victor Stinner488fa492011-12-12 00:01:39 +01003938 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003939 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003940 PyErr_SetString(PyExc_IndexError, "string index out of range");
3941 return -1;
3942 }
Victor Stinner488fa492011-12-12 00:01:39 +01003943 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003944 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003945 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3946 index, ch);
3947 return 0;
3948}
3949
Alexander Belopolsky40018472011-02-26 01:02:56 +00003950const char *
3951PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003952{
Victor Stinner42cb4622010-09-01 19:39:01 +00003953 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003954}
3955
Victor Stinner554f3f02010-06-16 23:33:54 +00003956/* create or adjust a UnicodeDecodeError */
3957static void
3958make_decode_exception(PyObject **exceptionObject,
3959 const char *encoding,
3960 const char *input, Py_ssize_t length,
3961 Py_ssize_t startpos, Py_ssize_t endpos,
3962 const char *reason)
3963{
3964 if (*exceptionObject == NULL) {
3965 *exceptionObject = PyUnicodeDecodeError_Create(
3966 encoding, input, length, startpos, endpos, reason);
3967 }
3968 else {
3969 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3970 goto onError;
3971 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3972 goto onError;
3973 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3974 goto onError;
3975 }
3976 return;
3977
3978onError:
3979 Py_DECREF(*exceptionObject);
3980 *exceptionObject = NULL;
3981}
3982
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003983/* error handling callback helper:
3984 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003985 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003986 and adjust various state variables.
3987 return 0 on success, -1 on error
3988*/
3989
Alexander Belopolsky40018472011-02-26 01:02:56 +00003990static int
3991unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003992 const char *encoding, const char *reason,
3993 const char **input, const char **inend, Py_ssize_t *startinpos,
3994 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003995 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003996{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003997 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003998
3999 PyObject *restuple = NULL;
4000 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004001 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004002 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004003 Py_ssize_t requiredsize;
4004 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004005 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004006 int res = -1;
4007
Victor Stinner596a6c42011-11-09 00:02:18 +01004008 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4009 outsize = PyUnicode_GET_LENGTH(*output);
4010 else
4011 outsize = _PyUnicode_WSTR_LENGTH(*output);
4012
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004013 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004014 *errorHandler = PyCodec_LookupError(errors);
4015 if (*errorHandler == NULL)
4016 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004017 }
4018
Victor Stinner554f3f02010-06-16 23:33:54 +00004019 make_decode_exception(exceptionObject,
4020 encoding,
4021 *input, *inend - *input,
4022 *startinpos, *endinpos,
4023 reason);
4024 if (*exceptionObject == NULL)
4025 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004026
4027 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4028 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004029 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004030 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004031 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004032 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004033 }
4034 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004035 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004036 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004037 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004038
4039 /* Copy back the bytes variables, which might have been modified by the
4040 callback */
4041 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4042 if (!inputobj)
4043 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004044 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004045 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004046 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004047 *input = PyBytes_AS_STRING(inputobj);
4048 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004049 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004050 /* we can DECREF safely, as the exception has another reference,
4051 so the object won't go away. */
4052 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004053
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004054 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004055 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004056 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004057 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4058 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004059 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004060
Victor Stinner596a6c42011-11-09 00:02:18 +01004061 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4062 /* need more space? (at least enough for what we
4063 have+the replacement+the rest of the string (starting
4064 at the new input position), so we won't have to check space
4065 when there are no errors in the rest of the string) */
4066 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4067 requiredsize = *outpos + replen + insize-newpos;
4068 if (requiredsize > outsize) {
4069 if (requiredsize<2*outsize)
4070 requiredsize = 2*outsize;
4071 if (unicode_resize(output, requiredsize) < 0)
4072 goto onError;
4073 }
4074 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004075 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01004076 copy_characters(*output, *outpos, repunicode, 0, replen);
4077 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004078 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004079 else {
4080 wchar_t *repwstr;
4081 Py_ssize_t repwlen;
4082 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4083 if (repwstr == NULL)
4084 goto onError;
4085 /* need more space? (at least enough for what we
4086 have+the replacement+the rest of the string (starting
4087 at the new input position), so we won't have to check space
4088 when there are no errors in the rest of the string) */
4089 requiredsize = *outpos + repwlen + insize-newpos;
4090 if (requiredsize > outsize) {
4091 if (requiredsize < 2*outsize)
4092 requiredsize = 2*outsize;
4093 if (unicode_resize(output, requiredsize) < 0)
4094 goto onError;
4095 }
4096 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4097 *outpos += repwlen;
4098 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004099 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004100 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004101
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004102 /* we made it! */
4103 res = 0;
4104
Benjamin Peterson29060642009-01-31 22:14:21 +00004105 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004106 Py_XDECREF(restuple);
4107 return res;
4108}
4109
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004110/* --- UTF-7 Codec -------------------------------------------------------- */
4111
Antoine Pitrou244651a2009-05-04 18:56:13 +00004112/* See RFC2152 for details. We encode conservatively and decode liberally. */
4113
4114/* Three simple macros defining base-64. */
4115
4116/* Is c a base-64 character? */
4117
4118#define IS_BASE64(c) \
4119 (((c) >= 'A' && (c) <= 'Z') || \
4120 ((c) >= 'a' && (c) <= 'z') || \
4121 ((c) >= '0' && (c) <= '9') || \
4122 (c) == '+' || (c) == '/')
4123
4124/* given that c is a base-64 character, what is its base-64 value? */
4125
4126#define FROM_BASE64(c) \
4127 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4128 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4129 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4130 (c) == '+' ? 62 : 63)
4131
4132/* What is the base-64 character of the bottom 6 bits of n? */
4133
4134#define TO_BASE64(n) \
4135 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4136
4137/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4138 * decoded as itself. We are permissive on decoding; the only ASCII
4139 * byte not decoding to itself is the + which begins a base64
4140 * string. */
4141
4142#define DECODE_DIRECT(c) \
4143 ((c) <= 127 && (c) != '+')
4144
4145/* The UTF-7 encoder treats ASCII characters differently according to
4146 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4147 * the above). See RFC2152. This array identifies these different
4148 * sets:
4149 * 0 : "Set D"
4150 * alphanumeric and '(),-./:?
4151 * 1 : "Set O"
4152 * !"#$%&*;<=>@[]^_`{|}
4153 * 2 : "whitespace"
4154 * ht nl cr sp
4155 * 3 : special (must be base64 encoded)
4156 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4157 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004158
Tim Petersced69f82003-09-16 20:30:58 +00004159static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004160char utf7_category[128] = {
4161/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4162 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4163/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4164 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4165/* sp ! " # $ % & ' ( ) * + , - . / */
4166 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4167/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4168 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4169/* @ A B C D E F G H I J K L M N O */
4170 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4171/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4172 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4173/* ` a b c d e f g h i j k l m n o */
4174 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4175/* p q r s t u v w x y z { | } ~ del */
4176 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004177};
4178
Antoine Pitrou244651a2009-05-04 18:56:13 +00004179/* ENCODE_DIRECT: this character should be encoded as itself. The
4180 * answer depends on whether we are encoding set O as itself, and also
4181 * on whether we are encoding whitespace as itself. RFC2152 makes it
4182 * clear that the answers to these questions vary between
4183 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004184
Antoine Pitrou244651a2009-05-04 18:56:13 +00004185#define ENCODE_DIRECT(c, directO, directWS) \
4186 ((c) < 128 && (c) > 0 && \
4187 ((utf7_category[(c)] == 0) || \
4188 (directWS && (utf7_category[(c)] == 2)) || \
4189 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004190
Alexander Belopolsky40018472011-02-26 01:02:56 +00004191PyObject *
4192PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004193 Py_ssize_t size,
4194 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004195{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004196 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4197}
4198
Antoine Pitrou244651a2009-05-04 18:56:13 +00004199/* The decoder. The only state we preserve is our read position,
4200 * i.e. how many characters we have consumed. So if we end in the
4201 * middle of a shift sequence we have to back off the read position
4202 * and the output to the beginning of the sequence, otherwise we lose
4203 * all the shift state (seen bits, number of bits seen, high
4204 * surrogate). */
4205
Alexander Belopolsky40018472011-02-26 01:02:56 +00004206PyObject *
4207PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004208 Py_ssize_t size,
4209 const char *errors,
4210 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004211{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004212 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004213 Py_ssize_t startinpos;
4214 Py_ssize_t endinpos;
4215 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004216 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004217 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004218 const char *errmsg = "";
4219 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004220 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004221 unsigned int base64bits = 0;
4222 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004223 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004224 PyObject *errorHandler = NULL;
4225 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004226
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004227 /* Start off assuming it's all ASCII. Widen later as necessary. */
4228 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004229 if (!unicode)
4230 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004231 if (size == 0) {
4232 if (consumed)
4233 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004234 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004235 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004236
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004237 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004238 e = s + size;
4239
4240 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004241 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004242 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004243 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004244
Antoine Pitrou244651a2009-05-04 18:56:13 +00004245 if (inShift) { /* in a base-64 section */
4246 if (IS_BASE64(ch)) { /* consume a base-64 character */
4247 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4248 base64bits += 6;
4249 s++;
4250 if (base64bits >= 16) {
4251 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004252 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004253 base64bits -= 16;
4254 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4255 if (surrogate) {
4256 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004257 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4258 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004259 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4260 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004261 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004262 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004263 }
4264 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004265 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4266 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004267 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004268 }
4269 }
Victor Stinner551ac952011-11-29 22:58:13 +01004270 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004271 /* first surrogate */
4272 surrogate = outCh;
4273 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004274 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004275 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4276 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004277 }
4278 }
4279 }
4280 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004281 inShift = 0;
4282 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004283 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004284 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4285 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004286 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004287 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004288 if (base64bits > 0) { /* left-over bits */
4289 if (base64bits >= 6) {
4290 /* We've seen at least one base-64 character */
4291 errmsg = "partial character in shift sequence";
4292 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004293 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004294 else {
4295 /* Some bits remain; they should be zero */
4296 if (base64buffer != 0) {
4297 errmsg = "non-zero padding bits in shift sequence";
4298 goto utf7Error;
4299 }
4300 }
4301 }
4302 if (ch != '-') {
4303 /* '-' is absorbed; other terminating
4304 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004305 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4306 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004307 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004308 }
4309 }
4310 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004311 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004312 s++; /* consume '+' */
4313 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004314 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004315 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4316 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004317 }
4318 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004319 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004320 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004321 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004322 }
4323 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004324 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004325 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4326 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004327 s++;
4328 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004329 else {
4330 startinpos = s-starts;
4331 s++;
4332 errmsg = "unexpected special character";
4333 goto utf7Error;
4334 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004335 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004336utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004337 endinpos = s-starts;
4338 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004339 errors, &errorHandler,
4340 "utf7", errmsg,
4341 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004342 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004343 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004344 }
4345
Antoine Pitrou244651a2009-05-04 18:56:13 +00004346 /* end of string */
4347
4348 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4349 /* if we're in an inconsistent state, that's an error */
4350 if (surrogate ||
4351 (base64bits >= 6) ||
4352 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004353 endinpos = size;
4354 if (unicode_decode_call_errorhandler(
4355 errors, &errorHandler,
4356 "utf7", "unterminated shift sequence",
4357 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004358 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004359 goto onError;
4360 if (s < e)
4361 goto restart;
4362 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004363 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004364
4365 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004366 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004367 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004368 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004369 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004370 }
4371 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004372 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004373 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004374 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004375
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004376 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004377 goto onError;
4378
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004379 Py_XDECREF(errorHandler);
4380 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004381 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004382
Benjamin Peterson29060642009-01-31 22:14:21 +00004383 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004384 Py_XDECREF(errorHandler);
4385 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004386 Py_DECREF(unicode);
4387 return NULL;
4388}
4389
4390
Alexander Belopolsky40018472011-02-26 01:02:56 +00004391PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004392_PyUnicode_EncodeUTF7(PyObject *str,
4393 int base64SetO,
4394 int base64WhiteSpace,
4395 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004396{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004397 int kind;
4398 void *data;
4399 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004400 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004401 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004402 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004403 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004404 unsigned int base64bits = 0;
4405 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004406 char * out;
4407 char * start;
4408
Benjamin Petersonbac79492012-01-14 13:34:47 -05004409 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004410 return NULL;
4411 kind = PyUnicode_KIND(str);
4412 data = PyUnicode_DATA(str);
4413 len = PyUnicode_GET_LENGTH(str);
4414
4415 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004416 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004417
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004418 /* It might be possible to tighten this worst case */
4419 allocated = 8 * len;
4420 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004421 return PyErr_NoMemory();
4422
Antoine Pitrou244651a2009-05-04 18:56:13 +00004423 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004424 if (v == NULL)
4425 return NULL;
4426
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004427 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004428 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004429 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004430
Antoine Pitrou244651a2009-05-04 18:56:13 +00004431 if (inShift) {
4432 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4433 /* shifting out */
4434 if (base64bits) { /* output remaining bits */
4435 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4436 base64buffer = 0;
4437 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004438 }
4439 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004440 /* Characters not in the BASE64 set implicitly unshift the sequence
4441 so no '-' is required, except if the character is itself a '-' */
4442 if (IS_BASE64(ch) || ch == '-') {
4443 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004444 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004445 *out++ = (char) ch;
4446 }
4447 else {
4448 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004449 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004450 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004451 else { /* not in a shift sequence */
4452 if (ch == '+') {
4453 *out++ = '+';
4454 *out++ = '-';
4455 }
4456 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4457 *out++ = (char) ch;
4458 }
4459 else {
4460 *out++ = '+';
4461 inShift = 1;
4462 goto encode_char;
4463 }
4464 }
4465 continue;
4466encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004467 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004468 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004469
Antoine Pitrou244651a2009-05-04 18:56:13 +00004470 /* code first surrogate */
4471 base64bits += 16;
4472 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4473 while (base64bits >= 6) {
4474 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4475 base64bits -= 6;
4476 }
4477 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004478 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004479 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004480 base64bits += 16;
4481 base64buffer = (base64buffer << 16) | ch;
4482 while (base64bits >= 6) {
4483 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4484 base64bits -= 6;
4485 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004486 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004487 if (base64bits)
4488 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4489 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004490 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004491 if (_PyBytes_Resize(&v, out - start) < 0)
4492 return NULL;
4493 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004494}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004495PyObject *
4496PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4497 Py_ssize_t size,
4498 int base64SetO,
4499 int base64WhiteSpace,
4500 const char *errors)
4501{
4502 PyObject *result;
4503 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4504 if (tmp == NULL)
4505 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004506 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004507 base64WhiteSpace, errors);
4508 Py_DECREF(tmp);
4509 return result;
4510}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004511
Antoine Pitrou244651a2009-05-04 18:56:13 +00004512#undef IS_BASE64
4513#undef FROM_BASE64
4514#undef TO_BASE64
4515#undef DECODE_DIRECT
4516#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004517
Guido van Rossumd57fd912000-03-10 22:53:23 +00004518/* --- UTF-8 Codec -------------------------------------------------------- */
4519
Tim Petersced69f82003-09-16 20:30:58 +00004520static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004521char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004522 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4523 illegal prefix. See RFC 3629 for details */
4524 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4525 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004526 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004527 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4528 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4529 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4530 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004531 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4532 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 +00004533 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4534 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004535 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4536 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4537 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4538 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4539 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 +00004540};
4541
Alexander Belopolsky40018472011-02-26 01:02:56 +00004542PyObject *
4543PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004544 Py_ssize_t size,
4545 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004546{
Walter Dörwald69652032004-09-07 20:24:22 +00004547 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4548}
4549
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004550#include "stringlib/ucs1lib.h"
4551#include "stringlib/codecs.h"
4552#include "stringlib/undef.h"
4553
4554#include "stringlib/ucs2lib.h"
4555#include "stringlib/codecs.h"
4556#include "stringlib/undef.h"
4557
4558#include "stringlib/ucs4lib.h"
4559#include "stringlib/codecs.h"
4560#include "stringlib/undef.h"
4561
Antoine Pitrouab868312009-01-10 15:40:25 +00004562/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4563#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4564
4565/* Mask to quickly check whether a C 'long' contains a
4566 non-ASCII, UTF8-encoded char. */
4567#if (SIZEOF_LONG == 8)
4568# define ASCII_CHAR_MASK 0x8080808080808080L
4569#elif (SIZEOF_LONG == 4)
4570# define ASCII_CHAR_MASK 0x80808080L
4571#else
4572# error C 'long' size should be either 4 or 8!
4573#endif
4574
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004575/* Scans a UTF-8 string and returns the maximum character to be expected
4576 and the size of the decoded unicode string.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004577
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004578 This function doesn't check for errors, these checks are performed in
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004579 PyUnicode_DecodeUTF8Stateful.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004580 */
4581static Py_UCS4
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004582utf8_scanner(const unsigned char *p, Py_ssize_t string_size, Py_ssize_t *unicode_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004583{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004584 Py_ssize_t char_count = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004585 const unsigned char *end = p + string_size;
4586 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004587
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004588 assert(unicode_size != NULL);
4589
4590 /* By having a cascade of independent loops which fallback onto each
4591 other, we minimize the amount of work done in the average loop
4592 iteration, and we also maximize the CPU's ability to predict
4593 branches correctly (because a given condition will have always the
4594 same boolean outcome except perhaps in the last iteration of the
4595 corresponding loop).
4596 In the general case this brings us rather close to decoding
4597 performance pre-PEP 393, despite the two-pass decoding.
4598
4599 Note that the pure ASCII loop is not duplicated once a non-ASCII
4600 character has been encountered. It is actually a pessimization (by
4601 a significant factor) to use this loop on text with many non-ASCII
4602 characters, and it is important to avoid bad performance on valid
4603 utf-8 data (invalid utf-8 being a different can of worms).
4604 */
4605
4606 /* ASCII */
4607 for (; p < end; ++p) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004608 /* Only check value if it's not a ASCII char... */
4609 if (*p < 0x80) {
4610 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4611 an explanation. */
4612 if (!((size_t) p & LONG_PTR_MASK)) {
4613 /* Help register allocation */
4614 register const unsigned char *_p = p;
4615 while (_p < aligned_end) {
4616 unsigned long value = *(unsigned long *) _p;
4617 if (value & ASCII_CHAR_MASK)
4618 break;
4619 _p += SIZEOF_LONG;
4620 char_count += SIZEOF_LONG;
4621 }
4622 p = _p;
4623 if (p == end)
4624 break;
4625 }
4626 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004627 if (*p < 0x80)
4628 ++char_count;
4629 else
4630 goto _ucs1loop;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004631 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004632 *unicode_size = char_count;
4633 return 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004634
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004635_ucs1loop:
4636 for (; p < end; ++p) {
4637 if (*p < 0xc4)
4638 char_count += ((*p & 0xc0) != 0x80);
4639 else
4640 goto _ucs2loop;
4641 }
4642 *unicode_size = char_count;
4643 return 255;
4644
4645_ucs2loop:
4646 for (; p < end; ++p) {
4647 if (*p < 0xf0)
4648 char_count += ((*p & 0xc0) != 0x80);
4649 else
4650 goto _ucs4loop;
4651 }
4652 *unicode_size = char_count;
4653 return 65535;
4654
4655_ucs4loop:
4656 for (; p < end; ++p) {
4657 char_count += ((*p & 0xc0) != 0x80);
4658 }
4659 *unicode_size = char_count;
4660 return 65537;
4661}
4662
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004663/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
Victor Stinner785938e2011-12-11 20:09:03 +01004664 in case of errors. Implicit parameters: unicode, kind, data, onError.
4665 Potential resizing overallocates, so the result needs to shrink at the end.
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004666*/
Victor Stinner785938e2011-12-11 20:09:03 +01004667#define WRITE_MAYBE_FAIL(index, value) \
4668 do { \
4669 Py_ssize_t pos = index; \
4670 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4671 unicode_resize(&unicode, pos + pos/8) < 0) \
4672 goto onError; \
4673 if (unicode_putchar(&unicode, &pos, value) < 0) \
4674 goto onError; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004675 } while (0)
4676
Victor Stinnerbf6e5602011-12-12 01:53:47 +01004677static PyObject *
Victor Stinner785938e2011-12-11 20:09:03 +01004678decode_utf8_errors(const char *starts,
4679 Py_ssize_t size,
4680 const char *errors,
4681 Py_ssize_t *consumed,
4682 const char *s,
4683 PyObject *unicode,
4684 Py_ssize_t i)
Walter Dörwald69652032004-09-07 20:24:22 +00004685{
Guido van Rossumd57fd912000-03-10 22:53:23 +00004686 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004687 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004688 Py_ssize_t startinpos;
4689 Py_ssize_t endinpos;
Victor Stinner785938e2011-12-11 20:09:03 +01004690 const char *e = starts + size;
4691 const char *aligned_end;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004692 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004693 PyObject *errorHandler = NULL;
4694 PyObject *exc = NULL;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004695
Antoine Pitrouab868312009-01-10 15:40:25 +00004696 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004697
4698 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004699 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004700
4701 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004702 /* Fast path for runs of ASCII characters. Given that common UTF-8
4703 input will consist of an overwhelming majority of ASCII
4704 characters, we try to optimize for this case by checking
4705 as many characters as a C 'long' can contain.
4706 First, check if we can do an aligned read, as most CPUs have
4707 a penalty for unaligned reads.
4708 */
4709 if (!((size_t) s & LONG_PTR_MASK)) {
4710 /* Help register allocation */
4711 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004712 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004713 while (_s < aligned_end) {
4714 /* Read a whole long at a time (either 4 or 8 bytes),
4715 and do a fast unrolled copy if it only contains ASCII
4716 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004717 unsigned long value = *(unsigned long *) _s;
4718 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004719 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004720 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4721 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4722 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4723 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004724#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004725 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4726 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4727 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4728 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004729#endif
4730 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004731 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004732 }
4733 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004734 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004735 if (s == e)
4736 break;
4737 ch = (unsigned char)*s;
4738 }
4739 }
4740
4741 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004742 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004743 s++;
4744 continue;
4745 }
4746
4747 n = utf8_code_length[ch];
4748
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004749 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004750 if (consumed)
4751 break;
4752 else {
4753 errmsg = "unexpected end of data";
4754 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004755 endinpos = startinpos+1;
4756 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4757 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004758 goto utf8Error;
4759 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004760 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004761
4762 switch (n) {
4763
4764 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004765 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004766 startinpos = s-starts;
4767 endinpos = startinpos+1;
4768 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004769
4770 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004771 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004772 startinpos = s-starts;
4773 endinpos = startinpos+1;
4774 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004775
4776 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004777 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004778 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004779 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004780 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004781 goto utf8Error;
4782 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004783 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004784 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004785 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004786 break;
4787
4788 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004789 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4790 will result in surrogates in range d800-dfff. Surrogates are
4791 not valid UTF-8 so they are rejected.
4792 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4793 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004794 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004795 (s[2] & 0xc0) != 0x80 ||
4796 ((unsigned char)s[0] == 0xE0 &&
4797 (unsigned char)s[1] < 0xA0) ||
4798 ((unsigned char)s[0] == 0xED &&
4799 (unsigned char)s[1] > 0x9F)) {
4800 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004801 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004802 endinpos = startinpos + 1;
4803
4804 /* if s[1] first two bits are 1 and 0, then the invalid
4805 continuation byte is s[2], so increment endinpos by 1,
4806 if not, s[1] is invalid and endinpos doesn't need to
4807 be incremented. */
4808 if ((s[1] & 0xC0) == 0x80)
4809 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004810 goto utf8Error;
4811 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004812 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004813 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004814 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004815 break;
4816
4817 case 4:
4818 if ((s[1] & 0xc0) != 0x80 ||
4819 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004820 (s[3] & 0xc0) != 0x80 ||
4821 ((unsigned char)s[0] == 0xF0 &&
4822 (unsigned char)s[1] < 0x90) ||
4823 ((unsigned char)s[0] == 0xF4 &&
4824 (unsigned char)s[1] > 0x8F)) {
4825 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004826 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004827 endinpos = startinpos + 1;
4828 if ((s[1] & 0xC0) == 0x80) {
4829 endinpos++;
4830 if ((s[2] & 0xC0) == 0x80)
4831 endinpos++;
4832 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004833 goto utf8Error;
4834 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004835 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004836 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01004837 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Ezio Melotti57221d02010-07-01 07:32:02 +00004838
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004839 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004840 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004841 }
4842 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004843 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004844
Benjamin Peterson29060642009-01-31 22:14:21 +00004845 utf8Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00004846 if (unicode_decode_call_errorhandler(
4847 errors, &errorHandler,
Victor Stinnercbe01342012-02-14 01:17:45 +01004848 "utf-8", errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00004849 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004850 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004851 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004852 /* Update data because unicode_decode_call_errorhandler might have
4853 re-created or resized the unicode object. */
Benjamin Peterson29060642009-01-31 22:14:21 +00004854 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004855 }
Walter Dörwald69652032004-09-07 20:24:22 +00004856 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004857 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004858
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004859 /* Adjust length and ready string when it contained errors and
4860 is of the old resizable kind. */
Victor Stinner785938e2011-12-11 20:09:03 +01004861 if (unicode_resize(&unicode, i) < 0)
4862 goto onError;
4863 unicode_adjust_maxchar(&unicode);
4864 if (unicode == NULL)
4865 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004866
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004867 Py_XDECREF(errorHandler);
4868 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004869 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004870 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004871
Benjamin Peterson29060642009-01-31 22:14:21 +00004872 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004873 Py_XDECREF(errorHandler);
4874 Py_XDECREF(exc);
Victor Stinner785938e2011-12-11 20:09:03 +01004875 Py_XDECREF(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004876 return NULL;
4877}
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004878#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004879
Victor Stinner785938e2011-12-11 20:09:03 +01004880PyObject *
4881PyUnicode_DecodeUTF8Stateful(const char *s,
4882 Py_ssize_t size,
4883 const char *errors,
4884 Py_ssize_t *consumed)
4885{
4886 Py_UCS4 maxchar = 0;
4887 Py_ssize_t unicode_size;
4888 int has_errors = 0;
4889 PyObject *unicode;
4890 int kind;
4891 void *data;
4892 const char *starts = s;
4893 const char *e;
4894 Py_ssize_t i;
4895
4896 if (size == 0) {
4897 if (consumed)
4898 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004899 Py_INCREF(unicode_empty);
4900 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004901 }
4902
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004903 maxchar = utf8_scanner((const unsigned char *)s, size, &unicode_size);
Victor Stinner785938e2011-12-11 20:09:03 +01004904
4905 /* When the string is ASCII only, just use memcpy and return.
4906 unicode_size may be != size if there is an incomplete UTF-8
4907 sequence at the end of the ASCII block. */
4908 if (maxchar < 128 && size == unicode_size) {
4909 if (consumed)
4910 *consumed = size;
Victor Stinnerab870212011-12-17 22:39:43 +01004911 return unicode_fromascii((const unsigned char *)s, size);
Victor Stinner785938e2011-12-11 20:09:03 +01004912 }
4913
4914 unicode = PyUnicode_New(unicode_size, maxchar);
4915 if (!unicode)
4916 return NULL;
4917 kind = PyUnicode_KIND(unicode);
4918 data = PyUnicode_DATA(unicode);
4919
4920 /* Unpack UTF-8 encoded data */
4921 i = 0;
4922 e = starts + size;
4923 switch (kind) {
4924 case PyUnicode_1BYTE_KIND:
4925 has_errors = ucs1lib_utf8_try_decode(s, e, (Py_UCS1 *) data, &s, &i);
4926 break;
4927 case PyUnicode_2BYTE_KIND:
4928 has_errors = ucs2lib_utf8_try_decode(s, e, (Py_UCS2 *) data, &s, &i);
4929 break;
4930 case PyUnicode_4BYTE_KIND:
4931 has_errors = ucs4lib_utf8_try_decode(s, e, (Py_UCS4 *) data, &s, &i);
4932 break;
4933 }
4934 if (!has_errors) {
4935 /* Ensure the unicode size calculation was correct */
4936 assert(i == unicode_size);
4937 assert(s == e);
4938 if (consumed)
4939 *consumed = size;
4940 return unicode;
4941 }
4942
4943 /* In case of errors, maxchar and size computation might be incorrect;
4944 code below refits and resizes as necessary. */
4945 return decode_utf8_errors(starts, size, errors, consumed, s, unicode, i);
4946}
4947
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004948#ifdef __APPLE__
4949
4950/* Simplified UTF-8 decoder using surrogateescape error handler,
4951 used to decode the command line arguments on Mac OS X. */
4952
4953wchar_t*
4954_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4955{
4956 int n;
4957 const char *e;
4958 wchar_t *unicode, *p;
4959
4960 /* Note: size will always be longer than the resulting Unicode
4961 character count */
4962 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4963 PyErr_NoMemory();
4964 return NULL;
4965 }
4966 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4967 if (!unicode)
4968 return NULL;
4969
4970 /* Unpack UTF-8 encoded data */
4971 p = unicode;
4972 e = s + size;
4973 while (s < e) {
4974 Py_UCS4 ch = (unsigned char)*s;
4975
4976 if (ch < 0x80) {
4977 *p++ = (wchar_t)ch;
4978 s++;
4979 continue;
4980 }
4981
4982 n = utf8_code_length[ch];
4983 if (s + n > e) {
4984 goto surrogateescape;
4985 }
4986
4987 switch (n) {
4988 case 0:
4989 case 1:
4990 goto surrogateescape;
4991
4992 case 2:
4993 if ((s[1] & 0xc0) != 0x80)
4994 goto surrogateescape;
4995 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4996 assert ((ch > 0x007F) && (ch <= 0x07FF));
4997 *p++ = (wchar_t)ch;
4998 break;
4999
5000 case 3:
5001 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
5002 will result in surrogates in range d800-dfff. Surrogates are
5003 not valid UTF-8 so they are rejected.
5004 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
5005 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
5006 if ((s[1] & 0xc0) != 0x80 ||
5007 (s[2] & 0xc0) != 0x80 ||
5008 ((unsigned char)s[0] == 0xE0 &&
5009 (unsigned char)s[1] < 0xA0) ||
5010 ((unsigned char)s[0] == 0xED &&
5011 (unsigned char)s[1] > 0x9F)) {
5012
5013 goto surrogateescape;
5014 }
5015 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
5016 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005017 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005018 break;
5019
5020 case 4:
5021 if ((s[1] & 0xc0) != 0x80 ||
5022 (s[2] & 0xc0) != 0x80 ||
5023 (s[3] & 0xc0) != 0x80 ||
5024 ((unsigned char)s[0] == 0xF0 &&
5025 (unsigned char)s[1] < 0x90) ||
5026 ((unsigned char)s[0] == 0xF4 &&
5027 (unsigned char)s[1] > 0x8F)) {
5028 goto surrogateescape;
5029 }
5030 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
5031 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01005032 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005033
5034#if SIZEOF_WCHAR_T == 4
5035 *p++ = (wchar_t)ch;
5036#else
5037 /* compute and append the two surrogates: */
Victor Stinner551ac952011-11-29 22:58:13 +01005038 *p++ = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5039 *p++ = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005040#endif
5041 break;
5042 }
5043 s += n;
5044 continue;
5045
5046 surrogateescape:
5047 *p++ = 0xDC00 + ch;
5048 s++;
5049 }
5050 *p = L'\0';
5051 return unicode;
5052}
5053
5054#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005055
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005056/* Primary internal function which creates utf8 encoded bytes objects.
5057
5058 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005059 and allocate exactly as much space needed at the end. Else allocate the
5060 maximum possible needed (4 result bytes per Unicode character), and return
5061 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005062*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005063PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005064_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005065{
Victor Stinner6099a032011-12-18 14:22:26 +01005066 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005067 void *data;
5068 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005069
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005070 if (!PyUnicode_Check(unicode)) {
5071 PyErr_BadArgument();
5072 return NULL;
5073 }
5074
5075 if (PyUnicode_READY(unicode) == -1)
5076 return NULL;
5077
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005078 if (PyUnicode_UTF8(unicode))
5079 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5080 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005081
5082 kind = PyUnicode_KIND(unicode);
5083 data = PyUnicode_DATA(unicode);
5084 size = PyUnicode_GET_LENGTH(unicode);
5085
Benjamin Petersonead6b532011-12-20 17:23:42 -06005086 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005087 default:
5088 assert(0);
5089 case PyUnicode_1BYTE_KIND:
5090 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5091 assert(!PyUnicode_IS_ASCII(unicode));
5092 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5093 case PyUnicode_2BYTE_KIND:
5094 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5095 case PyUnicode_4BYTE_KIND:
5096 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005097 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005098}
5099
Alexander Belopolsky40018472011-02-26 01:02:56 +00005100PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005101PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5102 Py_ssize_t size,
5103 const char *errors)
5104{
5105 PyObject *v, *unicode;
5106
5107 unicode = PyUnicode_FromUnicode(s, size);
5108 if (unicode == NULL)
5109 return NULL;
5110 v = _PyUnicode_AsUTF8String(unicode, errors);
5111 Py_DECREF(unicode);
5112 return v;
5113}
5114
5115PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005116PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005117{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005118 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005119}
5120
Walter Dörwald41980ca2007-08-16 21:55:45 +00005121/* --- UTF-32 Codec ------------------------------------------------------- */
5122
5123PyObject *
5124PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005125 Py_ssize_t size,
5126 const char *errors,
5127 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005128{
5129 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5130}
5131
5132PyObject *
5133PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005134 Py_ssize_t size,
5135 const char *errors,
5136 int *byteorder,
5137 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005138{
5139 const char *starts = s;
5140 Py_ssize_t startinpos;
5141 Py_ssize_t endinpos;
5142 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005143 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005144 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005145 int bo = 0; /* assume native ordering by default */
5146 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005147 /* Offsets from q for retrieving bytes in the right order. */
5148#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5149 int iorder[] = {0, 1, 2, 3};
5150#else
5151 int iorder[] = {3, 2, 1, 0};
5152#endif
5153 PyObject *errorHandler = NULL;
5154 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005155
Walter Dörwald41980ca2007-08-16 21:55:45 +00005156 q = (unsigned char *)s;
5157 e = q + size;
5158
5159 if (byteorder)
5160 bo = *byteorder;
5161
5162 /* Check for BOM marks (U+FEFF) in the input and adjust current
5163 byte order setting accordingly. In native mode, the leading BOM
5164 mark is skipped, in all other modes, it is copied to the output
5165 stream as-is (giving a ZWNBSP character). */
5166 if (bo == 0) {
5167 if (size >= 4) {
5168 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00005169 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005170#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005171 if (bom == 0x0000FEFF) {
5172 q += 4;
5173 bo = -1;
5174 }
5175 else if (bom == 0xFFFE0000) {
5176 q += 4;
5177 bo = 1;
5178 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005179#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005180 if (bom == 0x0000FEFF) {
5181 q += 4;
5182 bo = 1;
5183 }
5184 else if (bom == 0xFFFE0000) {
5185 q += 4;
5186 bo = -1;
5187 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005188#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005189 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005190 }
5191
5192 if (bo == -1) {
5193 /* force LE */
5194 iorder[0] = 0;
5195 iorder[1] = 1;
5196 iorder[2] = 2;
5197 iorder[3] = 3;
5198 }
5199 else if (bo == 1) {
5200 /* force BE */
5201 iorder[0] = 3;
5202 iorder[1] = 2;
5203 iorder[2] = 1;
5204 iorder[3] = 0;
5205 }
5206
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005207 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005208 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005209 if (!unicode)
5210 return NULL;
5211 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005212 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005213 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005214
Walter Dörwald41980ca2007-08-16 21:55:45 +00005215 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005216 Py_UCS4 ch;
5217 /* remaining bytes at the end? (size should be divisible by 4) */
5218 if (e-q<4) {
5219 if (consumed)
5220 break;
5221 errmsg = "truncated data";
5222 startinpos = ((const char *)q)-starts;
5223 endinpos = ((const char *)e)-starts;
5224 goto utf32Error;
5225 /* The remaining input chars are ignored if the callback
5226 chooses to skip the input */
5227 }
5228 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5229 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005230
Benjamin Peterson29060642009-01-31 22:14:21 +00005231 if (ch >= 0x110000)
5232 {
5233 errmsg = "codepoint not in range(0x110000)";
5234 startinpos = ((const char *)q)-starts;
5235 endinpos = startinpos+4;
5236 goto utf32Error;
5237 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005238 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5239 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005240 q += 4;
5241 continue;
5242 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005243 if (unicode_decode_call_errorhandler(
5244 errors, &errorHandler,
5245 "utf32", errmsg,
5246 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005247 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005248 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005249 }
5250
5251 if (byteorder)
5252 *byteorder = bo;
5253
5254 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005255 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005256
5257 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005258 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005259 goto onError;
5260
5261 Py_XDECREF(errorHandler);
5262 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005263 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005264
Benjamin Peterson29060642009-01-31 22:14:21 +00005265 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005266 Py_DECREF(unicode);
5267 Py_XDECREF(errorHandler);
5268 Py_XDECREF(exc);
5269 return NULL;
5270}
5271
5272PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005273_PyUnicode_EncodeUTF32(PyObject *str,
5274 const char *errors,
5275 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005276{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005277 int kind;
5278 void *data;
5279 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005280 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005281 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005282 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005283 /* Offsets from p for storing byte pairs in the right order. */
5284#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5285 int iorder[] = {0, 1, 2, 3};
5286#else
5287 int iorder[] = {3, 2, 1, 0};
5288#endif
5289
Benjamin Peterson29060642009-01-31 22:14:21 +00005290#define STORECHAR(CH) \
5291 do { \
5292 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5293 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5294 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5295 p[iorder[0]] = (CH) & 0xff; \
5296 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005297 } while(0)
5298
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005299 if (!PyUnicode_Check(str)) {
5300 PyErr_BadArgument();
5301 return NULL;
5302 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005303 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005304 return NULL;
5305 kind = PyUnicode_KIND(str);
5306 data = PyUnicode_DATA(str);
5307 len = PyUnicode_GET_LENGTH(str);
5308
5309 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005310 bytesize = nsize * 4;
5311 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005312 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005313 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005314 if (v == NULL)
5315 return NULL;
5316
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005317 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005318 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005319 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005320 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005321 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005322
5323 if (byteorder == -1) {
5324 /* force LE */
5325 iorder[0] = 0;
5326 iorder[1] = 1;
5327 iorder[2] = 2;
5328 iorder[3] = 3;
5329 }
5330 else if (byteorder == 1) {
5331 /* force BE */
5332 iorder[0] = 3;
5333 iorder[1] = 2;
5334 iorder[2] = 1;
5335 iorder[3] = 0;
5336 }
5337
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005338 for (i = 0; i < len; i++)
5339 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005340
5341 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005342 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005343#undef STORECHAR
5344}
5345
Alexander Belopolsky40018472011-02-26 01:02:56 +00005346PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005347PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5348 Py_ssize_t size,
5349 const char *errors,
5350 int byteorder)
5351{
5352 PyObject *result;
5353 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5354 if (tmp == NULL)
5355 return NULL;
5356 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5357 Py_DECREF(tmp);
5358 return result;
5359}
5360
5361PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005362PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005363{
Victor Stinnerb960b342011-11-20 19:12:52 +01005364 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005365}
5366
Guido van Rossumd57fd912000-03-10 22:53:23 +00005367/* --- UTF-16 Codec ------------------------------------------------------- */
5368
Tim Peters772747b2001-08-09 22:21:55 +00005369PyObject *
5370PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005371 Py_ssize_t size,
5372 const char *errors,
5373 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005374{
Walter Dörwald69652032004-09-07 20:24:22 +00005375 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5376}
5377
Antoine Pitrouab868312009-01-10 15:40:25 +00005378/* Two masks for fast checking of whether a C 'long' may contain
5379 UTF16-encoded surrogate characters. This is an efficient heuristic,
5380 assuming that non-surrogate characters with a code point >= 0x8000 are
5381 rare in most input.
5382 FAST_CHAR_MASK is used when the input is in native byte ordering,
5383 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005384*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005385#if (SIZEOF_LONG == 8)
5386# define FAST_CHAR_MASK 0x8000800080008000L
5387# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5388#elif (SIZEOF_LONG == 4)
5389# define FAST_CHAR_MASK 0x80008000L
5390# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5391#else
5392# error C 'long' size should be either 4 or 8!
5393#endif
5394
Walter Dörwald69652032004-09-07 20:24:22 +00005395PyObject *
5396PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005397 Py_ssize_t size,
5398 const char *errors,
5399 int *byteorder,
5400 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005401{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005402 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005403 Py_ssize_t startinpos;
5404 Py_ssize_t endinpos;
5405 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005406 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005407 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005408 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005409 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005410 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005411 /* Offsets from q for retrieving byte pairs in the right order. */
5412#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5413 int ihi = 1, ilo = 0;
5414#else
5415 int ihi = 0, ilo = 1;
5416#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005417 PyObject *errorHandler = NULL;
5418 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005419
5420 /* Note: size will always be longer than the resulting Unicode
5421 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005422 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005423 if (!unicode)
5424 return NULL;
5425 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005426 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005427 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428
Tim Peters772747b2001-08-09 22:21:55 +00005429 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005430 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005431
5432 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005433 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005434
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005435 /* Check for BOM marks (U+FEFF) in the input and adjust current
5436 byte order setting accordingly. In native mode, the leading BOM
5437 mark is skipped, in all other modes, it is copied to the output
5438 stream as-is (giving a ZWNBSP character). */
5439 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005440 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005441 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005442#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005443 if (bom == 0xFEFF) {
5444 q += 2;
5445 bo = -1;
5446 }
5447 else if (bom == 0xFFFE) {
5448 q += 2;
5449 bo = 1;
5450 }
Tim Petersced69f82003-09-16 20:30:58 +00005451#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005452 if (bom == 0xFEFF) {
5453 q += 2;
5454 bo = 1;
5455 }
5456 else if (bom == 0xFFFE) {
5457 q += 2;
5458 bo = -1;
5459 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005460#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005461 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005462 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005463
Tim Peters772747b2001-08-09 22:21:55 +00005464 if (bo == -1) {
5465 /* force LE */
5466 ihi = 1;
5467 ilo = 0;
5468 }
5469 else if (bo == 1) {
5470 /* force BE */
5471 ihi = 0;
5472 ilo = 1;
5473 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005474#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5475 native_ordering = ilo < ihi;
5476#else
5477 native_ordering = ilo > ihi;
5478#endif
Tim Peters772747b2001-08-09 22:21:55 +00005479
Antoine Pitrouab868312009-01-10 15:40:25 +00005480 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005481 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005482 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005483 /* First check for possible aligned read of a C 'long'. Unaligned
5484 reads are more expensive, better to defer to another iteration. */
5485 if (!((size_t) q & LONG_PTR_MASK)) {
5486 /* Fast path for runs of non-surrogate chars. */
5487 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005488 int kind = PyUnicode_KIND(unicode);
5489 void *data = PyUnicode_DATA(unicode);
5490 while (_q < aligned_end) {
5491 unsigned long block = * (unsigned long *) _q;
5492 unsigned short *pblock = (unsigned short*)&block;
5493 Py_UCS4 maxch;
5494 if (native_ordering) {
5495 /* Can use buffer directly */
5496 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005497 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005498 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005499 else {
5500 /* Need to byte-swap */
5501 unsigned char *_p = (unsigned char*)pblock;
5502 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005503 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005504 _p[0] = _q[1];
5505 _p[1] = _q[0];
5506 _p[2] = _q[3];
5507 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005508#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005509 _p[4] = _q[5];
5510 _p[5] = _q[4];
5511 _p[6] = _q[7];
5512 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005513#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005514 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005515 maxch = Py_MAX(pblock[0], pblock[1]);
5516#if SIZEOF_LONG == 8
5517 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5518#endif
5519 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5520 if (unicode_widen(&unicode, maxch) < 0)
5521 goto onError;
5522 kind = PyUnicode_KIND(unicode);
5523 data = PyUnicode_DATA(unicode);
5524 }
5525 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5526 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5527#if SIZEOF_LONG == 8
5528 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5529 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5530#endif
5531 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005532 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005533 q = _q;
5534 if (q >= e)
5535 break;
5536 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005537 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005538
Benjamin Peterson14339b62009-01-31 16:36:08 +00005539 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005540
Victor Stinner551ac952011-11-29 22:58:13 +01005541 if (!Py_UNICODE_IS_SURROGATE(ch)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005542 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5543 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005544 continue;
5545 }
5546
5547 /* UTF-16 code pair: */
5548 if (q > e) {
5549 errmsg = "unexpected end of data";
5550 startinpos = (((const char *)q) - 2) - starts;
5551 endinpos = ((const char *)e) + 1 - starts;
5552 goto utf16Error;
5553 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005554 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5555 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005556 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005557 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005558 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005559 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005560 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005561 continue;
5562 }
5563 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005564 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005565 startinpos = (((const char *)q)-4)-starts;
5566 endinpos = startinpos+2;
5567 goto utf16Error;
5568 }
5569
Benjamin Peterson14339b62009-01-31 16:36:08 +00005570 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005571 errmsg = "illegal encoding";
5572 startinpos = (((const char *)q)-2)-starts;
5573 endinpos = startinpos+2;
5574 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005575
Benjamin Peterson29060642009-01-31 22:14:21 +00005576 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005577 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005578 errors,
5579 &errorHandler,
5580 "utf16", errmsg,
5581 &starts,
5582 (const char **)&e,
5583 &startinpos,
5584 &endinpos,
5585 &exc,
5586 (const char **)&q,
5587 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005588 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005589 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005590 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005591 /* remaining byte at the end? (size should be even) */
5592 if (e == q) {
5593 if (!consumed) {
5594 errmsg = "truncated data";
5595 startinpos = ((const char *)q) - starts;
5596 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005597 if (unicode_decode_call_errorhandler(
5598 errors,
5599 &errorHandler,
5600 "utf16", errmsg,
5601 &starts,
5602 (const char **)&e,
5603 &startinpos,
5604 &endinpos,
5605 &exc,
5606 (const char **)&q,
5607 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005608 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005609 goto onError;
5610 /* The remaining input chars are ignored if the callback
5611 chooses to skip the input */
5612 }
5613 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005614
5615 if (byteorder)
5616 *byteorder = bo;
5617
Walter Dörwald69652032004-09-07 20:24:22 +00005618 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005619 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005620
Guido van Rossumd57fd912000-03-10 22:53:23 +00005621 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005622 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005623 goto onError;
5624
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005625 Py_XDECREF(errorHandler);
5626 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005627 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005628
Benjamin Peterson29060642009-01-31 22:14:21 +00005629 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005630 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005631 Py_XDECREF(errorHandler);
5632 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005633 return NULL;
5634}
5635
Antoine Pitrouab868312009-01-10 15:40:25 +00005636#undef FAST_CHAR_MASK
5637#undef SWAPPED_FAST_CHAR_MASK
5638
Tim Peters772747b2001-08-09 22:21:55 +00005639PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005640_PyUnicode_EncodeUTF16(PyObject *str,
5641 const char *errors,
5642 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005643{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005644 int kind;
5645 void *data;
5646 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005647 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005648 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005649 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005650 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005651 /* Offsets from p for storing byte pairs in the right order. */
5652#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5653 int ihi = 1, ilo = 0;
5654#else
5655 int ihi = 0, ilo = 1;
5656#endif
5657
Benjamin Peterson29060642009-01-31 22:14:21 +00005658#define STORECHAR(CH) \
5659 do { \
5660 p[ihi] = ((CH) >> 8) & 0xff; \
5661 p[ilo] = (CH) & 0xff; \
5662 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005663 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005664
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005665 if (!PyUnicode_Check(str)) {
5666 PyErr_BadArgument();
5667 return NULL;
5668 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005669 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005670 return NULL;
5671 kind = PyUnicode_KIND(str);
5672 data = PyUnicode_DATA(str);
5673 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005674
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005675 pairs = 0;
5676 if (kind == PyUnicode_4BYTE_KIND)
5677 for (i = 0; i < len; i++)
5678 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5679 pairs++;
5680 /* 2 * (len + pairs + (byteorder == 0)) */
5681 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005682 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005683 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005684 bytesize = nsize * 2;
5685 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005686 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005687 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005688 if (v == NULL)
5689 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005690
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005691 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005692 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005693 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005694 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005695 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005696
5697 if (byteorder == -1) {
5698 /* force LE */
5699 ihi = 1;
5700 ilo = 0;
5701 }
5702 else if (byteorder == 1) {
5703 /* force BE */
5704 ihi = 0;
5705 ilo = 1;
5706 }
5707
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005708 for (i = 0; i < len; i++) {
5709 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5710 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005711 if (ch >= 0x10000) {
Victor Stinner551ac952011-11-29 22:58:13 +01005712 ch2 = Py_UNICODE_LOW_SURROGATE(ch);
5713 ch = Py_UNICODE_HIGH_SURROGATE(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00005714 }
Tim Peters772747b2001-08-09 22:21:55 +00005715 STORECHAR(ch);
5716 if (ch2)
5717 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005718 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005719
5720 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005721 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005722#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005723}
5724
Alexander Belopolsky40018472011-02-26 01:02:56 +00005725PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005726PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5727 Py_ssize_t size,
5728 const char *errors,
5729 int byteorder)
5730{
5731 PyObject *result;
5732 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5733 if (tmp == NULL)
5734 return NULL;
5735 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5736 Py_DECREF(tmp);
5737 return result;
5738}
5739
5740PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005741PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005742{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005743 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005744}
5745
5746/* --- Unicode Escape Codec ----------------------------------------------- */
5747
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005748/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5749 if all the escapes in the string make it still a valid ASCII string.
5750 Returns -1 if any escapes were found which cause the string to
5751 pop out of ASCII range. Otherwise returns the length of the
5752 required buffer to hold the string.
5753 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005754static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005755length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5756{
5757 const unsigned char *p = (const unsigned char *)s;
5758 const unsigned char *end = p + size;
5759 Py_ssize_t length = 0;
5760
5761 if (size < 0)
5762 return -1;
5763
5764 for (; p < end; ++p) {
5765 if (*p > 127) {
5766 /* Non-ASCII */
5767 return -1;
5768 }
5769 else if (*p != '\\') {
5770 /* Normal character */
5771 ++length;
5772 }
5773 else {
5774 /* Backslash-escape, check next char */
5775 ++p;
5776 /* Escape sequence reaches till end of string or
5777 non-ASCII follow-up. */
5778 if (p >= end || *p > 127)
5779 return -1;
5780 switch (*p) {
5781 case '\n':
5782 /* backslash + \n result in zero characters */
5783 break;
5784 case '\\': case '\'': case '\"':
5785 case 'b': case 'f': case 't':
5786 case 'n': case 'r': case 'v': case 'a':
5787 ++length;
5788 break;
5789 case '0': case '1': case '2': case '3':
5790 case '4': case '5': case '6': case '7':
5791 case 'x': case 'u': case 'U': case 'N':
5792 /* these do not guarantee ASCII characters */
5793 return -1;
5794 default:
5795 /* count the backslash + the other character */
5796 length += 2;
5797 }
5798 }
5799 }
5800 return length;
5801}
5802
Fredrik Lundh06d12682001-01-24 07:59:11 +00005803static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005804
Alexander Belopolsky40018472011-02-26 01:02:56 +00005805PyObject *
5806PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005807 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005808 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005809{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005810 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005811 Py_ssize_t startinpos;
5812 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005813 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005814 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005815 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005816 char* message;
5817 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005818 PyObject *errorHandler = NULL;
5819 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005820 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005821 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005822
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005823 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005824
5825 /* After length_of_escaped_ascii_string() there are two alternatives,
5826 either the string is pure ASCII with named escapes like \n, etc.
5827 and we determined it's exact size (common case)
5828 or it contains \x, \u, ... escape sequences. then we create a
5829 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005830 if (len >= 0) {
5831 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005832 if (!v)
5833 goto onError;
5834 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005835 }
5836 else {
5837 /* Escaped strings will always be longer than the resulting
5838 Unicode string, so we start with size here and then reduce the
5839 length after conversion to the true value.
5840 (but if the error callback returns a long replacement string
5841 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005842 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005843 if (!v)
5844 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005845 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005846 }
5847
Guido van Rossumd57fd912000-03-10 22:53:23 +00005848 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005849 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005850 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005851 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005852
Guido van Rossumd57fd912000-03-10 22:53:23 +00005853 while (s < end) {
5854 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005855 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005856 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005857
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005858 /* The only case in which i == ascii_length is a backslash
5859 followed by a newline. */
5860 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005861
Guido van Rossumd57fd912000-03-10 22:53:23 +00005862 /* Non-escape characters are interpreted as Unicode ordinals */
5863 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005864 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5865 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005866 continue;
5867 }
5868
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005869 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005870 /* \ - Escapes */
5871 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005872 c = *s++;
5873 if (s > end)
5874 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005875
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005876 /* The only case in which i == ascii_length is a backslash
5877 followed by a newline. */
5878 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005879
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005880 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005881
Benjamin Peterson29060642009-01-31 22:14:21 +00005882 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005883#define WRITECHAR(ch) \
5884 do { \
5885 if (unicode_putchar(&v, &i, ch) < 0) \
5886 goto onError; \
5887 }while(0)
5888
Guido van Rossumd57fd912000-03-10 22:53:23 +00005889 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005890 case '\\': WRITECHAR('\\'); break;
5891 case '\'': WRITECHAR('\''); break;
5892 case '\"': WRITECHAR('\"'); break;
5893 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005894 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005895 case 'f': WRITECHAR('\014'); break;
5896 case 't': WRITECHAR('\t'); break;
5897 case 'n': WRITECHAR('\n'); break;
5898 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005899 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005900 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005901 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005902 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005903
Benjamin Peterson29060642009-01-31 22:14:21 +00005904 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005905 case '0': case '1': case '2': case '3':
5906 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005907 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005908 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005909 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005910 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005911 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005912 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005913 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914 break;
5915
Benjamin Peterson29060642009-01-31 22:14:21 +00005916 /* hex escapes */
5917 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005918 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005919 digits = 2;
5920 message = "truncated \\xXX escape";
5921 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005922
Benjamin Peterson29060642009-01-31 22:14:21 +00005923 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005924 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005925 digits = 4;
5926 message = "truncated \\uXXXX escape";
5927 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005928
Benjamin Peterson29060642009-01-31 22:14:21 +00005929 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005930 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005931 digits = 8;
5932 message = "truncated \\UXXXXXXXX escape";
5933 hexescape:
5934 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005935 if (s+digits>end) {
5936 endinpos = size;
5937 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005938 errors, &errorHandler,
5939 "unicodeescape", "end of string in escape sequence",
5940 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005941 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005942 goto onError;
5943 goto nextByte;
5944 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005945 for (j = 0; j < digits; ++j) {
5946 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005947 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005948 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005949 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005950 errors, &errorHandler,
5951 "unicodeescape", message,
5952 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005953 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005954 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005955 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005956 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005957 }
5958 chr = (chr<<4) & ~0xF;
5959 if (c >= '0' && c <= '9')
5960 chr += c - '0';
5961 else if (c >= 'a' && c <= 'f')
5962 chr += 10 + c - 'a';
5963 else
5964 chr += 10 + c - 'A';
5965 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005966 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005967 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005968 /* _decoding_error will have already written into the
5969 target buffer. */
5970 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005971 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005972 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005973 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005974 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005975 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005976 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005977 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005978 errors, &errorHandler,
5979 "unicodeescape", "illegal Unicode character",
5980 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005981 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005982 goto onError;
5983 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005984 break;
5985
Benjamin Peterson29060642009-01-31 22:14:21 +00005986 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005987 case 'N':
5988 message = "malformed \\N character escape";
5989 if (ucnhash_CAPI == NULL) {
5990 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005991 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5992 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005993 if (ucnhash_CAPI == NULL)
5994 goto ucnhashError;
5995 }
5996 if (*s == '{') {
5997 const char *start = s+1;
5998 /* look for the closing brace */
5999 while (*s != '}' && s < end)
6000 s++;
6001 if (s > start && s < end && *s == '}') {
6002 /* found a name. look it up in the unicode database */
6003 message = "unknown Unicode character name";
6004 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006005 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03006006 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00006007 goto store;
6008 }
6009 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006010 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006011 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006012 errors, &errorHandler,
6013 "unicodeescape", message,
6014 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006015 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00006016 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006017 break;
6018
6019 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00006020 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006021 message = "\\ at end of string";
6022 s--;
6023 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006024 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006025 errors, &errorHandler,
6026 "unicodeescape", message,
6027 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006028 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00006029 goto onError;
6030 }
6031 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006032 WRITECHAR('\\');
6033 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00006034 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006035 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006036 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006037 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006038 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006040#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006041
Victor Stinner16e6a802011-12-12 13:24:15 +01006042 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006043 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006044 Py_XDECREF(errorHandler);
6045 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006046 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00006047
Benjamin Peterson29060642009-01-31 22:14:21 +00006048 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00006049 PyErr_SetString(
6050 PyExc_UnicodeError,
6051 "\\N escapes not supported (can't load unicodedata module)"
6052 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00006053 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006054 Py_XDECREF(errorHandler);
6055 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00006056 return NULL;
6057
Benjamin Peterson29060642009-01-31 22:14:21 +00006058 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006059 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006060 Py_XDECREF(errorHandler);
6061 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006062 return NULL;
6063}
6064
6065/* Return a Unicode-Escape string version of the Unicode object.
6066
6067 If quotes is true, the string is enclosed in u"" or u'' quotes as
6068 appropriate.
6069
6070*/
6071
Alexander Belopolsky40018472011-02-26 01:02:56 +00006072PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006073PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006074{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006075 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006076 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006077 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006078 int kind;
6079 void *data;
6080 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006081
Thomas Wouters89f507f2006-12-13 04:49:30 +00006082 /* Initial allocation is based on the longest-possible unichr
6083 escape.
6084
6085 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
6086 unichr, so in this case it's the longest unichr escape. In
6087 narrow (UTF-16) builds this is five chars per source unichr
6088 since there are two unichrs in the surrogate pair, so in narrow
6089 (UTF-16) builds it's not the longest unichr escape.
6090
6091 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
6092 so in the narrow (UTF-16) build case it's the longest unichr
6093 escape.
6094 */
6095
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006096 if (!PyUnicode_Check(unicode)) {
6097 PyErr_BadArgument();
6098 return NULL;
6099 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006100 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006101 return NULL;
6102 len = PyUnicode_GET_LENGTH(unicode);
6103 kind = PyUnicode_KIND(unicode);
6104 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06006105 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006106 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6107 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6108 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6109 }
6110
6111 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006112 return PyBytes_FromStringAndSize(NULL, 0);
6113
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006114 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006115 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006116
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006117 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00006118 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006119 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00006120 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006121 if (repr == NULL)
6122 return NULL;
6123
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006124 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006125
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006126 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006127 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006128
Walter Dörwald79e913e2007-05-12 11:08:06 +00006129 /* Escape backslashes */
6130 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006131 *p++ = '\\';
6132 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00006133 continue;
Tim Petersced69f82003-09-16 20:30:58 +00006134 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006135
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006136 /* Map 21-bit characters to '\U00xxxxxx' */
6137 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006138 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006139 *p++ = '\\';
6140 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006141 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
6142 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
6143 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6144 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6145 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6146 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6147 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6148 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006149 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006150 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006151
Guido van Rossumd57fd912000-03-10 22:53:23 +00006152 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006153 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006154 *p++ = '\\';
6155 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006156 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6157 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6158 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6159 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006160 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006161
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006162 /* Map special whitespace to '\t', \n', '\r' */
6163 else if (ch == '\t') {
6164 *p++ = '\\';
6165 *p++ = 't';
6166 }
6167 else if (ch == '\n') {
6168 *p++ = '\\';
6169 *p++ = 'n';
6170 }
6171 else if (ch == '\r') {
6172 *p++ = '\\';
6173 *p++ = 'r';
6174 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006175
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006176 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006177 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006178 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006179 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006180 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6181 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006182 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006183
Guido van Rossumd57fd912000-03-10 22:53:23 +00006184 /* Copy everything else as-is */
6185 else
6186 *p++ = (char) ch;
6187 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006188
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006189 assert(p - PyBytes_AS_STRING(repr) > 0);
6190 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6191 return NULL;
6192 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006193}
6194
Alexander Belopolsky40018472011-02-26 01:02:56 +00006195PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006196PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6197 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006198{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006199 PyObject *result;
6200 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6201 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006202 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006203 result = PyUnicode_AsUnicodeEscapeString(tmp);
6204 Py_DECREF(tmp);
6205 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006206}
6207
6208/* --- Raw Unicode Escape Codec ------------------------------------------- */
6209
Alexander Belopolsky40018472011-02-26 01:02:56 +00006210PyObject *
6211PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006212 Py_ssize_t size,
6213 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006214{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006215 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006216 Py_ssize_t startinpos;
6217 Py_ssize_t endinpos;
6218 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006219 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006220 const char *end;
6221 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006222 PyObject *errorHandler = NULL;
6223 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006224
Guido van Rossumd57fd912000-03-10 22:53:23 +00006225 /* Escaped strings will always be longer than the resulting
6226 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006227 length after conversion to the true value. (But decoding error
6228 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006229 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006230 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006231 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006232 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006233 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006234 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006235 end = s + size;
6236 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006237 unsigned char c;
6238 Py_UCS4 x;
6239 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006240 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006241
Benjamin Peterson29060642009-01-31 22:14:21 +00006242 /* Non-escape characters are interpreted as Unicode ordinals */
6243 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006244 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6245 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006246 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006247 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006248 startinpos = s-starts;
6249
6250 /* \u-escapes are only interpreted iff the number of leading
6251 backslashes if odd */
6252 bs = s;
6253 for (;s < end;) {
6254 if (*s != '\\')
6255 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006256 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6257 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006258 }
6259 if (((s - bs) & 1) == 0 ||
6260 s >= end ||
6261 (*s != 'u' && *s != 'U')) {
6262 continue;
6263 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006264 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006265 count = *s=='u' ? 4 : 8;
6266 s++;
6267
6268 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006269 for (x = 0, i = 0; i < count; ++i, ++s) {
6270 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006271 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006272 endinpos = s-starts;
6273 if (unicode_decode_call_errorhandler(
6274 errors, &errorHandler,
6275 "rawunicodeescape", "truncated \\uXXXX",
6276 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006277 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006278 goto onError;
6279 goto nextByte;
6280 }
6281 x = (x<<4) & ~0xF;
6282 if (c >= '0' && c <= '9')
6283 x += c - '0';
6284 else if (c >= 'a' && c <= 'f')
6285 x += 10 + c - 'a';
6286 else
6287 x += 10 + c - 'A';
6288 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006289 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006290 if (unicode_putchar(&v, &outpos, x) < 0)
6291 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006292 } else {
6293 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006294 if (unicode_decode_call_errorhandler(
6295 errors, &errorHandler,
6296 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006297 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006298 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006299 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006300 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006301 nextByte:
6302 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006303 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006304 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006305 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006306 Py_XDECREF(errorHandler);
6307 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006308 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006309
Benjamin Peterson29060642009-01-31 22:14:21 +00006310 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006311 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006312 Py_XDECREF(errorHandler);
6313 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006314 return NULL;
6315}
6316
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006317
Alexander Belopolsky40018472011-02-26 01:02:56 +00006318PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006319PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006320{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006321 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006322 char *p;
6323 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006324 Py_ssize_t expandsize, pos;
6325 int kind;
6326 void *data;
6327 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006328
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006329 if (!PyUnicode_Check(unicode)) {
6330 PyErr_BadArgument();
6331 return NULL;
6332 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006333 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006334 return NULL;
6335 kind = PyUnicode_KIND(unicode);
6336 data = PyUnicode_DATA(unicode);
6337 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006338 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6339 bytes, and 1 byte characters 4. */
6340 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006341
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006342 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006343 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006344
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006345 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006346 if (repr == NULL)
6347 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006348 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006349 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006350
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006351 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006352 for (pos = 0; pos < len; pos++) {
6353 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006354 /* Map 32-bit characters to '\Uxxxxxxxx' */
6355 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006356 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006357 *p++ = '\\';
6358 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006359 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6360 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6361 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6362 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6363 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6364 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6365 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6366 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006367 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006368 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006369 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006370 *p++ = '\\';
6371 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006372 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6373 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6374 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6375 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006376 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006377 /* Copy everything else as-is */
6378 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006379 *p++ = (char) ch;
6380 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006381
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006382 assert(p > q);
6383 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006384 return NULL;
6385 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006386}
6387
Alexander Belopolsky40018472011-02-26 01:02:56 +00006388PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006389PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6390 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006391{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006392 PyObject *result;
6393 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6394 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006395 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006396 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6397 Py_DECREF(tmp);
6398 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006399}
6400
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006401/* --- Unicode Internal Codec ------------------------------------------- */
6402
Alexander Belopolsky40018472011-02-26 01:02:56 +00006403PyObject *
6404_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006405 Py_ssize_t size,
6406 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006407{
6408 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006409 Py_ssize_t startinpos;
6410 Py_ssize_t endinpos;
6411 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006412 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006413 const char *end;
6414 const char *reason;
6415 PyObject *errorHandler = NULL;
6416 PyObject *exc = NULL;
6417
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006418 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006419 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006420 1))
6421 return NULL;
6422
Thomas Wouters89f507f2006-12-13 04:49:30 +00006423 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006424 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006425 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006426 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006427 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006428 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006429 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006430 end = s + size;
6431
6432 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006433 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006434 Py_UCS4 ch;
6435 /* We copy the raw representation one byte at a time because the
6436 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006437 ((char *) &uch)[0] = s[0];
6438 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006439#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006440 ((char *) &uch)[2] = s[2];
6441 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006442#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006443 ch = uch;
6444
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006445 /* We have to sanity check the raw data, otherwise doom looms for
6446 some malformed UCS-4 data. */
6447 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006448#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006449 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006450#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006451 end-s < Py_UNICODE_SIZE
6452 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006453 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006454 startinpos = s - starts;
6455 if (end-s < Py_UNICODE_SIZE) {
6456 endinpos = end-starts;
6457 reason = "truncated input";
6458 }
6459 else {
6460 endinpos = s - starts + Py_UNICODE_SIZE;
6461 reason = "illegal code point (> 0x10FFFF)";
6462 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006463 if (unicode_decode_call_errorhandler(
6464 errors, &errorHandler,
6465 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006466 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006467 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006468 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006469 continue;
6470 }
6471
6472 s += Py_UNICODE_SIZE;
6473#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006474 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006475 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006476 Py_UNICODE uch2;
6477 ((char *) &uch2)[0] = s[0];
6478 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006479 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006480 {
Victor Stinner551ac952011-11-29 22:58:13 +01006481 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006482 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006483 }
6484 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006485#endif
6486
6487 if (unicode_putchar(&v, &outpos, ch) < 0)
6488 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006489 }
6490
Victor Stinner16e6a802011-12-12 13:24:15 +01006491 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006492 goto onError;
6493 Py_XDECREF(errorHandler);
6494 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006495 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006496
Benjamin Peterson29060642009-01-31 22:14:21 +00006497 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006498 Py_XDECREF(v);
6499 Py_XDECREF(errorHandler);
6500 Py_XDECREF(exc);
6501 return NULL;
6502}
6503
Guido van Rossumd57fd912000-03-10 22:53:23 +00006504/* --- Latin-1 Codec ------------------------------------------------------ */
6505
Alexander Belopolsky40018472011-02-26 01:02:56 +00006506PyObject *
6507PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006508 Py_ssize_t size,
6509 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006510{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006511 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006512 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006513}
6514
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006515/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006516static void
6517make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006518 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006519 PyObject *unicode,
6520 Py_ssize_t startpos, Py_ssize_t endpos,
6521 const char *reason)
6522{
6523 if (*exceptionObject == NULL) {
6524 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006525 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006526 encoding, unicode, startpos, endpos, reason);
6527 }
6528 else {
6529 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6530 goto onError;
6531 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6532 goto onError;
6533 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6534 goto onError;
6535 return;
6536 onError:
6537 Py_DECREF(*exceptionObject);
6538 *exceptionObject = NULL;
6539 }
6540}
6541
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006542/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006543static void
6544raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006545 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006546 PyObject *unicode,
6547 Py_ssize_t startpos, Py_ssize_t endpos,
6548 const char *reason)
6549{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006550 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006551 encoding, unicode, startpos, endpos, reason);
6552 if (*exceptionObject != NULL)
6553 PyCodec_StrictErrors(*exceptionObject);
6554}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006555
6556/* error handling callback helper:
6557 build arguments, call the callback and check the arguments,
6558 put the result into newpos and return the replacement string, which
6559 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006560static PyObject *
6561unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006562 PyObject **errorHandler,
6563 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006564 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006565 Py_ssize_t startpos, Py_ssize_t endpos,
6566 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006567{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006568 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006569 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006570 PyObject *restuple;
6571 PyObject *resunicode;
6572
6573 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006574 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006575 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006576 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006577 }
6578
Benjamin Petersonbac79492012-01-14 13:34:47 -05006579 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006580 return NULL;
6581 len = PyUnicode_GET_LENGTH(unicode);
6582
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006583 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006584 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006585 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006586 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006587
6588 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006589 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006590 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006591 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006592 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006593 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006594 Py_DECREF(restuple);
6595 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006596 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006597 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006598 &resunicode, newpos)) {
6599 Py_DECREF(restuple);
6600 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006601 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006602 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6603 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6604 Py_DECREF(restuple);
6605 return NULL;
6606 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006607 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006608 *newpos = len + *newpos;
6609 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006610 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6611 Py_DECREF(restuple);
6612 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006613 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006614 Py_INCREF(resunicode);
6615 Py_DECREF(restuple);
6616 return resunicode;
6617}
6618
Alexander Belopolsky40018472011-02-26 01:02:56 +00006619static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006620unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006621 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006622 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006623{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006624 /* input state */
6625 Py_ssize_t pos=0, size;
6626 int kind;
6627 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006628 /* output object */
6629 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006630 /* pointer into the output */
6631 char *str;
6632 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006633 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006634 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6635 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006636 PyObject *errorHandler = NULL;
6637 PyObject *exc = NULL;
6638 /* the following variable is used for caching string comparisons
6639 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6640 int known_errorHandler = -1;
6641
Benjamin Petersonbac79492012-01-14 13:34:47 -05006642 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006643 return NULL;
6644 size = PyUnicode_GET_LENGTH(unicode);
6645 kind = PyUnicode_KIND(unicode);
6646 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006647 /* allocate enough for a simple encoding without
6648 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006649 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006650 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006651 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006652 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006653 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006654 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006655 ressize = size;
6656
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006657 while (pos < size) {
6658 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006659
Benjamin Peterson29060642009-01-31 22:14:21 +00006660 /* can we encode this? */
6661 if (c<limit) {
6662 /* no overflow check, because we know that the space is enough */
6663 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006664 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006665 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006666 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006667 Py_ssize_t requiredsize;
6668 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006669 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006670 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006671 Py_ssize_t collstart = pos;
6672 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006673 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006674 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006675 ++collend;
6676 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6677 if (known_errorHandler==-1) {
6678 if ((errors==NULL) || (!strcmp(errors, "strict")))
6679 known_errorHandler = 1;
6680 else if (!strcmp(errors, "replace"))
6681 known_errorHandler = 2;
6682 else if (!strcmp(errors, "ignore"))
6683 known_errorHandler = 3;
6684 else if (!strcmp(errors, "xmlcharrefreplace"))
6685 known_errorHandler = 4;
6686 else
6687 known_errorHandler = 0;
6688 }
6689 switch (known_errorHandler) {
6690 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006691 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006692 goto onError;
6693 case 2: /* replace */
6694 while (collstart++<collend)
6695 *str++ = '?'; /* fall through */
6696 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006697 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006698 break;
6699 case 4: /* xmlcharrefreplace */
6700 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006701 /* determine replacement size */
6702 for (i = collstart, repsize = 0; i < collend; ++i) {
6703 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6704 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006705 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006706 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006707 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006708 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006709 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006710 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006711 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006712 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006713 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006714 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006715 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006716 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006717 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006718 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006719 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006720 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006721 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006722 if (requiredsize > ressize) {
6723 if (requiredsize<2*ressize)
6724 requiredsize = 2*ressize;
6725 if (_PyBytes_Resize(&res, requiredsize))
6726 goto onError;
6727 str = PyBytes_AS_STRING(res) + respos;
6728 ressize = requiredsize;
6729 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006730 /* generate replacement */
6731 for (i = collstart; i < collend; ++i) {
6732 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006733 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006734 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006735 break;
6736 default:
6737 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006738 encoding, reason, unicode, &exc,
6739 collstart, collend, &newpos);
6740 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006741 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006742 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006743 if (PyBytes_Check(repunicode)) {
6744 /* Directly copy bytes result to output. */
6745 repsize = PyBytes_Size(repunicode);
6746 if (repsize > 1) {
6747 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006748 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006749 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6750 Py_DECREF(repunicode);
6751 goto onError;
6752 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006753 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006754 ressize += repsize-1;
6755 }
6756 memcpy(str, PyBytes_AsString(repunicode), repsize);
6757 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006758 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006759 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006760 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006761 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006762 /* need more space? (at least enough for what we
6763 have+the replacement+the rest of the string, so
6764 we won't have to check space for encodable characters) */
6765 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006766 repsize = PyUnicode_GET_LENGTH(repunicode);
6767 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006768 if (requiredsize > ressize) {
6769 if (requiredsize<2*ressize)
6770 requiredsize = 2*ressize;
6771 if (_PyBytes_Resize(&res, requiredsize)) {
6772 Py_DECREF(repunicode);
6773 goto onError;
6774 }
6775 str = PyBytes_AS_STRING(res) + respos;
6776 ressize = requiredsize;
6777 }
6778 /* check if there is anything unencodable in the replacement
6779 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006780 for (i = 0; repsize-->0; ++i, ++str) {
6781 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006782 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006783 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006784 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006785 Py_DECREF(repunicode);
6786 goto onError;
6787 }
6788 *str = (char)c;
6789 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006790 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006791 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006792 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006793 }
6794 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006795 /* Resize if we allocated to much */
6796 size = str - PyBytes_AS_STRING(res);
6797 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006798 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006799 if (_PyBytes_Resize(&res, size) < 0)
6800 goto onError;
6801 }
6802
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006803 Py_XDECREF(errorHandler);
6804 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006805 return res;
6806
6807 onError:
6808 Py_XDECREF(res);
6809 Py_XDECREF(errorHandler);
6810 Py_XDECREF(exc);
6811 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006812}
6813
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006814/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006815PyObject *
6816PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006817 Py_ssize_t size,
6818 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006819{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006820 PyObject *result;
6821 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6822 if (unicode == NULL)
6823 return NULL;
6824 result = unicode_encode_ucs1(unicode, errors, 256);
6825 Py_DECREF(unicode);
6826 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006827}
6828
Alexander Belopolsky40018472011-02-26 01:02:56 +00006829PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006830_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006831{
6832 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006833 PyErr_BadArgument();
6834 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006835 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006836 if (PyUnicode_READY(unicode) == -1)
6837 return NULL;
6838 /* Fast path: if it is a one-byte string, construct
6839 bytes object directly. */
6840 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6841 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6842 PyUnicode_GET_LENGTH(unicode));
6843 /* Non-Latin-1 characters present. Defer to above function to
6844 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006845 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006846}
6847
6848PyObject*
6849PyUnicode_AsLatin1String(PyObject *unicode)
6850{
6851 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006852}
6853
6854/* --- 7-bit ASCII Codec -------------------------------------------------- */
6855
Alexander Belopolsky40018472011-02-26 01:02:56 +00006856PyObject *
6857PyUnicode_DecodeASCII(const char *s,
6858 Py_ssize_t size,
6859 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006860{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006861 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006862 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006863 int kind;
6864 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006865 Py_ssize_t startinpos;
6866 Py_ssize_t endinpos;
6867 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006868 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006869 int has_error;
6870 const unsigned char *p = (const unsigned char *)s;
6871 const unsigned char *end = p + size;
6872 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006873 PyObject *errorHandler = NULL;
6874 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006875
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006876 if (size == 0) {
6877 Py_INCREF(unicode_empty);
6878 return unicode_empty;
6879 }
6880
Guido van Rossumd57fd912000-03-10 22:53:23 +00006881 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006882 if (size == 1 && (unsigned char)s[0] < 128)
6883 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006884
Victor Stinner702c7342011-10-05 13:50:52 +02006885 has_error = 0;
6886 while (p < end && !has_error) {
6887 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6888 an explanation. */
6889 if (!((size_t) p & LONG_PTR_MASK)) {
6890 /* Help register allocation */
6891 register const unsigned char *_p = p;
6892 while (_p < aligned_end) {
6893 unsigned long value = *(unsigned long *) _p;
6894 if (value & ASCII_CHAR_MASK) {
6895 has_error = 1;
6896 break;
6897 }
6898 _p += SIZEOF_LONG;
6899 }
6900 if (_p == end)
6901 break;
6902 if (has_error)
6903 break;
6904 p = _p;
6905 }
6906 if (*p & 0x80) {
6907 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006908 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006909 }
6910 else {
6911 ++p;
6912 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006913 }
Victor Stinner702c7342011-10-05 13:50:52 +02006914 if (!has_error)
6915 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006916
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006917 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006918 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006919 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006920 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006921 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006922 kind = PyUnicode_KIND(v);
6923 data = PyUnicode_DATA(v);
6924 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006925 e = s + size;
6926 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006927 register unsigned char c = (unsigned char)*s;
6928 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006929 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006930 ++s;
6931 }
6932 else {
6933 startinpos = s-starts;
6934 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006935 if (unicode_decode_call_errorhandler(
6936 errors, &errorHandler,
6937 "ascii", "ordinal not in range(128)",
6938 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006939 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006940 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006941 kind = PyUnicode_KIND(v);
6942 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006943 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006944 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006945 if (unicode_resize(&v, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006946 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006947 Py_XDECREF(errorHandler);
6948 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006949 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006950 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006951
Benjamin Peterson29060642009-01-31 22:14:21 +00006952 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006953 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006954 Py_XDECREF(errorHandler);
6955 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006956 return NULL;
6957}
6958
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006959/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006960PyObject *
6961PyUnicode_EncodeASCII(const Py_UNICODE *p,
6962 Py_ssize_t size,
6963 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006964{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006965 PyObject *result;
6966 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6967 if (unicode == NULL)
6968 return NULL;
6969 result = unicode_encode_ucs1(unicode, errors, 128);
6970 Py_DECREF(unicode);
6971 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006972}
6973
Alexander Belopolsky40018472011-02-26 01:02:56 +00006974PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006975_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006976{
6977 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006978 PyErr_BadArgument();
6979 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006980 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006981 if (PyUnicode_READY(unicode) == -1)
6982 return NULL;
6983 /* Fast path: if it is an ASCII-only string, construct bytes object
6984 directly. Else defer to above function to raise the exception. */
6985 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6986 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6987 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006988 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006989}
6990
6991PyObject *
6992PyUnicode_AsASCIIString(PyObject *unicode)
6993{
6994 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006995}
6996
Victor Stinner99b95382011-07-04 14:23:54 +02006997#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006998
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006999/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007000
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007001#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007002#define NEED_RETRY
7003#endif
7004
Victor Stinner3a50e702011-10-18 21:21:00 +02007005#ifndef WC_ERR_INVALID_CHARS
7006# define WC_ERR_INVALID_CHARS 0x0080
7007#endif
7008
7009static char*
7010code_page_name(UINT code_page, PyObject **obj)
7011{
7012 *obj = NULL;
7013 if (code_page == CP_ACP)
7014 return "mbcs";
7015 if (code_page == CP_UTF7)
7016 return "CP_UTF7";
7017 if (code_page == CP_UTF8)
7018 return "CP_UTF8";
7019
7020 *obj = PyBytes_FromFormat("cp%u", code_page);
7021 if (*obj == NULL)
7022 return NULL;
7023 return PyBytes_AS_STRING(*obj);
7024}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007025
Alexander Belopolsky40018472011-02-26 01:02:56 +00007026static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007027is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007028{
7029 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02007030 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007031
Victor Stinner3a50e702011-10-18 21:21:00 +02007032 if (!IsDBCSLeadByteEx(code_page, *curr))
7033 return 0;
7034
7035 prev = CharPrevExA(code_page, s, curr, 0);
7036 if (prev == curr)
7037 return 1;
7038 /* FIXME: This code is limited to "true" double-byte encodings,
7039 as it assumes an incomplete character consists of a single
7040 byte. */
7041 if (curr - prev == 2)
7042 return 1;
7043 if (!IsDBCSLeadByteEx(code_page, *prev))
7044 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007045 return 0;
7046}
7047
Victor Stinner3a50e702011-10-18 21:21:00 +02007048static DWORD
7049decode_code_page_flags(UINT code_page)
7050{
7051 if (code_page == CP_UTF7) {
7052 /* The CP_UTF7 decoder only supports flags=0 */
7053 return 0;
7054 }
7055 else
7056 return MB_ERR_INVALID_CHARS;
7057}
7058
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007059/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007060 * Decode a byte string from a Windows code page into unicode object in strict
7061 * mode.
7062 *
7063 * Returns consumed size if succeed, returns -2 on decode error, or raise a
7064 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007065 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007066static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007067decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007068 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007069 const char *in,
7070 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007071{
Victor Stinner3a50e702011-10-18 21:21:00 +02007072 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007073 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007074 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007075
7076 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007077 assert(insize > 0);
7078 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7079 if (outsize <= 0)
7080 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081
7082 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007083 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007084 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007085 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007086 if (*v == NULL)
7087 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007088 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007089 }
7090 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007091 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007092 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007093 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007094 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007095 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007096 }
7097
7098 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007099 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7100 if (outsize <= 0)
7101 goto error;
7102 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007103
Victor Stinner3a50e702011-10-18 21:21:00 +02007104error:
7105 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7106 return -2;
7107 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007108 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007109}
7110
Victor Stinner3a50e702011-10-18 21:21:00 +02007111/*
7112 * Decode a byte string from a code page into unicode object with an error
7113 * handler.
7114 *
7115 * Returns consumed size if succeed, or raise a WindowsError or
7116 * UnicodeDecodeError exception and returns -1 on error.
7117 */
7118static int
7119decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007120 PyObject **v,
7121 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007122 const char *errors)
7123{
7124 const char *startin = in;
7125 const char *endin = in + size;
7126 const DWORD flags = decode_code_page_flags(code_page);
7127 /* Ideally, we should get reason from FormatMessage. This is the Windows
7128 2000 English version of the message. */
7129 const char *reason = "No mapping for the Unicode character exists "
7130 "in the target code page.";
7131 /* each step cannot decode more than 1 character, but a character can be
7132 represented as a surrogate pair */
7133 wchar_t buffer[2], *startout, *out;
7134 int insize, outsize;
7135 PyObject *errorHandler = NULL;
7136 PyObject *exc = NULL;
7137 PyObject *encoding_obj = NULL;
7138 char *encoding;
7139 DWORD err;
7140 int ret = -1;
7141
7142 assert(size > 0);
7143
7144 encoding = code_page_name(code_page, &encoding_obj);
7145 if (encoding == NULL)
7146 return -1;
7147
7148 if (errors == NULL || strcmp(errors, "strict") == 0) {
7149 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7150 UnicodeDecodeError. */
7151 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7152 if (exc != NULL) {
7153 PyCodec_StrictErrors(exc);
7154 Py_CLEAR(exc);
7155 }
7156 goto error;
7157 }
7158
7159 if (*v == NULL) {
7160 /* Create unicode object */
7161 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7162 PyErr_NoMemory();
7163 goto error;
7164 }
Victor Stinnerab595942011-12-17 04:59:06 +01007165 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007166 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007167 if (*v == NULL)
7168 goto error;
7169 startout = PyUnicode_AS_UNICODE(*v);
7170 }
7171 else {
7172 /* Extend unicode object */
7173 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7174 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7175 PyErr_NoMemory();
7176 goto error;
7177 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007178 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007179 goto error;
7180 startout = PyUnicode_AS_UNICODE(*v) + n;
7181 }
7182
7183 /* Decode the byte string character per character */
7184 out = startout;
7185 while (in < endin)
7186 {
7187 /* Decode a character */
7188 insize = 1;
7189 do
7190 {
7191 outsize = MultiByteToWideChar(code_page, flags,
7192 in, insize,
7193 buffer, Py_ARRAY_LENGTH(buffer));
7194 if (outsize > 0)
7195 break;
7196 err = GetLastError();
7197 if (err != ERROR_NO_UNICODE_TRANSLATION
7198 && err != ERROR_INSUFFICIENT_BUFFER)
7199 {
7200 PyErr_SetFromWindowsErr(0);
7201 goto error;
7202 }
7203 insize++;
7204 }
7205 /* 4=maximum length of a UTF-8 sequence */
7206 while (insize <= 4 && (in + insize) <= endin);
7207
7208 if (outsize <= 0) {
7209 Py_ssize_t startinpos, endinpos, outpos;
7210
7211 startinpos = in - startin;
7212 endinpos = startinpos + 1;
7213 outpos = out - PyUnicode_AS_UNICODE(*v);
7214 if (unicode_decode_call_errorhandler(
7215 errors, &errorHandler,
7216 encoding, reason,
7217 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007218 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 {
7220 goto error;
7221 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007222 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007223 }
7224 else {
7225 in += insize;
7226 memcpy(out, buffer, outsize * sizeof(wchar_t));
7227 out += outsize;
7228 }
7229 }
7230
7231 /* write a NUL character at the end */
7232 *out = 0;
7233
7234 /* Extend unicode object */
7235 outsize = out - startout;
7236 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007237 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007238 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007239 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007240
7241error:
7242 Py_XDECREF(encoding_obj);
7243 Py_XDECREF(errorHandler);
7244 Py_XDECREF(exc);
7245 return ret;
7246}
7247
Victor Stinner3a50e702011-10-18 21:21:00 +02007248static PyObject *
7249decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007250 const char *s, Py_ssize_t size,
7251 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007252{
Victor Stinner76a31a62011-11-04 00:05:13 +01007253 PyObject *v = NULL;
7254 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007255
Victor Stinner3a50e702011-10-18 21:21:00 +02007256 if (code_page < 0) {
7257 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7258 return NULL;
7259 }
7260
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007261 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007262 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007263
Victor Stinner76a31a62011-11-04 00:05:13 +01007264 do
7265 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007266#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007267 if (size > INT_MAX) {
7268 chunk_size = INT_MAX;
7269 final = 0;
7270 done = 0;
7271 }
7272 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007273#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007274 {
7275 chunk_size = (int)size;
7276 final = (consumed == NULL);
7277 done = 1;
7278 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007279
Victor Stinner76a31a62011-11-04 00:05:13 +01007280 /* Skip trailing lead-byte unless 'final' is set */
7281 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7282 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007283
Victor Stinner76a31a62011-11-04 00:05:13 +01007284 if (chunk_size == 0 && done) {
7285 if (v != NULL)
7286 break;
7287 Py_INCREF(unicode_empty);
7288 return unicode_empty;
7289 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007290
Victor Stinner76a31a62011-11-04 00:05:13 +01007291
7292 converted = decode_code_page_strict(code_page, &v,
7293 s, chunk_size);
7294 if (converted == -2)
7295 converted = decode_code_page_errors(code_page, &v,
7296 s, chunk_size,
7297 errors);
7298 assert(converted != 0);
7299
7300 if (converted < 0) {
7301 Py_XDECREF(v);
7302 return NULL;
7303 }
7304
7305 if (consumed)
7306 *consumed += converted;
7307
7308 s += converted;
7309 size -= converted;
7310 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007311
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007312 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007313}
7314
Alexander Belopolsky40018472011-02-26 01:02:56 +00007315PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007316PyUnicode_DecodeCodePageStateful(int code_page,
7317 const char *s,
7318 Py_ssize_t size,
7319 const char *errors,
7320 Py_ssize_t *consumed)
7321{
7322 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7323}
7324
7325PyObject *
7326PyUnicode_DecodeMBCSStateful(const char *s,
7327 Py_ssize_t size,
7328 const char *errors,
7329 Py_ssize_t *consumed)
7330{
7331 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7332}
7333
7334PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007335PyUnicode_DecodeMBCS(const char *s,
7336 Py_ssize_t size,
7337 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007338{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007339 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7340}
7341
Victor Stinner3a50e702011-10-18 21:21:00 +02007342static DWORD
7343encode_code_page_flags(UINT code_page, const char *errors)
7344{
7345 if (code_page == CP_UTF8) {
7346 if (winver.dwMajorVersion >= 6)
7347 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7348 and later */
7349 return WC_ERR_INVALID_CHARS;
7350 else
7351 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7352 return 0;
7353 }
7354 else if (code_page == CP_UTF7) {
7355 /* CP_UTF7 only supports flags=0 */
7356 return 0;
7357 }
7358 else {
7359 if (errors != NULL && strcmp(errors, "replace") == 0)
7360 return 0;
7361 else
7362 return WC_NO_BEST_FIT_CHARS;
7363 }
7364}
7365
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007366/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007367 * Encode a Unicode string to a Windows code page into a byte string in strict
7368 * mode.
7369 *
7370 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7371 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007372 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007373static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007374encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007375 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007376 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007377{
Victor Stinner554f3f02010-06-16 23:33:54 +00007378 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007379 BOOL *pusedDefaultChar = &usedDefaultChar;
7380 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007381 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007382 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007383 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007384 const DWORD flags = encode_code_page_flags(code_page, NULL);
7385 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007386 /* Create a substring so that we can get the UTF-16 representation
7387 of just the slice under consideration. */
7388 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007389
Martin v. Löwis3d325192011-11-04 18:23:06 +01007390 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007391
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007393 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007394 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007395 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007396
Victor Stinner2fc507f2011-11-04 20:06:39 +01007397 substring = PyUnicode_Substring(unicode, offset, offset+len);
7398 if (substring == NULL)
7399 return -1;
7400 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7401 if (p == NULL) {
7402 Py_DECREF(substring);
7403 return -1;
7404 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007405
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007406 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007407 outsize = WideCharToMultiByte(code_page, flags,
7408 p, size,
7409 NULL, 0,
7410 NULL, pusedDefaultChar);
7411 if (outsize <= 0)
7412 goto error;
7413 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007414 if (pusedDefaultChar && *pusedDefaultChar) {
7415 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007416 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007417 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007418
Victor Stinner3a50e702011-10-18 21:21:00 +02007419 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007420 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007421 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007422 if (*outbytes == NULL) {
7423 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007424 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007425 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007426 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007427 }
7428 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007429 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007430 const Py_ssize_t n = PyBytes_Size(*outbytes);
7431 if (outsize > PY_SSIZE_T_MAX - n) {
7432 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007433 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007434 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007435 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007436 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7437 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007438 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007439 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007440 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007441 }
7442
7443 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007444 outsize = WideCharToMultiByte(code_page, flags,
7445 p, size,
7446 out, outsize,
7447 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007448 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007449 if (outsize <= 0)
7450 goto error;
7451 if (pusedDefaultChar && *pusedDefaultChar)
7452 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007453 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007454
Victor Stinner3a50e702011-10-18 21:21:00 +02007455error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007456 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007457 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7458 return -2;
7459 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007460 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007461}
7462
Victor Stinner3a50e702011-10-18 21:21:00 +02007463/*
7464 * Encode a Unicode string to a Windows code page into a byte string using a
7465 * error handler.
7466 *
7467 * Returns consumed characters if succeed, or raise a WindowsError and returns
7468 * -1 on other error.
7469 */
7470static int
7471encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007472 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007473 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007474{
Victor Stinner3a50e702011-10-18 21:21:00 +02007475 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007476 Py_ssize_t pos = unicode_offset;
7477 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007478 /* Ideally, we should get reason from FormatMessage. This is the Windows
7479 2000 English version of the message. */
7480 const char *reason = "invalid character";
7481 /* 4=maximum length of a UTF-8 sequence */
7482 char buffer[4];
7483 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7484 Py_ssize_t outsize;
7485 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007486 PyObject *errorHandler = NULL;
7487 PyObject *exc = NULL;
7488 PyObject *encoding_obj = NULL;
7489 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007490 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007491 PyObject *rep;
7492 int ret = -1;
7493
7494 assert(insize > 0);
7495
7496 encoding = code_page_name(code_page, &encoding_obj);
7497 if (encoding == NULL)
7498 return -1;
7499
7500 if (errors == NULL || strcmp(errors, "strict") == 0) {
7501 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7502 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007503 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007504 if (exc != NULL) {
7505 PyCodec_StrictErrors(exc);
7506 Py_DECREF(exc);
7507 }
7508 Py_XDECREF(encoding_obj);
7509 return -1;
7510 }
7511
7512 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7513 pusedDefaultChar = &usedDefaultChar;
7514 else
7515 pusedDefaultChar = NULL;
7516
7517 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7518 PyErr_NoMemory();
7519 goto error;
7520 }
7521 outsize = insize * Py_ARRAY_LENGTH(buffer);
7522
7523 if (*outbytes == NULL) {
7524 /* Create string object */
7525 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7526 if (*outbytes == NULL)
7527 goto error;
7528 out = PyBytes_AS_STRING(*outbytes);
7529 }
7530 else {
7531 /* Extend string object */
7532 Py_ssize_t n = PyBytes_Size(*outbytes);
7533 if (n > PY_SSIZE_T_MAX - outsize) {
7534 PyErr_NoMemory();
7535 goto error;
7536 }
7537 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7538 goto error;
7539 out = PyBytes_AS_STRING(*outbytes) + n;
7540 }
7541
7542 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007543 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007544 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007545 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7546 wchar_t chars[2];
7547 int charsize;
7548 if (ch < 0x10000) {
7549 chars[0] = (wchar_t)ch;
7550 charsize = 1;
7551 }
7552 else {
7553 ch -= 0x10000;
7554 chars[0] = 0xd800 + (ch >> 10);
7555 chars[1] = 0xdc00 + (ch & 0x3ff);
7556 charsize = 2;
7557 }
7558
Victor Stinner3a50e702011-10-18 21:21:00 +02007559 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007560 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007561 buffer, Py_ARRAY_LENGTH(buffer),
7562 NULL, pusedDefaultChar);
7563 if (outsize > 0) {
7564 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7565 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007566 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007567 memcpy(out, buffer, outsize);
7568 out += outsize;
7569 continue;
7570 }
7571 }
7572 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7573 PyErr_SetFromWindowsErr(0);
7574 goto error;
7575 }
7576
Victor Stinner3a50e702011-10-18 21:21:00 +02007577 rep = unicode_encode_call_errorhandler(
7578 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007579 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007580 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007581 if (rep == NULL)
7582 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007583 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007584
7585 if (PyBytes_Check(rep)) {
7586 outsize = PyBytes_GET_SIZE(rep);
7587 if (outsize != 1) {
7588 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7589 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7590 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7591 Py_DECREF(rep);
7592 goto error;
7593 }
7594 out = PyBytes_AS_STRING(*outbytes) + offset;
7595 }
7596 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7597 out += outsize;
7598 }
7599 else {
7600 Py_ssize_t i;
7601 enum PyUnicode_Kind kind;
7602 void *data;
7603
Benjamin Petersonbac79492012-01-14 13:34:47 -05007604 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007605 Py_DECREF(rep);
7606 goto error;
7607 }
7608
7609 outsize = PyUnicode_GET_LENGTH(rep);
7610 if (outsize != 1) {
7611 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7612 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7613 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7614 Py_DECREF(rep);
7615 goto error;
7616 }
7617 out = PyBytes_AS_STRING(*outbytes) + offset;
7618 }
7619 kind = PyUnicode_KIND(rep);
7620 data = PyUnicode_DATA(rep);
7621 for (i=0; i < outsize; i++) {
7622 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7623 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007624 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007625 encoding, unicode,
7626 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007627 "unable to encode error handler result to ASCII");
7628 Py_DECREF(rep);
7629 goto error;
7630 }
7631 *out = (unsigned char)ch;
7632 out++;
7633 }
7634 }
7635 Py_DECREF(rep);
7636 }
7637 /* write a NUL byte */
7638 *out = 0;
7639 outsize = out - PyBytes_AS_STRING(*outbytes);
7640 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7641 if (_PyBytes_Resize(outbytes, outsize) < 0)
7642 goto error;
7643 ret = 0;
7644
7645error:
7646 Py_XDECREF(encoding_obj);
7647 Py_XDECREF(errorHandler);
7648 Py_XDECREF(exc);
7649 return ret;
7650}
7651
Victor Stinner3a50e702011-10-18 21:21:00 +02007652static PyObject *
7653encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007654 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007655 const char *errors)
7656{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007657 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007658 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007659 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007660 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007661
Benjamin Petersonbac79492012-01-14 13:34:47 -05007662 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007663 return NULL;
7664 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007665
Victor Stinner3a50e702011-10-18 21:21:00 +02007666 if (code_page < 0) {
7667 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7668 return NULL;
7669 }
7670
Martin v. Löwis3d325192011-11-04 18:23:06 +01007671 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007672 return PyBytes_FromStringAndSize(NULL, 0);
7673
Victor Stinner7581cef2011-11-03 22:32:33 +01007674 offset = 0;
7675 do
7676 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007677#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007678 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007679 chunks. */
7680 if (len > INT_MAX/2) {
7681 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007682 done = 0;
7683 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007684 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007685#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007686 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007687 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007688 done = 1;
7689 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007690
Victor Stinner76a31a62011-11-04 00:05:13 +01007691 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007692 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007693 errors);
7694 if (ret == -2)
7695 ret = encode_code_page_errors(code_page, &outbytes,
7696 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007697 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007698 if (ret < 0) {
7699 Py_XDECREF(outbytes);
7700 return NULL;
7701 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007702
Victor Stinner7581cef2011-11-03 22:32:33 +01007703 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007704 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007705 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007706
Victor Stinner3a50e702011-10-18 21:21:00 +02007707 return outbytes;
7708}
7709
7710PyObject *
7711PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7712 Py_ssize_t size,
7713 const char *errors)
7714{
Victor Stinner7581cef2011-11-03 22:32:33 +01007715 PyObject *unicode, *res;
7716 unicode = PyUnicode_FromUnicode(p, size);
7717 if (unicode == NULL)
7718 return NULL;
7719 res = encode_code_page(CP_ACP, unicode, errors);
7720 Py_DECREF(unicode);
7721 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007722}
7723
7724PyObject *
7725PyUnicode_EncodeCodePage(int code_page,
7726 PyObject *unicode,
7727 const char *errors)
7728{
Victor Stinner7581cef2011-11-03 22:32:33 +01007729 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007730}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007731
Alexander Belopolsky40018472011-02-26 01:02:56 +00007732PyObject *
7733PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007734{
7735 if (!PyUnicode_Check(unicode)) {
7736 PyErr_BadArgument();
7737 return NULL;
7738 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007739 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007740}
7741
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007742#undef NEED_RETRY
7743
Victor Stinner99b95382011-07-04 14:23:54 +02007744#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007745
Guido van Rossumd57fd912000-03-10 22:53:23 +00007746/* --- Character Mapping Codec -------------------------------------------- */
7747
Alexander Belopolsky40018472011-02-26 01:02:56 +00007748PyObject *
7749PyUnicode_DecodeCharmap(const char *s,
7750 Py_ssize_t size,
7751 PyObject *mapping,
7752 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007753{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007754 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007755 Py_ssize_t startinpos;
7756 Py_ssize_t endinpos;
7757 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007758 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007759 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007760 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007761 PyObject *errorHandler = NULL;
7762 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007763
Guido van Rossumd57fd912000-03-10 22:53:23 +00007764 /* Default to Latin-1 */
7765 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007766 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007767
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007768 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007769 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007770 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007771 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007772 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007773 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007774 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007775 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007776 Py_ssize_t maplen;
7777 enum PyUnicode_Kind kind;
7778 void *data;
7779 Py_UCS4 x;
7780
Benjamin Petersonbac79492012-01-14 13:34:47 -05007781 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007782 return NULL;
7783
7784 maplen = PyUnicode_GET_LENGTH(mapping);
7785 data = PyUnicode_DATA(mapping);
7786 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007787 while (s < e) {
7788 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007789
Benjamin Peterson29060642009-01-31 22:14:21 +00007790 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007791 x = PyUnicode_READ(kind, data, ch);
7792 else
7793 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007794
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007795 if (x == 0xfffe)
7796 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007797 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007798 startinpos = s-starts;
7799 endinpos = startinpos+1;
7800 if (unicode_decode_call_errorhandler(
7801 errors, &errorHandler,
7802 "charmap", "character maps to <undefined>",
7803 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007804 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007805 goto onError;
7806 }
7807 continue;
7808 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007809
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007810 if (unicode_putchar(&v, &outpos, x) < 0)
7811 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007812 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007813 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007814 }
7815 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007816 while (s < e) {
7817 unsigned char ch = *s;
7818 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007819
Benjamin Peterson29060642009-01-31 22:14:21 +00007820 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7821 w = PyLong_FromLong((long)ch);
7822 if (w == NULL)
7823 goto onError;
7824 x = PyObject_GetItem(mapping, w);
7825 Py_DECREF(w);
7826 if (x == NULL) {
7827 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7828 /* No mapping found means: mapping is undefined. */
7829 PyErr_Clear();
7830 x = Py_None;
7831 Py_INCREF(x);
7832 } else
7833 goto onError;
7834 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007835
Benjamin Peterson29060642009-01-31 22:14:21 +00007836 /* Apply mapping */
7837 if (PyLong_Check(x)) {
7838 long value = PyLong_AS_LONG(x);
7839 if (value < 0 || value > 65535) {
7840 PyErr_SetString(PyExc_TypeError,
7841 "character mapping must be in range(65536)");
7842 Py_DECREF(x);
7843 goto onError;
7844 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007845 if (unicode_putchar(&v, &outpos, value) < 0)
7846 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007847 }
7848 else if (x == Py_None) {
7849 /* 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 Py_DECREF(x);
7858 goto onError;
7859 }
7860 Py_DECREF(x);
7861 continue;
7862 }
7863 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007864 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007865
Benjamin Petersonbac79492012-01-14 13:34:47 -05007866 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007867 goto onError;
7868 targetsize = PyUnicode_GET_LENGTH(x);
7869
7870 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007871 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007872 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007873 PyUnicode_READ_CHAR(x, 0)) < 0)
7874 goto onError;
7875 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007876 else if (targetsize > 1) {
7877 /* 1-n mapping */
7878 if (targetsize > extrachars) {
7879 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007880 Py_ssize_t needed = (targetsize - extrachars) + \
7881 (targetsize << 2);
7882 extrachars += needed;
7883 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007884 if (unicode_resize(&v,
7885 PyUnicode_GET_LENGTH(v) + needed) < 0)
7886 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007887 Py_DECREF(x);
7888 goto onError;
7889 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007890 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007891 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7892 goto onError;
7893 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7894 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007895 extrachars -= targetsize;
7896 }
7897 /* 1-0 mapping: skip the character */
7898 }
7899 else {
7900 /* wrong return value */
7901 PyErr_SetString(PyExc_TypeError,
7902 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007903 Py_DECREF(x);
7904 goto onError;
7905 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007906 Py_DECREF(x);
7907 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007908 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007909 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007910 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007911 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007912 Py_XDECREF(errorHandler);
7913 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007914 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007915
Benjamin Peterson29060642009-01-31 22:14:21 +00007916 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007917 Py_XDECREF(errorHandler);
7918 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007919 Py_XDECREF(v);
7920 return NULL;
7921}
7922
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007923/* Charmap encoding: the lookup table */
7924
Alexander Belopolsky40018472011-02-26 01:02:56 +00007925struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007926 PyObject_HEAD
7927 unsigned char level1[32];
7928 int count2, count3;
7929 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007930};
7931
7932static PyObject*
7933encoding_map_size(PyObject *obj, PyObject* args)
7934{
7935 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007936 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007937 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007938}
7939
7940static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007941 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007942 PyDoc_STR("Return the size (in bytes) of this object") },
7943 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007944};
7945
7946static void
7947encoding_map_dealloc(PyObject* o)
7948{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007949 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007950}
7951
7952static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007953 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007954 "EncodingMap", /*tp_name*/
7955 sizeof(struct encoding_map), /*tp_basicsize*/
7956 0, /*tp_itemsize*/
7957 /* methods */
7958 encoding_map_dealloc, /*tp_dealloc*/
7959 0, /*tp_print*/
7960 0, /*tp_getattr*/
7961 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007962 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007963 0, /*tp_repr*/
7964 0, /*tp_as_number*/
7965 0, /*tp_as_sequence*/
7966 0, /*tp_as_mapping*/
7967 0, /*tp_hash*/
7968 0, /*tp_call*/
7969 0, /*tp_str*/
7970 0, /*tp_getattro*/
7971 0, /*tp_setattro*/
7972 0, /*tp_as_buffer*/
7973 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7974 0, /*tp_doc*/
7975 0, /*tp_traverse*/
7976 0, /*tp_clear*/
7977 0, /*tp_richcompare*/
7978 0, /*tp_weaklistoffset*/
7979 0, /*tp_iter*/
7980 0, /*tp_iternext*/
7981 encoding_map_methods, /*tp_methods*/
7982 0, /*tp_members*/
7983 0, /*tp_getset*/
7984 0, /*tp_base*/
7985 0, /*tp_dict*/
7986 0, /*tp_descr_get*/
7987 0, /*tp_descr_set*/
7988 0, /*tp_dictoffset*/
7989 0, /*tp_init*/
7990 0, /*tp_alloc*/
7991 0, /*tp_new*/
7992 0, /*tp_free*/
7993 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007994};
7995
7996PyObject*
7997PyUnicode_BuildEncodingMap(PyObject* string)
7998{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007999 PyObject *result;
8000 struct encoding_map *mresult;
8001 int i;
8002 int need_dict = 0;
8003 unsigned char level1[32];
8004 unsigned char level2[512];
8005 unsigned char *mlevel1, *mlevel2, *mlevel3;
8006 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008007 int kind;
8008 void *data;
8009 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008011 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008012 PyErr_BadArgument();
8013 return NULL;
8014 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008015 kind = PyUnicode_KIND(string);
8016 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008017 memset(level1, 0xFF, sizeof level1);
8018 memset(level2, 0xFF, sizeof level2);
8019
8020 /* If there isn't a one-to-one mapping of NULL to \0,
8021 or if there are non-BMP characters, we need to use
8022 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008023 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008024 need_dict = 1;
8025 for (i = 1; i < 256; i++) {
8026 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008027 ch = PyUnicode_READ(kind, data, i);
8028 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008029 need_dict = 1;
8030 break;
8031 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008032 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008033 /* unmapped character */
8034 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008035 l1 = ch >> 11;
8036 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008037 if (level1[l1] == 0xFF)
8038 level1[l1] = count2++;
8039 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008040 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008041 }
8042
8043 if (count2 >= 0xFF || count3 >= 0xFF)
8044 need_dict = 1;
8045
8046 if (need_dict) {
8047 PyObject *result = PyDict_New();
8048 PyObject *key, *value;
8049 if (!result)
8050 return NULL;
8051 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008052 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008053 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008054 if (!key || !value)
8055 goto failed1;
8056 if (PyDict_SetItem(result, key, value) == -1)
8057 goto failed1;
8058 Py_DECREF(key);
8059 Py_DECREF(value);
8060 }
8061 return result;
8062 failed1:
8063 Py_XDECREF(key);
8064 Py_XDECREF(value);
8065 Py_DECREF(result);
8066 return NULL;
8067 }
8068
8069 /* Create a three-level trie */
8070 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8071 16*count2 + 128*count3 - 1);
8072 if (!result)
8073 return PyErr_NoMemory();
8074 PyObject_Init(result, &EncodingMapType);
8075 mresult = (struct encoding_map*)result;
8076 mresult->count2 = count2;
8077 mresult->count3 = count3;
8078 mlevel1 = mresult->level1;
8079 mlevel2 = mresult->level23;
8080 mlevel3 = mresult->level23 + 16*count2;
8081 memcpy(mlevel1, level1, 32);
8082 memset(mlevel2, 0xFF, 16*count2);
8083 memset(mlevel3, 0, 128*count3);
8084 count3 = 0;
8085 for (i = 1; i < 256; i++) {
8086 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008087 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008088 /* unmapped character */
8089 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008090 o1 = PyUnicode_READ(kind, data, i)>>11;
8091 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008092 i2 = 16*mlevel1[o1] + o2;
8093 if (mlevel2[i2] == 0xFF)
8094 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008095 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008096 i3 = 128*mlevel2[i2] + o3;
8097 mlevel3[i3] = i;
8098 }
8099 return result;
8100}
8101
8102static int
Victor Stinner22168992011-11-20 17:09:18 +01008103encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008104{
8105 struct encoding_map *map = (struct encoding_map*)mapping;
8106 int l1 = c>>11;
8107 int l2 = (c>>7) & 0xF;
8108 int l3 = c & 0x7F;
8109 int i;
8110
Victor Stinner22168992011-11-20 17:09:18 +01008111 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008112 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008113 if (c == 0)
8114 return 0;
8115 /* level 1*/
8116 i = map->level1[l1];
8117 if (i == 0xFF) {
8118 return -1;
8119 }
8120 /* level 2*/
8121 i = map->level23[16*i+l2];
8122 if (i == 0xFF) {
8123 return -1;
8124 }
8125 /* level 3 */
8126 i = map->level23[16*map->count2 + 128*i + l3];
8127 if (i == 0) {
8128 return -1;
8129 }
8130 return i;
8131}
8132
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008133/* Lookup the character ch in the mapping. If the character
8134 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008135 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008136static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008137charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008138{
Christian Heimes217cfd12007-12-02 14:31:20 +00008139 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008140 PyObject *x;
8141
8142 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008143 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008144 x = PyObject_GetItem(mapping, w);
8145 Py_DECREF(w);
8146 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008147 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8148 /* No mapping found means: mapping is undefined. */
8149 PyErr_Clear();
8150 x = Py_None;
8151 Py_INCREF(x);
8152 return x;
8153 } else
8154 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008155 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008156 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008157 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008158 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008159 long value = PyLong_AS_LONG(x);
8160 if (value < 0 || value > 255) {
8161 PyErr_SetString(PyExc_TypeError,
8162 "character mapping must be in range(256)");
8163 Py_DECREF(x);
8164 return NULL;
8165 }
8166 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008167 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008168 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008169 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008170 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008171 /* wrong return value */
8172 PyErr_Format(PyExc_TypeError,
8173 "character mapping must return integer, bytes or None, not %.400s",
8174 x->ob_type->tp_name);
8175 Py_DECREF(x);
8176 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008177 }
8178}
8179
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008180static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008181charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008182{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008183 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8184 /* exponentially overallocate to minimize reallocations */
8185 if (requiredsize < 2*outsize)
8186 requiredsize = 2*outsize;
8187 if (_PyBytes_Resize(outobj, requiredsize))
8188 return -1;
8189 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008190}
8191
Benjamin Peterson14339b62009-01-31 16:36:08 +00008192typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008193 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008194} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008195/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008196 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008197 space is available. Return a new reference to the object that
8198 was put in the output buffer, or Py_None, if the mapping was undefined
8199 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008200 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008201static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008202charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008203 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008204{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008205 PyObject *rep;
8206 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008207 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008208
Christian Heimes90aa7642007-12-19 02:45:37 +00008209 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008210 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008211 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008212 if (res == -1)
8213 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008214 if (outsize<requiredsize)
8215 if (charmapencode_resize(outobj, outpos, requiredsize))
8216 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008217 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008218 outstart[(*outpos)++] = (char)res;
8219 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008220 }
8221
8222 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008223 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008224 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008225 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008226 Py_DECREF(rep);
8227 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008228 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008229 if (PyLong_Check(rep)) {
8230 Py_ssize_t requiredsize = *outpos+1;
8231 if (outsize<requiredsize)
8232 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8233 Py_DECREF(rep);
8234 return enc_EXCEPTION;
8235 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008236 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008237 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008238 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008239 else {
8240 const char *repchars = PyBytes_AS_STRING(rep);
8241 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8242 Py_ssize_t requiredsize = *outpos+repsize;
8243 if (outsize<requiredsize)
8244 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8245 Py_DECREF(rep);
8246 return enc_EXCEPTION;
8247 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008248 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008249 memcpy(outstart + *outpos, repchars, repsize);
8250 *outpos += repsize;
8251 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008252 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008253 Py_DECREF(rep);
8254 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008255}
8256
8257/* handle an error in PyUnicode_EncodeCharmap
8258 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008259static int
8260charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008261 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008262 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008263 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008264 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008265{
8266 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008267 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008268 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008269 enum PyUnicode_Kind kind;
8270 void *data;
8271 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008272 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008273 Py_ssize_t collstartpos = *inpos;
8274 Py_ssize_t collendpos = *inpos+1;
8275 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008276 char *encoding = "charmap";
8277 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008278 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008279 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008280 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008281
Benjamin Petersonbac79492012-01-14 13:34:47 -05008282 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008283 return -1;
8284 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008285 /* find all unencodable characters */
8286 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008287 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008288 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008289 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008290 val = encoding_map_lookup(ch, mapping);
8291 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008292 break;
8293 ++collendpos;
8294 continue;
8295 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008296
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008297 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8298 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008299 if (rep==NULL)
8300 return -1;
8301 else if (rep!=Py_None) {
8302 Py_DECREF(rep);
8303 break;
8304 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008305 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008306 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008307 }
8308 /* cache callback name lookup
8309 * (if not done yet, i.e. it's the first error) */
8310 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008311 if ((errors==NULL) || (!strcmp(errors, "strict")))
8312 *known_errorHandler = 1;
8313 else if (!strcmp(errors, "replace"))
8314 *known_errorHandler = 2;
8315 else if (!strcmp(errors, "ignore"))
8316 *known_errorHandler = 3;
8317 else if (!strcmp(errors, "xmlcharrefreplace"))
8318 *known_errorHandler = 4;
8319 else
8320 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008321 }
8322 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008323 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008324 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008325 return -1;
8326 case 2: /* replace */
8327 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008328 x = charmapencode_output('?', mapping, res, respos);
8329 if (x==enc_EXCEPTION) {
8330 return -1;
8331 }
8332 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008333 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008334 return -1;
8335 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008336 }
8337 /* fall through */
8338 case 3: /* ignore */
8339 *inpos = collendpos;
8340 break;
8341 case 4: /* xmlcharrefreplace */
8342 /* generate replacement (temporarily (mis)uses p) */
8343 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008344 char buffer[2+29+1+1];
8345 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008346 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008347 for (cp = buffer; *cp; ++cp) {
8348 x = charmapencode_output(*cp, mapping, res, respos);
8349 if (x==enc_EXCEPTION)
8350 return -1;
8351 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008352 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008353 return -1;
8354 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008355 }
8356 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008357 *inpos = collendpos;
8358 break;
8359 default:
8360 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008361 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008362 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008363 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008364 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008365 if (PyBytes_Check(repunicode)) {
8366 /* Directly copy bytes result to output. */
8367 Py_ssize_t outsize = PyBytes_Size(*res);
8368 Py_ssize_t requiredsize;
8369 repsize = PyBytes_Size(repunicode);
8370 requiredsize = *respos + repsize;
8371 if (requiredsize > outsize)
8372 /* Make room for all additional bytes. */
8373 if (charmapencode_resize(res, respos, requiredsize)) {
8374 Py_DECREF(repunicode);
8375 return -1;
8376 }
8377 memcpy(PyBytes_AsString(*res) + *respos,
8378 PyBytes_AsString(repunicode), repsize);
8379 *respos += repsize;
8380 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008381 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008382 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008383 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008384 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008385 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008386 Py_DECREF(repunicode);
8387 return -1;
8388 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008389 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008390 data = PyUnicode_DATA(repunicode);
8391 kind = PyUnicode_KIND(repunicode);
8392 for (index = 0; index < repsize; index++) {
8393 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8394 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008395 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008396 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008397 return -1;
8398 }
8399 else if (x==enc_FAILED) {
8400 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008401 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008402 return -1;
8403 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008404 }
8405 *inpos = newpos;
8406 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008407 }
8408 return 0;
8409}
8410
Alexander Belopolsky40018472011-02-26 01:02:56 +00008411PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008412_PyUnicode_EncodeCharmap(PyObject *unicode,
8413 PyObject *mapping,
8414 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008415{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008416 /* output object */
8417 PyObject *res = NULL;
8418 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008419 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008420 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008421 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008422 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008423 PyObject *errorHandler = NULL;
8424 PyObject *exc = NULL;
8425 /* the following variable is used for caching string comparisons
8426 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8427 * 3=ignore, 4=xmlcharrefreplace */
8428 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008429
Benjamin Petersonbac79492012-01-14 13:34:47 -05008430 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008431 return NULL;
8432 size = PyUnicode_GET_LENGTH(unicode);
8433
Guido van Rossumd57fd912000-03-10 22:53:23 +00008434 /* Default to Latin-1 */
8435 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008436 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008437
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008438 /* allocate enough for a simple encoding without
8439 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008440 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008441 if (res == NULL)
8442 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008443 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008444 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008445
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008446 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008447 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008448 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008449 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008450 if (x==enc_EXCEPTION) /* error */
8451 goto onError;
8452 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008453 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008454 &exc,
8455 &known_errorHandler, &errorHandler, errors,
8456 &res, &respos)) {
8457 goto onError;
8458 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008459 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008460 else
8461 /* done with this character => adjust input position */
8462 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008463 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008464
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008465 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008466 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008467 if (_PyBytes_Resize(&res, respos) < 0)
8468 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008469
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008470 Py_XDECREF(exc);
8471 Py_XDECREF(errorHandler);
8472 return res;
8473
Benjamin Peterson29060642009-01-31 22:14:21 +00008474 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008475 Py_XDECREF(res);
8476 Py_XDECREF(exc);
8477 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008478 return NULL;
8479}
8480
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008481/* Deprecated */
8482PyObject *
8483PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8484 Py_ssize_t size,
8485 PyObject *mapping,
8486 const char *errors)
8487{
8488 PyObject *result;
8489 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8490 if (unicode == NULL)
8491 return NULL;
8492 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8493 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008494 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008495}
8496
Alexander Belopolsky40018472011-02-26 01:02:56 +00008497PyObject *
8498PyUnicode_AsCharmapString(PyObject *unicode,
8499 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008500{
8501 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 PyErr_BadArgument();
8503 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008504 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008505 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008506}
8507
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008508/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008509static void
8510make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008511 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008512 Py_ssize_t startpos, Py_ssize_t endpos,
8513 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008514{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008515 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008516 *exceptionObject = _PyUnicodeTranslateError_Create(
8517 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008518 }
8519 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008520 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8521 goto onError;
8522 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8523 goto onError;
8524 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8525 goto onError;
8526 return;
8527 onError:
8528 Py_DECREF(*exceptionObject);
8529 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008530 }
8531}
8532
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008533/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008534static void
8535raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008536 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008537 Py_ssize_t startpos, Py_ssize_t endpos,
8538 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008539{
8540 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008541 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008542 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008543 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008544}
8545
8546/* error handling callback helper:
8547 build arguments, call the callback and check the arguments,
8548 put the result into newpos and return the replacement string, which
8549 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008550static PyObject *
8551unicode_translate_call_errorhandler(const char *errors,
8552 PyObject **errorHandler,
8553 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008554 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008555 Py_ssize_t startpos, Py_ssize_t endpos,
8556 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008557{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008558 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008559
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008560 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008561 PyObject *restuple;
8562 PyObject *resunicode;
8563
8564 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008565 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008566 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008567 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008568 }
8569
8570 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008571 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008572 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008573 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008574
8575 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008576 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008577 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008578 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008579 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008580 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008581 Py_DECREF(restuple);
8582 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008583 }
8584 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008585 &resunicode, &i_newpos)) {
8586 Py_DECREF(restuple);
8587 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008588 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008589 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008590 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008591 else
8592 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008593 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008594 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8595 Py_DECREF(restuple);
8596 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008597 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008598 Py_INCREF(resunicode);
8599 Py_DECREF(restuple);
8600 return resunicode;
8601}
8602
8603/* Lookup the character ch in the mapping and put the result in result,
8604 which must be decrefed by the caller.
8605 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008606static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008607charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008608{
Christian Heimes217cfd12007-12-02 14:31:20 +00008609 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008610 PyObject *x;
8611
8612 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008613 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008614 x = PyObject_GetItem(mapping, w);
8615 Py_DECREF(w);
8616 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008617 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8618 /* No mapping found means: use 1:1 mapping. */
8619 PyErr_Clear();
8620 *result = NULL;
8621 return 0;
8622 } else
8623 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008624 }
8625 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008626 *result = x;
8627 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008628 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008629 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008630 long value = PyLong_AS_LONG(x);
8631 long max = PyUnicode_GetMax();
8632 if (value < 0 || value > max) {
8633 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008634 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008635 Py_DECREF(x);
8636 return -1;
8637 }
8638 *result = x;
8639 return 0;
8640 }
8641 else if (PyUnicode_Check(x)) {
8642 *result = x;
8643 return 0;
8644 }
8645 else {
8646 /* wrong return value */
8647 PyErr_SetString(PyExc_TypeError,
8648 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008649 Py_DECREF(x);
8650 return -1;
8651 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008652}
8653/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008654 if not reallocate and adjust various state variables.
8655 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008656static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008657charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008658 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008659{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008660 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008661 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008662 /* exponentially overallocate to minimize reallocations */
8663 if (requiredsize < 2 * oldsize)
8664 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008665 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8666 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008667 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008668 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008669 }
8670 return 0;
8671}
8672/* lookup the character, put the result in the output string and adjust
8673 various state variables. Return a new reference to the object that
8674 was put in the output buffer in *result, or Py_None, if the mapping was
8675 undefined (in which case no character was written).
8676 The called must decref result.
8677 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008678static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008679charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8680 PyObject *mapping, Py_UCS4 **output,
8681 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008682 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008683{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008684 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8685 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008686 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008687 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008688 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008689 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008690 }
8691 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008692 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008693 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008694 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008695 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008696 }
8697 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008698 Py_ssize_t repsize;
8699 if (PyUnicode_READY(*res) == -1)
8700 return -1;
8701 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 if (repsize==1) {
8703 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008704 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008705 }
8706 else if (repsize!=0) {
8707 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008708 Py_ssize_t requiredsize = *opos +
8709 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008710 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008711 Py_ssize_t i;
8712 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008713 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008714 for(i = 0; i < repsize; i++)
8715 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008716 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008717 }
8718 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008719 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008720 return 0;
8721}
8722
Alexander Belopolsky40018472011-02-26 01:02:56 +00008723PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008724_PyUnicode_TranslateCharmap(PyObject *input,
8725 PyObject *mapping,
8726 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008727{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008728 /* input object */
8729 char *idata;
8730 Py_ssize_t size, i;
8731 int kind;
8732 /* output buffer */
8733 Py_UCS4 *output = NULL;
8734 Py_ssize_t osize;
8735 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008736 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008737 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008738 char *reason = "character maps to <undefined>";
8739 PyObject *errorHandler = NULL;
8740 PyObject *exc = NULL;
8741 /* the following variable is used for caching string comparisons
8742 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8743 * 3=ignore, 4=xmlcharrefreplace */
8744 int known_errorHandler = -1;
8745
Guido van Rossumd57fd912000-03-10 22:53:23 +00008746 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008747 PyErr_BadArgument();
8748 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008749 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008750
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008751 if (PyUnicode_READY(input) == -1)
8752 return NULL;
8753 idata = (char*)PyUnicode_DATA(input);
8754 kind = PyUnicode_KIND(input);
8755 size = PyUnicode_GET_LENGTH(input);
8756 i = 0;
8757
8758 if (size == 0) {
8759 Py_INCREF(input);
8760 return input;
8761 }
8762
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008763 /* allocate enough for a simple 1:1 translation without
8764 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008765 osize = size;
8766 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8767 opos = 0;
8768 if (output == NULL) {
8769 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008770 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008771 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008772
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008773 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008774 /* try to encode it */
8775 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008776 if (charmaptranslate_output(input, i, mapping,
8777 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008778 Py_XDECREF(x);
8779 goto onError;
8780 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008781 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008782 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008783 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008784 else { /* untranslatable character */
8785 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8786 Py_ssize_t repsize;
8787 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008788 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008789 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008790 Py_ssize_t collstart = i;
8791 Py_ssize_t collend = i+1;
8792 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008793
Benjamin Peterson29060642009-01-31 22:14:21 +00008794 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008795 while (collend < size) {
8796 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008797 goto onError;
8798 Py_XDECREF(x);
8799 if (x!=Py_None)
8800 break;
8801 ++collend;
8802 }
8803 /* cache callback name lookup
8804 * (if not done yet, i.e. it's the first error) */
8805 if (known_errorHandler==-1) {
8806 if ((errors==NULL) || (!strcmp(errors, "strict")))
8807 known_errorHandler = 1;
8808 else if (!strcmp(errors, "replace"))
8809 known_errorHandler = 2;
8810 else if (!strcmp(errors, "ignore"))
8811 known_errorHandler = 3;
8812 else if (!strcmp(errors, "xmlcharrefreplace"))
8813 known_errorHandler = 4;
8814 else
8815 known_errorHandler = 0;
8816 }
8817 switch (known_errorHandler) {
8818 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008819 raise_translate_exception(&exc, input, collstart,
8820 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008821 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008822 case 2: /* replace */
8823 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008824 for (coll = collstart; coll<collend; coll++)
8825 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008826 /* fall through */
8827 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008828 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008829 break;
8830 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008831 /* generate replacement (temporarily (mis)uses i) */
8832 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008833 char buffer[2+29+1+1];
8834 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008835 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8836 if (charmaptranslate_makespace(&output, &osize,
8837 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008838 goto onError;
8839 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008840 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008841 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008842 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008843 break;
8844 default:
8845 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008846 reason, input, &exc,
8847 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008848 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008849 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008850 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008851 Py_DECREF(repunicode);
8852 goto onError;
8853 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008854 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008855 repsize = PyUnicode_GET_LENGTH(repunicode);
8856 if (charmaptranslate_makespace(&output, &osize,
8857 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008858 Py_DECREF(repunicode);
8859 goto onError;
8860 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008861 for (uni2 = 0; repsize-->0; ++uni2)
8862 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8863 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008864 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008865 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008866 }
8867 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008868 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8869 if (!res)
8870 goto onError;
8871 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008872 Py_XDECREF(exc);
8873 Py_XDECREF(errorHandler);
8874 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008875
Benjamin Peterson29060642009-01-31 22:14:21 +00008876 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008877 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008878 Py_XDECREF(exc);
8879 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008880 return NULL;
8881}
8882
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008883/* Deprecated. Use PyUnicode_Translate instead. */
8884PyObject *
8885PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8886 Py_ssize_t size,
8887 PyObject *mapping,
8888 const char *errors)
8889{
8890 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8891 if (!unicode)
8892 return NULL;
8893 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8894}
8895
Alexander Belopolsky40018472011-02-26 01:02:56 +00008896PyObject *
8897PyUnicode_Translate(PyObject *str,
8898 PyObject *mapping,
8899 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008900{
8901 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008902
Guido van Rossumd57fd912000-03-10 22:53:23 +00008903 str = PyUnicode_FromObject(str);
8904 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008905 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008906 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008907 Py_DECREF(str);
8908 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008909
Benjamin Peterson29060642009-01-31 22:14:21 +00008910 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008911 Py_XDECREF(str);
8912 return NULL;
8913}
Tim Petersced69f82003-09-16 20:30:58 +00008914
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008915static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008916fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008917{
8918 /* No need to call PyUnicode_READY(self) because this function is only
8919 called as a callback from fixup() which does it already. */
8920 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8921 const int kind = PyUnicode_KIND(self);
8922 void *data = PyUnicode_DATA(self);
8923 Py_UCS4 maxchar = 0, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008924 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008925 Py_ssize_t i;
8926
8927 for (i = 0; i < len; ++i) {
8928 ch = PyUnicode_READ(kind, data, i);
8929 fixed = 0;
8930 if (ch > 127) {
8931 if (Py_UNICODE_ISSPACE(ch))
8932 fixed = ' ';
8933 else {
8934 const int decimal = Py_UNICODE_TODECIMAL(ch);
8935 if (decimal >= 0)
8936 fixed = '0' + decimal;
8937 }
8938 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008939 modified = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008940 if (fixed > maxchar)
8941 maxchar = fixed;
8942 PyUnicode_WRITE(kind, data, i, fixed);
8943 }
8944 else if (ch > maxchar)
8945 maxchar = ch;
8946 }
8947 else if (ch > maxchar)
8948 maxchar = ch;
8949 }
8950
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008951 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008952}
8953
8954PyObject *
8955_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8956{
8957 if (!PyUnicode_Check(unicode)) {
8958 PyErr_BadInternalCall();
8959 return NULL;
8960 }
8961 if (PyUnicode_READY(unicode) == -1)
8962 return NULL;
8963 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8964 /* If the string is already ASCII, just return the same string */
8965 Py_INCREF(unicode);
8966 return unicode;
8967 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008968 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008969}
8970
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008971PyObject *
8972PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8973 Py_ssize_t length)
8974{
Victor Stinnerf0124502011-11-21 23:12:56 +01008975 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008976 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008977 Py_UCS4 maxchar;
8978 enum PyUnicode_Kind kind;
8979 void *data;
8980
Victor Stinner99d7ad02012-02-22 13:37:39 +01008981 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008982 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008983 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008984 if (ch > 127) {
8985 int decimal = Py_UNICODE_TODECIMAL(ch);
8986 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008987 ch = '0' + decimal;
Victor Stinner99d7ad02012-02-22 13:37:39 +01008988 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008989 }
8990 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008991
8992 /* Copy to a new string */
8993 decimal = PyUnicode_New(length, maxchar);
8994 if (decimal == NULL)
8995 return decimal;
8996 kind = PyUnicode_KIND(decimal);
8997 data = PyUnicode_DATA(decimal);
8998 /* Iterate over code points */
8999 for (i = 0; i < length; i++) {
9000 Py_UNICODE ch = s[i];
9001 if (ch > 127) {
9002 int decimal = Py_UNICODE_TODECIMAL(ch);
9003 if (decimal >= 0)
9004 ch = '0' + decimal;
9005 }
9006 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009007 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009008 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009009}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009010/* --- Decimal Encoder ---------------------------------------------------- */
9011
Alexander Belopolsky40018472011-02-26 01:02:56 +00009012int
9013PyUnicode_EncodeDecimal(Py_UNICODE *s,
9014 Py_ssize_t length,
9015 char *output,
9016 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009017{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009018 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009019 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009020 enum PyUnicode_Kind kind;
9021 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009022
9023 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009024 PyErr_BadArgument();
9025 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009026 }
9027
Victor Stinner42bf7752011-11-21 22:52:58 +01009028 unicode = PyUnicode_FromUnicode(s, length);
9029 if (unicode == NULL)
9030 return -1;
9031
Benjamin Petersonbac79492012-01-14 13:34:47 -05009032 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009033 Py_DECREF(unicode);
9034 return -1;
9035 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009036 kind = PyUnicode_KIND(unicode);
9037 data = PyUnicode_DATA(unicode);
9038
Victor Stinnerb84d7232011-11-22 01:50:07 +01009039 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009040 PyObject *exc;
9041 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009042 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009043 Py_ssize_t startpos;
9044
9045 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009046
Benjamin Peterson29060642009-01-31 22:14:21 +00009047 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009048 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009049 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009050 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009051 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009052 decimal = Py_UNICODE_TODECIMAL(ch);
9053 if (decimal >= 0) {
9054 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009055 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009056 continue;
9057 }
9058 if (0 < ch && ch < 256) {
9059 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009060 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009061 continue;
9062 }
Victor Stinner6345be92011-11-25 20:09:01 +01009063
Victor Stinner42bf7752011-11-21 22:52:58 +01009064 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009065 exc = NULL;
9066 raise_encode_exception(&exc, "decimal", unicode,
9067 startpos, startpos+1,
9068 "invalid decimal Unicode string");
9069 Py_XDECREF(exc);
9070 Py_DECREF(unicode);
9071 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009072 }
9073 /* 0-terminate the output string */
9074 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009075 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009076 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009077}
9078
Guido van Rossumd57fd912000-03-10 22:53:23 +00009079/* --- Helpers ------------------------------------------------------------ */
9080
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009081static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009082any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009083 Py_ssize_t start,
9084 Py_ssize_t end)
9085{
9086 int kind1, kind2, kind;
9087 void *buf1, *buf2;
9088 Py_ssize_t len1, len2, result;
9089
9090 kind1 = PyUnicode_KIND(s1);
9091 kind2 = PyUnicode_KIND(s2);
9092 kind = kind1 > kind2 ? kind1 : kind2;
9093 buf1 = PyUnicode_DATA(s1);
9094 buf2 = PyUnicode_DATA(s2);
9095 if (kind1 != kind)
9096 buf1 = _PyUnicode_AsKind(s1, kind);
9097 if (!buf1)
9098 return -2;
9099 if (kind2 != kind)
9100 buf2 = _PyUnicode_AsKind(s2, kind);
9101 if (!buf2) {
9102 if (kind1 != kind) PyMem_Free(buf1);
9103 return -2;
9104 }
9105 len1 = PyUnicode_GET_LENGTH(s1);
9106 len2 = PyUnicode_GET_LENGTH(s2);
9107
Victor Stinner794d5672011-10-10 03:21:36 +02009108 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009109 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009110 case PyUnicode_1BYTE_KIND:
9111 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9112 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9113 else
9114 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9115 break;
9116 case PyUnicode_2BYTE_KIND:
9117 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9118 break;
9119 case PyUnicode_4BYTE_KIND:
9120 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9121 break;
9122 default:
9123 assert(0); result = -2;
9124 }
9125 }
9126 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009127 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009128 case PyUnicode_1BYTE_KIND:
9129 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9130 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9131 else
9132 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9133 break;
9134 case PyUnicode_2BYTE_KIND:
9135 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9136 break;
9137 case PyUnicode_4BYTE_KIND:
9138 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9139 break;
9140 default:
9141 assert(0); result = -2;
9142 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009143 }
9144
9145 if (kind1 != kind)
9146 PyMem_Free(buf1);
9147 if (kind2 != kind)
9148 PyMem_Free(buf2);
9149
9150 return result;
9151}
9152
9153Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009154_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009155 Py_ssize_t n_buffer,
9156 void *digits, Py_ssize_t n_digits,
9157 Py_ssize_t min_width,
9158 const char *grouping,
9159 const char *thousands_sep)
9160{
Benjamin Petersonead6b532011-12-20 17:23:42 -06009161 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009162 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009163 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9164 return _PyUnicode_ascii_InsertThousandsGrouping(
9165 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9166 min_width, grouping, thousands_sep);
9167 else
9168 return _PyUnicode_ucs1_InsertThousandsGrouping(
9169 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9170 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009171 case PyUnicode_2BYTE_KIND:
9172 return _PyUnicode_ucs2_InsertThousandsGrouping(
9173 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9174 min_width, grouping, thousands_sep);
9175 case PyUnicode_4BYTE_KIND:
9176 return _PyUnicode_ucs4_InsertThousandsGrouping(
9177 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9178 min_width, grouping, thousands_sep);
9179 }
9180 assert(0);
9181 return -1;
9182}
9183
9184
Thomas Wouters477c8d52006-05-27 19:21:47 +00009185/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009186#define ADJUST_INDICES(start, end, len) \
9187 if (end > len) \
9188 end = len; \
9189 else if (end < 0) { \
9190 end += len; \
9191 if (end < 0) \
9192 end = 0; \
9193 } \
9194 if (start < 0) { \
9195 start += len; \
9196 if (start < 0) \
9197 start = 0; \
9198 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009199
Alexander Belopolsky40018472011-02-26 01:02:56 +00009200Py_ssize_t
9201PyUnicode_Count(PyObject *str,
9202 PyObject *substr,
9203 Py_ssize_t start,
9204 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009205{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009206 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009207 PyObject* str_obj;
9208 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009209 int kind1, kind2, kind;
9210 void *buf1 = NULL, *buf2 = NULL;
9211 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009212
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009213 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009214 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009215 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009216 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009217 if (!sub_obj) {
9218 Py_DECREF(str_obj);
9219 return -1;
9220 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009221 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009222 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009223 Py_DECREF(str_obj);
9224 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009225 }
Tim Petersced69f82003-09-16 20:30:58 +00009226
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009227 kind1 = PyUnicode_KIND(str_obj);
9228 kind2 = PyUnicode_KIND(sub_obj);
9229 kind = kind1 > kind2 ? kind1 : kind2;
9230 buf1 = PyUnicode_DATA(str_obj);
9231 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009232 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009233 if (!buf1)
9234 goto onError;
9235 buf2 = PyUnicode_DATA(sub_obj);
9236 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009237 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009238 if (!buf2)
9239 goto onError;
9240 len1 = PyUnicode_GET_LENGTH(str_obj);
9241 len2 = PyUnicode_GET_LENGTH(sub_obj);
9242
9243 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009244 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009245 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009246 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9247 result = asciilib_count(
9248 ((Py_UCS1*)buf1) + start, end - start,
9249 buf2, len2, PY_SSIZE_T_MAX
9250 );
9251 else
9252 result = ucs1lib_count(
9253 ((Py_UCS1*)buf1) + start, end - start,
9254 buf2, len2, PY_SSIZE_T_MAX
9255 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009256 break;
9257 case PyUnicode_2BYTE_KIND:
9258 result = ucs2lib_count(
9259 ((Py_UCS2*)buf1) + start, end - start,
9260 buf2, len2, PY_SSIZE_T_MAX
9261 );
9262 break;
9263 case PyUnicode_4BYTE_KIND:
9264 result = ucs4lib_count(
9265 ((Py_UCS4*)buf1) + start, end - start,
9266 buf2, len2, PY_SSIZE_T_MAX
9267 );
9268 break;
9269 default:
9270 assert(0); result = 0;
9271 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009272
9273 Py_DECREF(sub_obj);
9274 Py_DECREF(str_obj);
9275
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009276 if (kind1 != kind)
9277 PyMem_Free(buf1);
9278 if (kind2 != kind)
9279 PyMem_Free(buf2);
9280
Guido van Rossumd57fd912000-03-10 22:53:23 +00009281 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009282 onError:
9283 Py_DECREF(sub_obj);
9284 Py_DECREF(str_obj);
9285 if (kind1 != kind && buf1)
9286 PyMem_Free(buf1);
9287 if (kind2 != kind && buf2)
9288 PyMem_Free(buf2);
9289 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009290}
9291
Alexander Belopolsky40018472011-02-26 01:02:56 +00009292Py_ssize_t
9293PyUnicode_Find(PyObject *str,
9294 PyObject *sub,
9295 Py_ssize_t start,
9296 Py_ssize_t end,
9297 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009298{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009299 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009300
Guido van Rossumd57fd912000-03-10 22:53:23 +00009301 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009302 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009303 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009304 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009305 if (!sub) {
9306 Py_DECREF(str);
9307 return -2;
9308 }
9309 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9310 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009311 Py_DECREF(str);
9312 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009313 }
Tim Petersced69f82003-09-16 20:30:58 +00009314
Victor Stinner794d5672011-10-10 03:21:36 +02009315 result = any_find_slice(direction,
9316 str, sub, start, end
9317 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009318
Guido van Rossumd57fd912000-03-10 22:53:23 +00009319 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009320 Py_DECREF(sub);
9321
Guido van Rossumd57fd912000-03-10 22:53:23 +00009322 return result;
9323}
9324
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009325Py_ssize_t
9326PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9327 Py_ssize_t start, Py_ssize_t end,
9328 int direction)
9329{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009330 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009331 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009332 if (PyUnicode_READY(str) == -1)
9333 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009334 if (start < 0 || end < 0) {
9335 PyErr_SetString(PyExc_IndexError, "string index out of range");
9336 return -2;
9337 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009338 if (end > PyUnicode_GET_LENGTH(str))
9339 end = PyUnicode_GET_LENGTH(str);
9340 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009341 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9342 kind, end-start, ch, direction);
9343 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009344 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009345 else
9346 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009347}
9348
Alexander Belopolsky40018472011-02-26 01:02:56 +00009349static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009350tailmatch(PyObject *self,
9351 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009352 Py_ssize_t start,
9353 Py_ssize_t end,
9354 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009355{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009356 int kind_self;
9357 int kind_sub;
9358 void *data_self;
9359 void *data_sub;
9360 Py_ssize_t offset;
9361 Py_ssize_t i;
9362 Py_ssize_t end_sub;
9363
9364 if (PyUnicode_READY(self) == -1 ||
9365 PyUnicode_READY(substring) == -1)
9366 return 0;
9367
9368 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009369 return 1;
9370
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009371 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9372 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009373 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009374 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009375
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009376 kind_self = PyUnicode_KIND(self);
9377 data_self = PyUnicode_DATA(self);
9378 kind_sub = PyUnicode_KIND(substring);
9379 data_sub = PyUnicode_DATA(substring);
9380 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9381
9382 if (direction > 0)
9383 offset = end;
9384 else
9385 offset = start;
9386
9387 if (PyUnicode_READ(kind_self, data_self, offset) ==
9388 PyUnicode_READ(kind_sub, data_sub, 0) &&
9389 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9390 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9391 /* If both are of the same kind, memcmp is sufficient */
9392 if (kind_self == kind_sub) {
9393 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009394 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009395 data_sub,
9396 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009397 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009398 }
9399 /* otherwise we have to compare each character by first accesing it */
9400 else {
9401 /* We do not need to compare 0 and len(substring)-1 because
9402 the if statement above ensured already that they are equal
9403 when we end up here. */
9404 // TODO: honor direction and do a forward or backwards search
9405 for (i = 1; i < end_sub; ++i) {
9406 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9407 PyUnicode_READ(kind_sub, data_sub, i))
9408 return 0;
9409 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009410 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009411 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009412 }
9413
9414 return 0;
9415}
9416
Alexander Belopolsky40018472011-02-26 01:02:56 +00009417Py_ssize_t
9418PyUnicode_Tailmatch(PyObject *str,
9419 PyObject *substr,
9420 Py_ssize_t start,
9421 Py_ssize_t end,
9422 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009423{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009424 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009425
Guido van Rossumd57fd912000-03-10 22:53:23 +00009426 str = PyUnicode_FromObject(str);
9427 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009428 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009429 substr = PyUnicode_FromObject(substr);
9430 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009431 Py_DECREF(str);
9432 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009433 }
Tim Petersced69f82003-09-16 20:30:58 +00009434
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009435 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009436 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009437 Py_DECREF(str);
9438 Py_DECREF(substr);
9439 return result;
9440}
9441
Guido van Rossumd57fd912000-03-10 22:53:23 +00009442/* Apply fixfct filter to the Unicode object self and return a
9443 reference to the modified object */
9444
Alexander Belopolsky40018472011-02-26 01:02:56 +00009445static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009446fixup(PyObject *self,
9447 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009448{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009449 PyObject *u;
9450 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009451 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009452
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009453 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009454 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009455 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009456 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009457
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009458 /* fix functions return the new maximum character in a string,
9459 if the kind of the resulting unicode object does not change,
9460 everything is fine. Otherwise we need to change the string kind
9461 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009462 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009463
9464 if (maxchar_new == 0) {
9465 /* no changes */;
9466 if (PyUnicode_CheckExact(self)) {
9467 Py_DECREF(u);
9468 Py_INCREF(self);
9469 return self;
9470 }
9471 else
9472 return u;
9473 }
9474
9475 if (maxchar_new <= 127)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009476 maxchar_new = 127;
9477 else if (maxchar_new <= 255)
9478 maxchar_new = 255;
9479 else if (maxchar_new <= 65535)
9480 maxchar_new = 65535;
9481 else
Victor Stinner8faf8212011-12-08 22:14:11 +01009482 maxchar_new = MAX_UNICODE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009483
Victor Stinnereaab6042011-12-11 22:22:39 +01009484 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009485 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009486
9487 /* In case the maximum character changed, we need to
9488 convert the string to the new category. */
9489 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9490 if (v == NULL) {
9491 Py_DECREF(u);
9492 return NULL;
9493 }
9494 if (maxchar_new > maxchar_old) {
9495 /* If the maxchar increased so that the kind changed, not all
9496 characters are representable anymore and we need to fix the
9497 string again. This only happens in very few cases. */
9498 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
9499 maxchar_old = fixfct(v);
9500 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009501 }
9502 else {
Victor Stinnereaab6042011-12-11 22:22:39 +01009503 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009504 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009505 Py_DECREF(u);
9506 assert(_PyUnicode_CheckConsistency(v, 1));
9507 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009508}
9509
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009510static PyObject *
9511ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009512{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009513 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9514 char *resdata, *data = PyUnicode_DATA(self);
9515 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009516
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009517 res = PyUnicode_New(len, 127);
9518 if (res == NULL)
9519 return NULL;
9520 resdata = PyUnicode_DATA(res);
9521 if (lower)
9522 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009523 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009524 _Py_bytes_upper(resdata, data, len);
9525 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009526}
9527
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009528static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009529handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009530{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009531 Py_ssize_t j;
9532 int final_sigma;
9533 Py_UCS4 c;
9534 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009535
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009536 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9537
9538 where ! is a negation and \p{xxx} is a character with property xxx.
9539 */
9540 for (j = i - 1; j >= 0; j--) {
9541 c = PyUnicode_READ(kind, data, j);
9542 if (!_PyUnicode_IsCaseIgnorable(c))
9543 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009544 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009545 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9546 if (final_sigma) {
9547 for (j = i + 1; j < length; j++) {
9548 c = PyUnicode_READ(kind, data, j);
9549 if (!_PyUnicode_IsCaseIgnorable(c))
9550 break;
9551 }
9552 final_sigma = j == length || !_PyUnicode_IsCased(c);
9553 }
9554 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009555}
9556
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009557static int
9558lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9559 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009560{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009561 /* Obscure special case. */
9562 if (c == 0x3A3) {
9563 mapped[0] = handle_capital_sigma(kind, data, length, i);
9564 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009565 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009566 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009567}
9568
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009569static Py_ssize_t
9570do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009571{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009572 Py_ssize_t i, k = 0;
9573 int n_res, j;
9574 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009575
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009576 c = PyUnicode_READ(kind, data, 0);
9577 n_res = _PyUnicode_ToUpperFull(c, mapped);
9578 for (j = 0; j < n_res; j++) {
9579 if (mapped[j] > *maxchar)
9580 *maxchar = mapped[j];
9581 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009582 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009583 for (i = 1; i < length; i++) {
9584 c = PyUnicode_READ(kind, data, i);
9585 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9586 for (j = 0; j < n_res; j++) {
9587 if (mapped[j] > *maxchar)
9588 *maxchar = mapped[j];
9589 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009590 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009591 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009592 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009593}
9594
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009595static Py_ssize_t
9596do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9597 Py_ssize_t i, k = 0;
9598
9599 for (i = 0; i < length; i++) {
9600 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9601 int n_res, j;
9602 if (Py_UNICODE_ISUPPER(c)) {
9603 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9604 }
9605 else if (Py_UNICODE_ISLOWER(c)) {
9606 n_res = _PyUnicode_ToUpperFull(c, mapped);
9607 }
9608 else {
9609 n_res = 1;
9610 mapped[0] = c;
9611 }
9612 for (j = 0; j < n_res; j++) {
9613 if (mapped[j] > *maxchar)
9614 *maxchar = mapped[j];
9615 res[k++] = mapped[j];
9616 }
9617 }
9618 return k;
9619}
9620
9621static Py_ssize_t
9622do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9623 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009624{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009625 Py_ssize_t i, k = 0;
9626
9627 for (i = 0; i < length; i++) {
9628 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9629 int n_res, j;
9630 if (lower)
9631 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9632 else
9633 n_res = _PyUnicode_ToUpperFull(c, mapped);
9634 for (j = 0; j < n_res; j++) {
9635 if (mapped[j] > *maxchar)
9636 *maxchar = mapped[j];
9637 res[k++] = mapped[j];
9638 }
9639 }
9640 return k;
9641}
9642
9643static Py_ssize_t
9644do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9645{
9646 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9647}
9648
9649static Py_ssize_t
9650do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9651{
9652 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9653}
9654
Benjamin Petersone51757f2012-01-12 21:10:29 -05009655static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009656do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9657{
9658 Py_ssize_t i, k = 0;
9659
9660 for (i = 0; i < length; i++) {
9661 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9662 Py_UCS4 mapped[3];
9663 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9664 for (j = 0; j < n_res; j++) {
9665 if (mapped[j] > *maxchar)
9666 *maxchar = mapped[j];
9667 res[k++] = mapped[j];
9668 }
9669 }
9670 return k;
9671}
9672
9673static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009674do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9675{
9676 Py_ssize_t i, k = 0;
9677 int previous_is_cased;
9678
9679 previous_is_cased = 0;
9680 for (i = 0; i < length; i++) {
9681 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9682 Py_UCS4 mapped[3];
9683 int n_res, j;
9684
9685 if (previous_is_cased)
9686 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9687 else
9688 n_res = _PyUnicode_ToTitleFull(c, mapped);
9689
9690 for (j = 0; j < n_res; j++) {
9691 if (mapped[j] > *maxchar)
9692 *maxchar = mapped[j];
9693 res[k++] = mapped[j];
9694 }
9695
9696 previous_is_cased = _PyUnicode_IsCased(c);
9697 }
9698 return k;
9699}
9700
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009701static PyObject *
9702case_operation(PyObject *self,
9703 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9704{
9705 PyObject *res = NULL;
9706 Py_ssize_t length, newlength = 0;
9707 int kind, outkind;
9708 void *data, *outdata;
9709 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9710
Benjamin Petersoneea48462012-01-16 14:28:50 -05009711 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009712
9713 kind = PyUnicode_KIND(self);
9714 data = PyUnicode_DATA(self);
9715 length = PyUnicode_GET_LENGTH(self);
9716 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9717 if (tmp == NULL)
9718 return PyErr_NoMemory();
9719 newlength = perform(kind, data, length, tmp, &maxchar);
9720 res = PyUnicode_New(newlength, maxchar);
9721 if (res == NULL)
9722 goto leave;
9723 tmpend = tmp + newlength;
9724 outdata = PyUnicode_DATA(res);
9725 outkind = PyUnicode_KIND(res);
9726 switch (outkind) {
9727 case PyUnicode_1BYTE_KIND:
9728 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9729 break;
9730 case PyUnicode_2BYTE_KIND:
9731 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9732 break;
9733 case PyUnicode_4BYTE_KIND:
9734 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9735 break;
9736 default:
9737 assert(0);
9738 break;
9739 }
9740 leave:
9741 PyMem_FREE(tmp);
9742 return res;
9743}
9744
Tim Peters8ce9f162004-08-27 01:49:32 +00009745PyObject *
9746PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009747{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009748 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009749 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009750 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009751 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009752 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9753 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009754 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009755 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009756 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009757 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009758 int use_memcpy;
9759 unsigned char *res_data = NULL, *sep_data = NULL;
9760 PyObject *last_obj;
9761 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009762
Tim Peters05eba1f2004-08-27 21:32:02 +00009763 fseq = PySequence_Fast(seq, "");
9764 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009765 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009766 }
9767
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009768 /* NOTE: the following code can't call back into Python code,
9769 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009770 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009771
Tim Peters05eba1f2004-08-27 21:32:02 +00009772 seqlen = PySequence_Fast_GET_SIZE(fseq);
9773 /* If empty sequence, return u"". */
9774 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009775 Py_DECREF(fseq);
9776 Py_INCREF(unicode_empty);
9777 res = unicode_empty;
9778 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009779 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009780
Tim Peters05eba1f2004-08-27 21:32:02 +00009781 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009782 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009783 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009784 if (seqlen == 1) {
9785 if (PyUnicode_CheckExact(items[0])) {
9786 res = items[0];
9787 Py_INCREF(res);
9788 Py_DECREF(fseq);
9789 return res;
9790 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009791 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009792 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009793 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009794 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009795 /* Set up sep and seplen */
9796 if (separator == NULL) {
9797 /* fall back to a blank space separator */
9798 sep = PyUnicode_FromOrdinal(' ');
9799 if (!sep)
9800 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009801 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009802 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009803 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009804 else {
9805 if (!PyUnicode_Check(separator)) {
9806 PyErr_Format(PyExc_TypeError,
9807 "separator: expected str instance,"
9808 " %.80s found",
9809 Py_TYPE(separator)->tp_name);
9810 goto onError;
9811 }
9812 if (PyUnicode_READY(separator))
9813 goto onError;
9814 sep = separator;
9815 seplen = PyUnicode_GET_LENGTH(separator);
9816 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9817 /* inc refcount to keep this code path symmetric with the
9818 above case of a blank separator */
9819 Py_INCREF(sep);
9820 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009821 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009822 }
9823
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009824 /* There are at least two things to join, or else we have a subclass
9825 * of str in the sequence.
9826 * Do a pre-pass to figure out the total amount of space we'll
9827 * need (sz), and see whether all argument are strings.
9828 */
9829 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009830#ifdef Py_DEBUG
9831 use_memcpy = 0;
9832#else
9833 use_memcpy = 1;
9834#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009835 for (i = 0; i < seqlen; i++) {
9836 const Py_ssize_t old_sz = sz;
9837 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009838 if (!PyUnicode_Check(item)) {
9839 PyErr_Format(PyExc_TypeError,
9840 "sequence item %zd: expected str instance,"
9841 " %.80s found",
9842 i, Py_TYPE(item)->tp_name);
9843 goto onError;
9844 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009845 if (PyUnicode_READY(item) == -1)
9846 goto onError;
9847 sz += PyUnicode_GET_LENGTH(item);
9848 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009849 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009850 if (i != 0)
9851 sz += seplen;
9852 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9853 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009854 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009855 goto onError;
9856 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009857 if (use_memcpy && last_obj != NULL) {
9858 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9859 use_memcpy = 0;
9860 }
9861 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009862 }
Tim Petersced69f82003-09-16 20:30:58 +00009863
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009864 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009865 if (res == NULL)
9866 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009867
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009868 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009869#ifdef Py_DEBUG
9870 use_memcpy = 0;
9871#else
9872 if (use_memcpy) {
9873 res_data = PyUnicode_1BYTE_DATA(res);
9874 kind = PyUnicode_KIND(res);
9875 if (seplen != 0)
9876 sep_data = PyUnicode_1BYTE_DATA(sep);
9877 }
9878#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009879 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009880 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009881 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009882 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009883 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009884 if (use_memcpy) {
9885 Py_MEMCPY(res_data,
9886 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009887 kind * seplen);
9888 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009889 }
9890 else {
9891 copy_characters(res, res_offset, sep, 0, seplen);
9892 res_offset += seplen;
9893 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009894 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009895 itemlen = PyUnicode_GET_LENGTH(item);
9896 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009897 if (use_memcpy) {
9898 Py_MEMCPY(res_data,
9899 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009900 kind * itemlen);
9901 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009902 }
9903 else {
9904 copy_characters(res, res_offset, item, 0, itemlen);
9905 res_offset += itemlen;
9906 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009907 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009908 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009909 if (use_memcpy)
9910 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009911 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009912 else
9913 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009914
Tim Peters05eba1f2004-08-27 21:32:02 +00009915 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009916 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009917 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009918 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009919
Benjamin Peterson29060642009-01-31 22:14:21 +00009920 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009921 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009922 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009923 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009924 return NULL;
9925}
9926
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009927#define FILL(kind, data, value, start, length) \
9928 do { \
9929 Py_ssize_t i_ = 0; \
9930 assert(kind != PyUnicode_WCHAR_KIND); \
9931 switch ((kind)) { \
9932 case PyUnicode_1BYTE_KIND: { \
9933 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9934 memset(to_, (unsigned char)value, length); \
9935 break; \
9936 } \
9937 case PyUnicode_2BYTE_KIND: { \
9938 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9939 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9940 break; \
9941 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009942 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009943 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9944 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9945 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009946 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009947 } \
9948 } \
9949 } while (0)
9950
Victor Stinner3fe55312012-01-04 00:33:50 +01009951Py_ssize_t
9952PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9953 Py_UCS4 fill_char)
9954{
9955 Py_ssize_t maxlen;
9956 enum PyUnicode_Kind kind;
9957 void *data;
9958
9959 if (!PyUnicode_Check(unicode)) {
9960 PyErr_BadInternalCall();
9961 return -1;
9962 }
9963 if (PyUnicode_READY(unicode) == -1)
9964 return -1;
9965 if (unicode_check_modifiable(unicode))
9966 return -1;
9967
9968 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9969 PyErr_SetString(PyExc_ValueError,
9970 "fill character is bigger than "
9971 "the string maximum character");
9972 return -1;
9973 }
9974
9975 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9976 length = Py_MIN(maxlen, length);
9977 if (length <= 0)
9978 return 0;
9979
9980 kind = PyUnicode_KIND(unicode);
9981 data = PyUnicode_DATA(unicode);
9982 FILL(kind, data, fill_char, start, length);
9983 return length;
9984}
9985
Victor Stinner9310abb2011-10-05 00:59:23 +02009986static PyObject *
9987pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009988 Py_ssize_t left,
9989 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009990 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009991{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009992 PyObject *u;
9993 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009994 int kind;
9995 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009996
9997 if (left < 0)
9998 left = 0;
9999 if (right < 0)
10000 right = 0;
10001
Victor Stinnerc4b49542011-12-11 22:44:26 +010010002 if (left == 0 && right == 0)
10003 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010005 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10006 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010007 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10008 return NULL;
10009 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010010 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10011 if (fill > maxchar)
10012 maxchar = fill;
10013 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010014 if (!u)
10015 return NULL;
10016
10017 kind = PyUnicode_KIND(u);
10018 data = PyUnicode_DATA(u);
10019 if (left)
10020 FILL(kind, data, fill, 0, left);
10021 if (right)
10022 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010023 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010024 assert(_PyUnicode_CheckConsistency(u, 1));
10025 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010026}
10027
Alexander Belopolsky40018472011-02-26 01:02:56 +000010028PyObject *
10029PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010030{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010031 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010032
10033 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010034 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010035 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060010036 if (PyUnicode_READY(string) == -1) {
10037 Py_DECREF(string);
10038 return NULL;
10039 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010040
Benjamin Petersonead6b532011-12-20 17:23:42 -060010041 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010042 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010043 if (PyUnicode_IS_ASCII(string))
10044 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010045 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010046 PyUnicode_GET_LENGTH(string), keepends);
10047 else
10048 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010049 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010050 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010051 break;
10052 case PyUnicode_2BYTE_KIND:
10053 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010054 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010055 PyUnicode_GET_LENGTH(string), keepends);
10056 break;
10057 case PyUnicode_4BYTE_KIND:
10058 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010059 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010060 PyUnicode_GET_LENGTH(string), keepends);
10061 break;
10062 default:
10063 assert(0);
10064 list = 0;
10065 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010066 Py_DECREF(string);
10067 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010068}
10069
Alexander Belopolsky40018472011-02-26 01:02:56 +000010070static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010071split(PyObject *self,
10072 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010073 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010074{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010075 int kind1, kind2, kind;
10076 void *buf1, *buf2;
10077 Py_ssize_t len1, len2;
10078 PyObject* out;
10079
Guido van Rossumd57fd912000-03-10 22:53:23 +000010080 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010081 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010082
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010083 if (PyUnicode_READY(self) == -1)
10084 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010085
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010086 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010087 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010088 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010089 if (PyUnicode_IS_ASCII(self))
10090 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010091 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010092 PyUnicode_GET_LENGTH(self), maxcount
10093 );
10094 else
10095 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010096 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010097 PyUnicode_GET_LENGTH(self), maxcount
10098 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010099 case PyUnicode_2BYTE_KIND:
10100 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010101 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 PyUnicode_GET_LENGTH(self), maxcount
10103 );
10104 case PyUnicode_4BYTE_KIND:
10105 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010106 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010107 PyUnicode_GET_LENGTH(self), maxcount
10108 );
10109 default:
10110 assert(0);
10111 return NULL;
10112 }
10113
10114 if (PyUnicode_READY(substring) == -1)
10115 return NULL;
10116
10117 kind1 = PyUnicode_KIND(self);
10118 kind2 = PyUnicode_KIND(substring);
10119 kind = kind1 > kind2 ? kind1 : kind2;
10120 buf1 = PyUnicode_DATA(self);
10121 buf2 = PyUnicode_DATA(substring);
10122 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010123 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010124 if (!buf1)
10125 return NULL;
10126 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010127 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010128 if (!buf2) {
10129 if (kind1 != kind) PyMem_Free(buf1);
10130 return NULL;
10131 }
10132 len1 = PyUnicode_GET_LENGTH(self);
10133 len2 = PyUnicode_GET_LENGTH(substring);
10134
Benjamin Petersonead6b532011-12-20 17:23:42 -060010135 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010136 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010137 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10138 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010139 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010140 else
10141 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010142 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010143 break;
10144 case PyUnicode_2BYTE_KIND:
10145 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010146 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 break;
10148 case PyUnicode_4BYTE_KIND:
10149 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010150 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 break;
10152 default:
10153 out = NULL;
10154 }
10155 if (kind1 != kind)
10156 PyMem_Free(buf1);
10157 if (kind2 != kind)
10158 PyMem_Free(buf2);
10159 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010160}
10161
Alexander Belopolsky40018472011-02-26 01:02:56 +000010162static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010163rsplit(PyObject *self,
10164 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010165 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010166{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010167 int kind1, kind2, kind;
10168 void *buf1, *buf2;
10169 Py_ssize_t len1, len2;
10170 PyObject* out;
10171
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010172 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010173 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010174
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010175 if (PyUnicode_READY(self) == -1)
10176 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010177
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010178 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010179 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010180 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010181 if (PyUnicode_IS_ASCII(self))
10182 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010183 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010184 PyUnicode_GET_LENGTH(self), maxcount
10185 );
10186 else
10187 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010188 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010189 PyUnicode_GET_LENGTH(self), maxcount
10190 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191 case PyUnicode_2BYTE_KIND:
10192 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010193 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010194 PyUnicode_GET_LENGTH(self), maxcount
10195 );
10196 case PyUnicode_4BYTE_KIND:
10197 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010198 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010199 PyUnicode_GET_LENGTH(self), maxcount
10200 );
10201 default:
10202 assert(0);
10203 return NULL;
10204 }
10205
10206 if (PyUnicode_READY(substring) == -1)
10207 return NULL;
10208
10209 kind1 = PyUnicode_KIND(self);
10210 kind2 = PyUnicode_KIND(substring);
10211 kind = kind1 > kind2 ? kind1 : kind2;
10212 buf1 = PyUnicode_DATA(self);
10213 buf2 = PyUnicode_DATA(substring);
10214 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010215 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010216 if (!buf1)
10217 return NULL;
10218 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010219 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220 if (!buf2) {
10221 if (kind1 != kind) PyMem_Free(buf1);
10222 return NULL;
10223 }
10224 len1 = PyUnicode_GET_LENGTH(self);
10225 len2 = PyUnicode_GET_LENGTH(substring);
10226
Benjamin Petersonead6b532011-12-20 17:23:42 -060010227 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010228 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010229 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10230 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010231 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010232 else
10233 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010234 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010235 break;
10236 case PyUnicode_2BYTE_KIND:
10237 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010238 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239 break;
10240 case PyUnicode_4BYTE_KIND:
10241 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010242 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243 break;
10244 default:
10245 out = NULL;
10246 }
10247 if (kind1 != kind)
10248 PyMem_Free(buf1);
10249 if (kind2 != kind)
10250 PyMem_Free(buf2);
10251 return out;
10252}
10253
10254static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010255anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10256 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010257{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010258 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010259 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010260 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10261 return asciilib_find(buf1, len1, buf2, len2, offset);
10262 else
10263 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010264 case PyUnicode_2BYTE_KIND:
10265 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10266 case PyUnicode_4BYTE_KIND:
10267 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10268 }
10269 assert(0);
10270 return -1;
10271}
10272
10273static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010274anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10275 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010276{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010277 switch (kind) {
10278 case PyUnicode_1BYTE_KIND:
10279 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10280 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10281 else
10282 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10283 case PyUnicode_2BYTE_KIND:
10284 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10285 case PyUnicode_4BYTE_KIND:
10286 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10287 }
10288 assert(0);
10289 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010290}
10291
Alexander Belopolsky40018472011-02-26 01:02:56 +000010292static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293replace(PyObject *self, PyObject *str1,
10294 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010295{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010296 PyObject *u;
10297 char *sbuf = PyUnicode_DATA(self);
10298 char *buf1 = PyUnicode_DATA(str1);
10299 char *buf2 = PyUnicode_DATA(str2);
10300 int srelease = 0, release1 = 0, release2 = 0;
10301 int skind = PyUnicode_KIND(self);
10302 int kind1 = PyUnicode_KIND(str1);
10303 int kind2 = PyUnicode_KIND(str2);
10304 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10305 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10306 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010307 int mayshrink;
10308 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010309
10310 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010311 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010312 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010313 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010314
Victor Stinner59de0ee2011-10-07 10:01:28 +020010315 if (str1 == str2)
10316 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010317 if (skind < kind1)
10318 /* substring too wide to be present */
10319 goto nothing;
10320
Victor Stinner49a0a212011-10-12 23:46:10 +020010321 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10322 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10323 /* Replacing str1 with str2 may cause a maxchar reduction in the
10324 result string. */
10325 mayshrink = (maxchar_str2 < maxchar);
10326 maxchar = Py_MAX(maxchar, maxchar_str2);
10327
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010328 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010329 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010330 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010331 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010332 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010333 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010334 Py_UCS4 u1, u2;
10335 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010336 Py_ssize_t index, pos;
10337 char *src;
10338
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010339 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010340 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10341 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010342 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010343 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010344 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010345 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010346 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010347 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010348 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010349
10350 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10351 index = 0;
10352 src = sbuf;
10353 while (--maxcount)
10354 {
10355 pos++;
10356 src += pos * PyUnicode_KIND(self);
10357 slen -= pos;
10358 index += pos;
10359 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10360 if (pos < 0)
10361 break;
10362 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10363 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010364 }
10365 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010366 int rkind = skind;
10367 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010368 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010369
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010370 if (kind1 < rkind) {
10371 /* widen substring */
10372 buf1 = _PyUnicode_AsKind(str1, rkind);
10373 if (!buf1) goto error;
10374 release1 = 1;
10375 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010376 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010377 if (i < 0)
10378 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379 if (rkind > kind2) {
10380 /* widen replacement */
10381 buf2 = _PyUnicode_AsKind(str2, rkind);
10382 if (!buf2) goto error;
10383 release2 = 1;
10384 }
10385 else if (rkind < kind2) {
10386 /* widen self and buf1 */
10387 rkind = kind2;
10388 if (release1) PyMem_Free(buf1);
10389 sbuf = _PyUnicode_AsKind(self, rkind);
10390 if (!sbuf) goto error;
10391 srelease = 1;
10392 buf1 = _PyUnicode_AsKind(str1, rkind);
10393 if (!buf1) goto error;
10394 release1 = 1;
10395 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010396 u = PyUnicode_New(slen, maxchar);
10397 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010398 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010399 assert(PyUnicode_KIND(u) == rkind);
10400 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010401
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010402 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010403 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010404 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010406 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010407 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010408
10409 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010410 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010411 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010412 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010413 if (i == -1)
10414 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010415 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010416 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010417 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010418 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010419 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010420 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010421 }
10422 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010423 Py_ssize_t n, i, j, ires;
10424 Py_ssize_t product, new_size;
10425 int rkind = skind;
10426 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010427
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010428 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010429 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010430 buf1 = _PyUnicode_AsKind(str1, rkind);
10431 if (!buf1) goto error;
10432 release1 = 1;
10433 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010434 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010435 if (n == 0)
10436 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010437 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010438 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439 buf2 = _PyUnicode_AsKind(str2, rkind);
10440 if (!buf2) goto error;
10441 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010442 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010443 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010444 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010445 rkind = kind2;
10446 sbuf = _PyUnicode_AsKind(self, rkind);
10447 if (!sbuf) goto error;
10448 srelease = 1;
10449 if (release1) PyMem_Free(buf1);
10450 buf1 = _PyUnicode_AsKind(str1, rkind);
10451 if (!buf1) goto error;
10452 release1 = 1;
10453 }
10454 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10455 PyUnicode_GET_LENGTH(str1))); */
10456 product = n * (len2-len1);
10457 if ((product / (len2-len1)) != n) {
10458 PyErr_SetString(PyExc_OverflowError,
10459 "replace string is too long");
10460 goto error;
10461 }
10462 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010463 if (new_size == 0) {
10464 Py_INCREF(unicode_empty);
10465 u = unicode_empty;
10466 goto done;
10467 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10469 PyErr_SetString(PyExc_OverflowError,
10470 "replace string is too long");
10471 goto error;
10472 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010473 u = PyUnicode_New(new_size, maxchar);
10474 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010475 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010476 assert(PyUnicode_KIND(u) == rkind);
10477 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010478 ires = i = 0;
10479 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010480 while (n-- > 0) {
10481 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010482 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010483 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010484 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010485 if (j == -1)
10486 break;
10487 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010488 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010489 memcpy(res + rkind * ires,
10490 sbuf + rkind * i,
10491 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010492 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010493 }
10494 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010495 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010496 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010498 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010499 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010500 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010501 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010502 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010503 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010504 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010505 memcpy(res + rkind * ires,
10506 sbuf + rkind * i,
10507 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010508 }
10509 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010510 /* interleave */
10511 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010512 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010513 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010514 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010515 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010516 if (--n <= 0)
10517 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010518 memcpy(res + rkind * ires,
10519 sbuf + rkind * i,
10520 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010521 ires++;
10522 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010523 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010524 memcpy(res + rkind * ires,
10525 sbuf + rkind * i,
10526 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010527 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010528 }
10529
10530 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010531 unicode_adjust_maxchar(&u);
10532 if (u == NULL)
10533 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010534 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010535
10536 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010537 if (srelease)
10538 PyMem_FREE(sbuf);
10539 if (release1)
10540 PyMem_FREE(buf1);
10541 if (release2)
10542 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010543 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010544 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010545
Benjamin Peterson29060642009-01-31 22:14:21 +000010546 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010547 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010548 if (srelease)
10549 PyMem_FREE(sbuf);
10550 if (release1)
10551 PyMem_FREE(buf1);
10552 if (release2)
10553 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010554 return unicode_result_unchanged(self);
10555
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010556 error:
10557 if (srelease && sbuf)
10558 PyMem_FREE(sbuf);
10559 if (release1 && buf1)
10560 PyMem_FREE(buf1);
10561 if (release2 && buf2)
10562 PyMem_FREE(buf2);
10563 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010564}
10565
10566/* --- Unicode Object Methods --------------------------------------------- */
10567
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010568PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010569 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010570\n\
10571Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010572characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010573
10574static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010575unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010576{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010577 if (PyUnicode_READY(self) == -1)
10578 return NULL;
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010579 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010580}
10581
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010582PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010583 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010584\n\
10585Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010586have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010587
10588static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010589unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010590{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010591 if (PyUnicode_READY(self) == -1)
10592 return NULL;
10593 if (PyUnicode_GET_LENGTH(self) == 0)
10594 return unicode_result_unchanged(self);
10595 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010596}
10597
Benjamin Petersond5890c82012-01-14 13:23:30 -050010598PyDoc_STRVAR(casefold__doc__,
10599 "S.casefold() -> str\n\
10600\n\
10601Return a version of S suitable for caseless comparisons.");
10602
10603static PyObject *
10604unicode_casefold(PyObject *self)
10605{
10606 if (PyUnicode_READY(self) == -1)
10607 return NULL;
10608 if (PyUnicode_IS_ASCII(self))
10609 return ascii_upper_or_lower(self, 1);
10610 return case_operation(self, do_casefold);
10611}
10612
10613
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010614/* Argument converter. Coerces to a single unicode character */
10615
10616static int
10617convert_uc(PyObject *obj, void *addr)
10618{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010619 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010620 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010621
Benjamin Peterson14339b62009-01-31 16:36:08 +000010622 uniobj = PyUnicode_FromObject(obj);
10623 if (uniobj == NULL) {
10624 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010625 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010626 return 0;
10627 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010628 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010629 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010630 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010631 Py_DECREF(uniobj);
10632 return 0;
10633 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010634 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010635 Py_DECREF(uniobj);
10636 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010637}
10638
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010639PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010640 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010641\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010642Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010643done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010644
10645static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010646unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010647{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010648 Py_ssize_t marg, left;
10649 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010650 Py_UCS4 fillchar = ' ';
10651
Victor Stinnere9a29352011-10-01 02:14:59 +020010652 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010653 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010654
Benjamin Petersonbac79492012-01-14 13:34:47 -050010655 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010656 return NULL;
10657
Victor Stinnerc4b49542011-12-11 22:44:26 +010010658 if (PyUnicode_GET_LENGTH(self) >= width)
10659 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010660
Victor Stinnerc4b49542011-12-11 22:44:26 +010010661 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010662 left = marg / 2 + (marg & width & 1);
10663
Victor Stinner9310abb2011-10-05 00:59:23 +020010664 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010665}
10666
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010667/* This function assumes that str1 and str2 are readied by the caller. */
10668
Marc-André Lemburge5034372000-08-08 08:04:29 +000010669static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010670unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010671{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010672 int kind1, kind2;
10673 void *data1, *data2;
10674 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010675
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010676 kind1 = PyUnicode_KIND(str1);
10677 kind2 = PyUnicode_KIND(str2);
10678 data1 = PyUnicode_DATA(str1);
10679 data2 = PyUnicode_DATA(str2);
10680 len1 = PyUnicode_GET_LENGTH(str1);
10681 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010682
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010683 for (i = 0; i < len1 && i < len2; ++i) {
10684 Py_UCS4 c1, c2;
10685 c1 = PyUnicode_READ(kind1, data1, i);
10686 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010687
10688 if (c1 != c2)
10689 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010690 }
10691
10692 return (len1 < len2) ? -1 : (len1 != len2);
10693}
10694
Alexander Belopolsky40018472011-02-26 01:02:56 +000010695int
10696PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010697{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010698 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10699 if (PyUnicode_READY(left) == -1 ||
10700 PyUnicode_READY(right) == -1)
10701 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010702 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010703 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010704 PyErr_Format(PyExc_TypeError,
10705 "Can't compare %.100s and %.100s",
10706 left->ob_type->tp_name,
10707 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010708 return -1;
10709}
10710
Martin v. Löwis5b222132007-06-10 09:51:05 +000010711int
10712PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10713{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010714 Py_ssize_t i;
10715 int kind;
10716 void *data;
10717 Py_UCS4 chr;
10718
Victor Stinner910337b2011-10-03 03:20:16 +020010719 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010720 if (PyUnicode_READY(uni) == -1)
10721 return -1;
10722 kind = PyUnicode_KIND(uni);
10723 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010724 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010725 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10726 if (chr != str[i])
10727 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010728 /* This check keeps Python strings that end in '\0' from comparing equal
10729 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010730 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010731 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010732 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010733 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010734 return 0;
10735}
10736
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010737
Benjamin Peterson29060642009-01-31 22:14:21 +000010738#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010739 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010740
Alexander Belopolsky40018472011-02-26 01:02:56 +000010741PyObject *
10742PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010743{
10744 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010745
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010746 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10747 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010748 if (PyUnicode_READY(left) == -1 ||
10749 PyUnicode_READY(right) == -1)
10750 return NULL;
10751 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10752 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010753 if (op == Py_EQ) {
10754 Py_INCREF(Py_False);
10755 return Py_False;
10756 }
10757 if (op == Py_NE) {
10758 Py_INCREF(Py_True);
10759 return Py_True;
10760 }
10761 }
10762 if (left == right)
10763 result = 0;
10764 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010765 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010766
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010767 /* Convert the return value to a Boolean */
10768 switch (op) {
10769 case Py_EQ:
10770 v = TEST_COND(result == 0);
10771 break;
10772 case Py_NE:
10773 v = TEST_COND(result != 0);
10774 break;
10775 case Py_LE:
10776 v = TEST_COND(result <= 0);
10777 break;
10778 case Py_GE:
10779 v = TEST_COND(result >= 0);
10780 break;
10781 case Py_LT:
10782 v = TEST_COND(result == -1);
10783 break;
10784 case Py_GT:
10785 v = TEST_COND(result == 1);
10786 break;
10787 default:
10788 PyErr_BadArgument();
10789 return NULL;
10790 }
10791 Py_INCREF(v);
10792 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010793 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010794
Brian Curtindfc80e32011-08-10 20:28:54 -050010795 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010796}
10797
Alexander Belopolsky40018472011-02-26 01:02:56 +000010798int
10799PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010800{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010801 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010802 int kind1, kind2, kind;
10803 void *buf1, *buf2;
10804 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010805 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010806
10807 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010808 sub = PyUnicode_FromObject(element);
10809 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010810 PyErr_Format(PyExc_TypeError,
10811 "'in <string>' requires string as left operand, not %s",
10812 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010813 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010814 }
10815
Thomas Wouters477c8d52006-05-27 19:21:47 +000010816 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010817 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010818 Py_DECREF(sub);
10819 return -1;
10820 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010821 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10822 Py_DECREF(sub);
10823 Py_DECREF(str);
10824 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010826 kind1 = PyUnicode_KIND(str);
10827 kind2 = PyUnicode_KIND(sub);
10828 kind = kind1 > kind2 ? kind1 : kind2;
10829 buf1 = PyUnicode_DATA(str);
10830 buf2 = PyUnicode_DATA(sub);
10831 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010832 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010833 if (!buf1) {
10834 Py_DECREF(sub);
10835 return -1;
10836 }
10837 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010838 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010839 if (!buf2) {
10840 Py_DECREF(sub);
10841 if (kind1 != kind) PyMem_Free(buf1);
10842 return -1;
10843 }
10844 len1 = PyUnicode_GET_LENGTH(str);
10845 len2 = PyUnicode_GET_LENGTH(sub);
10846
Benjamin Petersonead6b532011-12-20 17:23:42 -060010847 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010848 case PyUnicode_1BYTE_KIND:
10849 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10850 break;
10851 case PyUnicode_2BYTE_KIND:
10852 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10853 break;
10854 case PyUnicode_4BYTE_KIND:
10855 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10856 break;
10857 default:
10858 result = -1;
10859 assert(0);
10860 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010861
10862 Py_DECREF(str);
10863 Py_DECREF(sub);
10864
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010865 if (kind1 != kind)
10866 PyMem_Free(buf1);
10867 if (kind2 != kind)
10868 PyMem_Free(buf2);
10869
Guido van Rossum403d68b2000-03-13 15:55:09 +000010870 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010871}
10872
Guido van Rossumd57fd912000-03-10 22:53:23 +000010873/* Concat to string or Unicode object giving a new Unicode object. */
10874
Alexander Belopolsky40018472011-02-26 01:02:56 +000010875PyObject *
10876PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010877{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010878 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010879 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010880 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010881
10882 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010883 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010884 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010885 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010886 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010887 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010888 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010889
10890 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010891 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010892 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010893 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010894 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010895 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010896 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010897 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010898 }
10899
Victor Stinner488fa492011-12-12 00:01:39 +010010900 u_len = PyUnicode_GET_LENGTH(u);
10901 v_len = PyUnicode_GET_LENGTH(v);
10902 if (u_len > PY_SSIZE_T_MAX - v_len) {
10903 PyErr_SetString(PyExc_OverflowError,
10904 "strings are too large to concat");
10905 goto onError;
10906 }
10907 new_len = u_len + v_len;
10908
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010909 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010910 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10911 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010912
Guido van Rossumd57fd912000-03-10 22:53:23 +000010913 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010914 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010915 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010916 goto onError;
Victor Stinner488fa492011-12-12 00:01:39 +010010917 copy_characters(w, 0, u, 0, u_len);
10918 copy_characters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010919 Py_DECREF(u);
10920 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010921 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010922 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010923
Benjamin Peterson29060642009-01-31 22:14:21 +000010924 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010925 Py_XDECREF(u);
10926 Py_XDECREF(v);
10927 return NULL;
10928}
10929
Walter Dörwald1ab83302007-05-18 17:15:44 +000010930void
Victor Stinner23e56682011-10-03 03:54:37 +020010931PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010932{
Victor Stinner23e56682011-10-03 03:54:37 +020010933 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010934 Py_UCS4 maxchar, maxchar2;
10935 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010936
10937 if (p_left == NULL) {
10938 if (!PyErr_Occurred())
10939 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010940 return;
10941 }
Victor Stinner23e56682011-10-03 03:54:37 +020010942 left = *p_left;
10943 if (right == NULL || !PyUnicode_Check(left)) {
10944 if (!PyErr_Occurred())
10945 PyErr_BadInternalCall();
10946 goto error;
10947 }
10948
Benjamin Petersonbac79492012-01-14 13:34:47 -050010949 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010950 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010951 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010952 goto error;
10953
Victor Stinner488fa492011-12-12 00:01:39 +010010954 /* Shortcuts */
10955 if (left == unicode_empty) {
10956 Py_DECREF(left);
10957 Py_INCREF(right);
10958 *p_left = right;
10959 return;
10960 }
10961 if (right == unicode_empty)
10962 return;
10963
10964 left_len = PyUnicode_GET_LENGTH(left);
10965 right_len = PyUnicode_GET_LENGTH(right);
10966 if (left_len > PY_SSIZE_T_MAX - right_len) {
10967 PyErr_SetString(PyExc_OverflowError,
10968 "strings are too large to concat");
10969 goto error;
10970 }
10971 new_len = left_len + right_len;
10972
10973 if (unicode_modifiable(left)
10974 && PyUnicode_CheckExact(right)
10975 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010976 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10977 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010978 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010979 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010980 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10981 {
10982 /* append inplace */
10983 if (unicode_resize(p_left, new_len) != 0) {
10984 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10985 * deallocated so it cannot be put back into
10986 * 'variable'. The MemoryError is raised when there
10987 * is no value in 'variable', which might (very
10988 * remotely) be a cause of incompatibilities.
10989 */
10990 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010991 }
Victor Stinner488fa492011-12-12 00:01:39 +010010992 /* copy 'right' into the newly allocated area of 'left' */
10993 copy_characters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010994 }
Victor Stinner488fa492011-12-12 00:01:39 +010010995 else {
10996 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10997 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
10998 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010999
Victor Stinner488fa492011-12-12 00:01:39 +010011000 /* Concat the two Unicode strings */
11001 res = PyUnicode_New(new_len, maxchar);
11002 if (res == NULL)
11003 goto error;
11004 copy_characters(res, 0, left, 0, left_len);
11005 copy_characters(res, left_len, right, 0, right_len);
11006 Py_DECREF(left);
11007 *p_left = res;
11008 }
11009 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011010 return;
11011
11012error:
Victor Stinner488fa492011-12-12 00:01:39 +010011013 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011014}
11015
11016void
11017PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11018{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011019 PyUnicode_Append(pleft, right);
11020 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011021}
11022
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011023PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011024 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011025\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011026Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011027string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011028interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011029
11030static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011031unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011032{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011033 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011034 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011035 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011036 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011037 int kind1, kind2, kind;
11038 void *buf1, *buf2;
11039 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011040
Jesus Ceaac451502011-04-20 17:09:23 +020011041 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11042 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011043 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011044
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011045 kind1 = PyUnicode_KIND(self);
11046 kind2 = PyUnicode_KIND(substring);
11047 kind = kind1 > kind2 ? kind1 : kind2;
11048 buf1 = PyUnicode_DATA(self);
11049 buf2 = PyUnicode_DATA(substring);
11050 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011051 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011052 if (!buf1) {
11053 Py_DECREF(substring);
11054 return NULL;
11055 }
11056 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011057 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011058 if (!buf2) {
11059 Py_DECREF(substring);
11060 if (kind1 != kind) PyMem_Free(buf1);
11061 return NULL;
11062 }
11063 len1 = PyUnicode_GET_LENGTH(self);
11064 len2 = PyUnicode_GET_LENGTH(substring);
11065
11066 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060011067 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011068 case PyUnicode_1BYTE_KIND:
11069 iresult = ucs1lib_count(
11070 ((Py_UCS1*)buf1) + start, end - start,
11071 buf2, len2, PY_SSIZE_T_MAX
11072 );
11073 break;
11074 case PyUnicode_2BYTE_KIND:
11075 iresult = ucs2lib_count(
11076 ((Py_UCS2*)buf1) + start, end - start,
11077 buf2, len2, PY_SSIZE_T_MAX
11078 );
11079 break;
11080 case PyUnicode_4BYTE_KIND:
11081 iresult = ucs4lib_count(
11082 ((Py_UCS4*)buf1) + start, end - start,
11083 buf2, len2, PY_SSIZE_T_MAX
11084 );
11085 break;
11086 default:
11087 assert(0); iresult = 0;
11088 }
11089
11090 result = PyLong_FromSsize_t(iresult);
11091
11092 if (kind1 != kind)
11093 PyMem_Free(buf1);
11094 if (kind2 != kind)
11095 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011096
11097 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011098
Guido van Rossumd57fd912000-03-10 22:53:23 +000011099 return result;
11100}
11101
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011102PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011103 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011104\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011105Encode S using the codec registered for encoding. Default encoding\n\
11106is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011107handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011108a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11109'xmlcharrefreplace' as well as any other name registered with\n\
11110codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011111
11112static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011113unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011114{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011115 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011116 char *encoding = NULL;
11117 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011118
Benjamin Peterson308d6372009-09-18 21:42:35 +000011119 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11120 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011121 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011122 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011123}
11124
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011125PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011126 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011127\n\
11128Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011129If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011130
11131static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011132unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011133{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011134 Py_ssize_t i, j, line_pos, src_len, incr;
11135 Py_UCS4 ch;
11136 PyObject *u;
11137 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011138 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011139 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011140 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011141
11142 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011143 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011144
Antoine Pitrou22425222011-10-04 19:10:51 +020011145 if (PyUnicode_READY(self) == -1)
11146 return NULL;
11147
Thomas Wouters7e474022000-07-16 12:04:32 +000011148 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011149 src_len = PyUnicode_GET_LENGTH(self);
11150 i = j = line_pos = 0;
11151 kind = PyUnicode_KIND(self);
11152 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011153 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011154 for (; i < src_len; i++) {
11155 ch = PyUnicode_READ(kind, src_data, i);
11156 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011157 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011158 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011159 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011160 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011161 goto overflow;
11162 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011163 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011164 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011165 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011166 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011167 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011168 goto overflow;
11169 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011170 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011171 if (ch == '\n' || ch == '\r')
11172 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011174 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011175 if (!found)
11176 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011177
Guido van Rossumd57fd912000-03-10 22:53:23 +000011178 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011179 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011180 if (!u)
11181 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011182 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011183
Antoine Pitroue71d5742011-10-04 15:55:09 +020011184 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011185
Antoine Pitroue71d5742011-10-04 15:55:09 +020011186 for (; i < src_len; i++) {
11187 ch = PyUnicode_READ(kind, src_data, i);
11188 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011189 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011190 incr = tabsize - (line_pos % tabsize);
11191 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011192 FILL(kind, dest_data, ' ', j, incr);
11193 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011194 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011195 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011196 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011197 line_pos++;
11198 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011199 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011200 if (ch == '\n' || ch == '\r')
11201 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011203 }
11204 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011205 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011206
Antoine Pitroue71d5742011-10-04 15:55:09 +020011207 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011208 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11209 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210}
11211
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011212PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011213 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011214\n\
11215Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011216such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011217arguments start and end are interpreted as in slice notation.\n\
11218\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011219Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011220
11221static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011222unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011223{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011224 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011225 Py_ssize_t start;
11226 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011227 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011228
Jesus Ceaac451502011-04-20 17:09:23 +020011229 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11230 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011231 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011232
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011233 if (PyUnicode_READY(self) == -1)
11234 return NULL;
11235 if (PyUnicode_READY(substring) == -1)
11236 return NULL;
11237
Victor Stinner7931d9a2011-11-04 00:22:48 +010011238 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011239
11240 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011241
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011242 if (result == -2)
11243 return NULL;
11244
Christian Heimes217cfd12007-12-02 14:31:20 +000011245 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011246}
11247
11248static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011249unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011250{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011251 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11252 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011253 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011254 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011255}
11256
Guido van Rossumc2504932007-09-18 19:42:40 +000011257/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011258 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011259static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011260unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011261{
Guido van Rossumc2504932007-09-18 19:42:40 +000011262 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011263 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011264
Benjamin Peterson69e97272012-02-21 11:08:50 -050011265 assert(_Py_HashSecret_Initialized);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011266 if (_PyUnicode_HASH(self) != -1)
11267 return _PyUnicode_HASH(self);
11268 if (PyUnicode_READY(self) == -1)
11269 return -1;
11270 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011271 /*
11272 We make the hash of the empty string be 0, rather than using
11273 (prefix ^ suffix), since this slightly obfuscates the hash secret
11274 */
11275 if (len == 0) {
11276 _PyUnicode_HASH(self) = 0;
11277 return 0;
11278 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011279
11280 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011281#define HASH(P) \
11282 x ^= (Py_uhash_t) *P << 7; \
11283 while (--len >= 0) \
11284 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011285
Georg Brandl2fb477c2012-02-21 00:33:36 +010011286 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011287 switch (PyUnicode_KIND(self)) {
11288 case PyUnicode_1BYTE_KIND: {
11289 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11290 HASH(c);
11291 break;
11292 }
11293 case PyUnicode_2BYTE_KIND: {
11294 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11295 HASH(s);
11296 break;
11297 }
11298 default: {
11299 Py_UCS4 *l;
11300 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11301 "Impossible switch case in unicode_hash");
11302 l = PyUnicode_4BYTE_DATA(self);
11303 HASH(l);
11304 break;
11305 }
11306 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011307 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11308 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011309
Guido van Rossumc2504932007-09-18 19:42:40 +000011310 if (x == -1)
11311 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011312 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011313 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011314}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011315#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011316
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011317PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011318 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011319\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011320Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011321
11322static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011323unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011325 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011326 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011327 Py_ssize_t start;
11328 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011329
Jesus Ceaac451502011-04-20 17:09:23 +020011330 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11331 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011332 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011333
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011334 if (PyUnicode_READY(self) == -1)
11335 return NULL;
11336 if (PyUnicode_READY(substring) == -1)
11337 return NULL;
11338
Victor Stinner7931d9a2011-11-04 00:22:48 +010011339 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011340
11341 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011342
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011343 if (result == -2)
11344 return NULL;
11345
Guido van Rossumd57fd912000-03-10 22:53:23 +000011346 if (result < 0) {
11347 PyErr_SetString(PyExc_ValueError, "substring not found");
11348 return NULL;
11349 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011350
Christian Heimes217cfd12007-12-02 14:31:20 +000011351 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011352}
11353
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011354PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011355 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011356\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011357Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011358at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011359
11360static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011361unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011362{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011363 Py_ssize_t i, length;
11364 int kind;
11365 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011366 int cased;
11367
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011368 if (PyUnicode_READY(self) == -1)
11369 return NULL;
11370 length = PyUnicode_GET_LENGTH(self);
11371 kind = PyUnicode_KIND(self);
11372 data = PyUnicode_DATA(self);
11373
Guido van Rossumd57fd912000-03-10 22:53:23 +000011374 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011375 if (length == 1)
11376 return PyBool_FromLong(
11377 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011378
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011379 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011380 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011381 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011382
Guido van Rossumd57fd912000-03-10 22:53:23 +000011383 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011384 for (i = 0; i < length; i++) {
11385 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011386
Benjamin Peterson29060642009-01-31 22:14:21 +000011387 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11388 return PyBool_FromLong(0);
11389 else if (!cased && Py_UNICODE_ISLOWER(ch))
11390 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011392 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011393}
11394
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011395PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011396 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011397\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011398Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011399at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011400
11401static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011402unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011403{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011404 Py_ssize_t i, length;
11405 int kind;
11406 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407 int cased;
11408
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011409 if (PyUnicode_READY(self) == -1)
11410 return NULL;
11411 length = PyUnicode_GET_LENGTH(self);
11412 kind = PyUnicode_KIND(self);
11413 data = PyUnicode_DATA(self);
11414
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011416 if (length == 1)
11417 return PyBool_FromLong(
11418 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011420 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011421 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011422 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011423
Guido van Rossumd57fd912000-03-10 22:53:23 +000011424 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011425 for (i = 0; i < length; i++) {
11426 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011427
Benjamin Peterson29060642009-01-31 22:14:21 +000011428 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11429 return PyBool_FromLong(0);
11430 else if (!cased && Py_UNICODE_ISUPPER(ch))
11431 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011433 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011434}
11435
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011436PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011437 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011438\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011439Return True if S is a titlecased string and there is at least one\n\
11440character in S, i.e. upper- and titlecase characters may only\n\
11441follow uncased characters and lowercase characters only cased ones.\n\
11442Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443
11444static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011445unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011446{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011447 Py_ssize_t i, length;
11448 int kind;
11449 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011450 int cased, previous_is_cased;
11451
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011452 if (PyUnicode_READY(self) == -1)
11453 return NULL;
11454 length = PyUnicode_GET_LENGTH(self);
11455 kind = PyUnicode_KIND(self);
11456 data = PyUnicode_DATA(self);
11457
Guido van Rossumd57fd912000-03-10 22:53:23 +000011458 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011459 if (length == 1) {
11460 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11461 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11462 (Py_UNICODE_ISUPPER(ch) != 0));
11463 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011464
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011465 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011466 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011467 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011468
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469 cased = 0;
11470 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011471 for (i = 0; i < length; i++) {
11472 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011473
Benjamin Peterson29060642009-01-31 22:14:21 +000011474 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11475 if (previous_is_cased)
11476 return PyBool_FromLong(0);
11477 previous_is_cased = 1;
11478 cased = 1;
11479 }
11480 else if (Py_UNICODE_ISLOWER(ch)) {
11481 if (!previous_is_cased)
11482 return PyBool_FromLong(0);
11483 previous_is_cased = 1;
11484 cased = 1;
11485 }
11486 else
11487 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011488 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011489 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011490}
11491
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011492PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011493 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011495Return True if all characters in S are whitespace\n\
11496and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497
11498static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011499unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011500{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011501 Py_ssize_t i, length;
11502 int kind;
11503 void *data;
11504
11505 if (PyUnicode_READY(self) == -1)
11506 return NULL;
11507 length = PyUnicode_GET_LENGTH(self);
11508 kind = PyUnicode_KIND(self);
11509 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510
Guido van Rossumd57fd912000-03-10 22:53:23 +000011511 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011512 if (length == 1)
11513 return PyBool_FromLong(
11514 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011515
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011516 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011517 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011518 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011519
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011520 for (i = 0; i < length; i++) {
11521 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011522 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011523 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011525 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011526}
11527
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011528PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011529 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011530\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011531Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011532and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011533
11534static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011535unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011536{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011537 Py_ssize_t i, length;
11538 int kind;
11539 void *data;
11540
11541 if (PyUnicode_READY(self) == -1)
11542 return NULL;
11543 length = PyUnicode_GET_LENGTH(self);
11544 kind = PyUnicode_KIND(self);
11545 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011546
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011547 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011548 if (length == 1)
11549 return PyBool_FromLong(
11550 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011551
11552 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011553 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011554 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011555
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011556 for (i = 0; i < length; i++) {
11557 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011558 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011559 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011560 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011561}
11562
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011563PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011564 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011565\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011566Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011567and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011568
11569static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011570unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011571{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011572 int kind;
11573 void *data;
11574 Py_ssize_t len, i;
11575
11576 if (PyUnicode_READY(self) == -1)
11577 return NULL;
11578
11579 kind = PyUnicode_KIND(self);
11580 data = PyUnicode_DATA(self);
11581 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011582
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011583 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011584 if (len == 1) {
11585 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11586 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11587 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011588
11589 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011590 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011591 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011592
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011593 for (i = 0; i < len; i++) {
11594 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011595 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011596 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011597 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011598 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011599}
11600
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011601PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011602 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011603\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011604Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011605False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606
11607static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011608unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011609{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011610 Py_ssize_t i, length;
11611 int kind;
11612 void *data;
11613
11614 if (PyUnicode_READY(self) == -1)
11615 return NULL;
11616 length = PyUnicode_GET_LENGTH(self);
11617 kind = PyUnicode_KIND(self);
11618 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011619
Guido van Rossumd57fd912000-03-10 22:53:23 +000011620 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011621 if (length == 1)
11622 return PyBool_FromLong(
11623 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011625 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011626 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011627 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011628
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011629 for (i = 0; i < length; i++) {
11630 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011631 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011632 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011633 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011634}
11635
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011636PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011637 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011638\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011639Return True if all characters in S are digits\n\
11640and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011641
11642static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011643unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011644{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011645 Py_ssize_t i, length;
11646 int kind;
11647 void *data;
11648
11649 if (PyUnicode_READY(self) == -1)
11650 return NULL;
11651 length = PyUnicode_GET_LENGTH(self);
11652 kind = PyUnicode_KIND(self);
11653 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011654
Guido van Rossumd57fd912000-03-10 22:53:23 +000011655 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011656 if (length == 1) {
11657 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11658 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11659 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011660
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011661 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011662 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011663 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011664
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011665 for (i = 0; i < length; i++) {
11666 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011667 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011668 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011669 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011670}
11671
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011672PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011673 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011674\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011675Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011676False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011677
11678static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011679unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011680{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 Py_ssize_t i, length;
11682 int kind;
11683 void *data;
11684
11685 if (PyUnicode_READY(self) == -1)
11686 return NULL;
11687 length = PyUnicode_GET_LENGTH(self);
11688 kind = PyUnicode_KIND(self);
11689 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011690
Guido van Rossumd57fd912000-03-10 22:53:23 +000011691 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011692 if (length == 1)
11693 return PyBool_FromLong(
11694 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011696 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011697 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011698 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011699
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011700 for (i = 0; i < length; i++) {
11701 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011702 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011704 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011705}
11706
Martin v. Löwis47383402007-08-15 07:32:56 +000011707int
11708PyUnicode_IsIdentifier(PyObject *self)
11709{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011710 int kind;
11711 void *data;
11712 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011713 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011714
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011715 if (PyUnicode_READY(self) == -1) {
11716 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011717 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011718 }
11719
11720 /* Special case for empty strings */
11721 if (PyUnicode_GET_LENGTH(self) == 0)
11722 return 0;
11723 kind = PyUnicode_KIND(self);
11724 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011725
11726 /* PEP 3131 says that the first character must be in
11727 XID_Start and subsequent characters in XID_Continue,
11728 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011729 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011730 letters, digits, underscore). However, given the current
11731 definition of XID_Start and XID_Continue, it is sufficient
11732 to check just for these, except that _ must be allowed
11733 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011734 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011735 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011736 return 0;
11737
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011738 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011739 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011740 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011741 return 1;
11742}
11743
11744PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011745 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011746\n\
11747Return True if S is a valid identifier according\n\
11748to the language definition.");
11749
11750static PyObject*
11751unicode_isidentifier(PyObject *self)
11752{
11753 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11754}
11755
Georg Brandl559e5d72008-06-11 18:37:52 +000011756PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011757 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011758\n\
11759Return True if all characters in S are considered\n\
11760printable in repr() or S is empty, False otherwise.");
11761
11762static PyObject*
11763unicode_isprintable(PyObject *self)
11764{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011765 Py_ssize_t i, length;
11766 int kind;
11767 void *data;
11768
11769 if (PyUnicode_READY(self) == -1)
11770 return NULL;
11771 length = PyUnicode_GET_LENGTH(self);
11772 kind = PyUnicode_KIND(self);
11773 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011774
11775 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011776 if (length == 1)
11777 return PyBool_FromLong(
11778 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011779
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011780 for (i = 0; i < length; i++) {
11781 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011782 Py_RETURN_FALSE;
11783 }
11784 }
11785 Py_RETURN_TRUE;
11786}
11787
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011788PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011789 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011790\n\
11791Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011792iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011793
11794static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011795unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011796{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011797 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011798}
11799
Martin v. Löwis18e16552006-02-15 17:27:45 +000011800static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011801unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011802{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011803 if (PyUnicode_READY(self) == -1)
11804 return -1;
11805 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011806}
11807
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011808PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011809 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011810\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011811Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011812done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011813
11814static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011815unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011816{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011817 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011818 Py_UCS4 fillchar = ' ';
11819
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011820 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011821 return NULL;
11822
Benjamin Petersonbac79492012-01-14 13:34:47 -050011823 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011824 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011825
Victor Stinnerc4b49542011-12-11 22:44:26 +010011826 if (PyUnicode_GET_LENGTH(self) >= width)
11827 return unicode_result_unchanged(self);
11828
11829 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011830}
11831
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011832PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011833 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011834\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011835Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011836
11837static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011838unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011839{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011840 if (PyUnicode_READY(self) == -1)
11841 return NULL;
11842 if (PyUnicode_IS_ASCII(self))
11843 return ascii_upper_or_lower(self, 1);
11844 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011845}
11846
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011847#define LEFTSTRIP 0
11848#define RIGHTSTRIP 1
11849#define BOTHSTRIP 2
11850
11851/* Arrays indexed by above */
11852static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11853
11854#define STRIPNAME(i) (stripformat[i]+3)
11855
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011856/* externally visible for str.strip(unicode) */
11857PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011858_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011859{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011860 void *data;
11861 int kind;
11862 Py_ssize_t i, j, len;
11863 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011864
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011865 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11866 return NULL;
11867
11868 kind = PyUnicode_KIND(self);
11869 data = PyUnicode_DATA(self);
11870 len = PyUnicode_GET_LENGTH(self);
11871 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11872 PyUnicode_DATA(sepobj),
11873 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011874
Benjamin Peterson14339b62009-01-31 16:36:08 +000011875 i = 0;
11876 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011877 while (i < len &&
11878 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011879 i++;
11880 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011881 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011882
Benjamin Peterson14339b62009-01-31 16:36:08 +000011883 j = len;
11884 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011885 do {
11886 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011887 } while (j >= i &&
11888 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011889 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011890 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011891
Victor Stinner7931d9a2011-11-04 00:22:48 +010011892 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011893}
11894
11895PyObject*
11896PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11897{
11898 unsigned char *data;
11899 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011900 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011901
Victor Stinnerde636f32011-10-01 03:55:54 +020011902 if (PyUnicode_READY(self) == -1)
11903 return NULL;
11904
11905 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11906
Victor Stinner12bab6d2011-10-01 01:53:49 +020011907 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Victor Stinnerc4b49542011-12-11 22:44:26 +010011908 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011909
Victor Stinner12bab6d2011-10-01 01:53:49 +020011910 length = end - start;
11911 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011912 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011913
Victor Stinnerde636f32011-10-01 03:55:54 +020011914 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011915 PyErr_SetString(PyExc_IndexError, "string index out of range");
11916 return NULL;
11917 }
11918
Victor Stinnerb9275c12011-10-05 14:01:42 +020011919 if (PyUnicode_IS_ASCII(self)) {
11920 kind = PyUnicode_KIND(self);
11921 data = PyUnicode_1BYTE_DATA(self);
11922 return unicode_fromascii(data + start, length);
11923 }
11924 else {
11925 kind = PyUnicode_KIND(self);
11926 data = PyUnicode_1BYTE_DATA(self);
11927 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011928 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011929 length);
11930 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011931}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011932
11933static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011934do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011935{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011936 int kind;
11937 void *data;
11938 Py_ssize_t len, i, j;
11939
11940 if (PyUnicode_READY(self) == -1)
11941 return NULL;
11942
11943 kind = PyUnicode_KIND(self);
11944 data = PyUnicode_DATA(self);
11945 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011946
Benjamin Peterson14339b62009-01-31 16:36:08 +000011947 i = 0;
11948 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011949 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011950 i++;
11951 }
11952 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011953
Benjamin Peterson14339b62009-01-31 16:36:08 +000011954 j = len;
11955 if (striptype != LEFTSTRIP) {
11956 do {
11957 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011958 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011959 j++;
11960 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011961
Victor Stinner7931d9a2011-11-04 00:22:48 +010011962 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011963}
11964
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011965
11966static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011967do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011968{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011969 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011970
Benjamin Peterson14339b62009-01-31 16:36:08 +000011971 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11972 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011973
Benjamin Peterson14339b62009-01-31 16:36:08 +000011974 if (sep != NULL && sep != Py_None) {
11975 if (PyUnicode_Check(sep))
11976 return _PyUnicode_XStrip(self, striptype, sep);
11977 else {
11978 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011979 "%s arg must be None or str",
11980 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011981 return NULL;
11982 }
11983 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011984
Benjamin Peterson14339b62009-01-31 16:36:08 +000011985 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011986}
11987
11988
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011989PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011990 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011991\n\
11992Return a copy of the string S with leading and trailing\n\
11993whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011994If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011995
11996static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011997unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011998{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011999 if (PyTuple_GET_SIZE(args) == 0)
12000 return do_strip(self, BOTHSTRIP); /* Common case */
12001 else
12002 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012003}
12004
12005
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012006PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012007 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012008\n\
12009Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012010If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012011
12012static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012013unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012014{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012015 if (PyTuple_GET_SIZE(args) == 0)
12016 return do_strip(self, LEFTSTRIP); /* Common case */
12017 else
12018 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012019}
12020
12021
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012022PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012023 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012024\n\
12025Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012026If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012027
12028static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012029unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012030{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012031 if (PyTuple_GET_SIZE(args) == 0)
12032 return do_strip(self, RIGHTSTRIP); /* Common case */
12033 else
12034 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012035}
12036
12037
Guido van Rossumd57fd912000-03-10 22:53:23 +000012038static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012039unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012040{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012041 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012042 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012043
Georg Brandl222de0f2009-04-12 12:01:50 +000012044 if (len < 1) {
12045 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020012046 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000012047 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012048
Victor Stinnerc4b49542011-12-11 22:44:26 +010012049 /* no repeat, return original string */
12050 if (len == 1)
12051 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012052
Benjamin Petersonbac79492012-01-14 13:34:47 -050012053 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012054 return NULL;
12055
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012056 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012057 PyErr_SetString(PyExc_OverflowError,
12058 "repeated string is too long");
12059 return NULL;
12060 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012061 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012062
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012063 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012064 if (!u)
12065 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012066 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012067
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012068 if (PyUnicode_GET_LENGTH(str) == 1) {
12069 const int kind = PyUnicode_KIND(str);
12070 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012071 if (kind == PyUnicode_1BYTE_KIND) {
12072 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012073 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012074 }
12075 else if (kind == PyUnicode_2BYTE_KIND) {
12076 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012077 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012078 ucs2[n] = fill_char;
12079 } else {
12080 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12081 assert(kind == PyUnicode_4BYTE_KIND);
12082 for (n = 0; n < len; ++n)
12083 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012084 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012085 }
12086 else {
12087 /* number of characters copied this far */
12088 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012089 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012090 char *to = (char *) PyUnicode_DATA(u);
12091 Py_MEMCPY(to, PyUnicode_DATA(str),
12092 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012093 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012094 n = (done <= nchars-done) ? done : nchars-done;
12095 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012096 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012097 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012098 }
12099
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012100 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012101 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012102}
12103
Alexander Belopolsky40018472011-02-26 01:02:56 +000012104PyObject *
12105PyUnicode_Replace(PyObject *obj,
12106 PyObject *subobj,
12107 PyObject *replobj,
12108 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012109{
12110 PyObject *self;
12111 PyObject *str1;
12112 PyObject *str2;
12113 PyObject *result;
12114
12115 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012116 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012117 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012118 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012119 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012120 Py_DECREF(self);
12121 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012122 }
12123 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012124 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012125 Py_DECREF(self);
12126 Py_DECREF(str1);
12127 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012128 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012129 if (PyUnicode_READY(self) == -1 ||
12130 PyUnicode_READY(str1) == -1 ||
12131 PyUnicode_READY(str2) == -1)
12132 result = NULL;
12133 else
12134 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012135 Py_DECREF(self);
12136 Py_DECREF(str1);
12137 Py_DECREF(str2);
12138 return result;
12139}
12140
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012141PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012142 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012143\n\
12144Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012145old replaced by new. If the optional argument count is\n\
12146given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012147
12148static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012149unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012150{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012151 PyObject *str1;
12152 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012153 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012154 PyObject *result;
12155
Martin v. Löwis18e16552006-02-15 17:27:45 +000012156 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012157 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012158 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012159 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012160 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012161 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012162 return NULL;
12163 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012164 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012165 Py_DECREF(str1);
12166 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012167 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012168 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12169 result = NULL;
12170 else
12171 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012172
12173 Py_DECREF(str1);
12174 Py_DECREF(str2);
12175 return result;
12176}
12177
Alexander Belopolsky40018472011-02-26 01:02:56 +000012178static PyObject *
12179unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012180{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012181 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012182 Py_ssize_t isize;
12183 Py_ssize_t osize, squote, dquote, i, o;
12184 Py_UCS4 max, quote;
12185 int ikind, okind;
12186 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012187
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012188 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012189 return NULL;
12190
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012191 isize = PyUnicode_GET_LENGTH(unicode);
12192 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012193
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012194 /* Compute length of output, quote characters, and
12195 maximum character */
12196 osize = 2; /* quotes */
12197 max = 127;
12198 squote = dquote = 0;
12199 ikind = PyUnicode_KIND(unicode);
12200 for (i = 0; i < isize; i++) {
12201 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12202 switch (ch) {
12203 case '\'': squote++; osize++; break;
12204 case '"': dquote++; osize++; break;
12205 case '\\': case '\t': case '\r': case '\n':
12206 osize += 2; break;
12207 default:
12208 /* Fast-path ASCII */
12209 if (ch < ' ' || ch == 0x7f)
12210 osize += 4; /* \xHH */
12211 else if (ch < 0x7f)
12212 osize++;
12213 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12214 osize++;
12215 max = ch > max ? ch : max;
12216 }
12217 else if (ch < 0x100)
12218 osize += 4; /* \xHH */
12219 else if (ch < 0x10000)
12220 osize += 6; /* \uHHHH */
12221 else
12222 osize += 10; /* \uHHHHHHHH */
12223 }
12224 }
12225
12226 quote = '\'';
12227 if (squote) {
12228 if (dquote)
12229 /* Both squote and dquote present. Use squote,
12230 and escape them */
12231 osize += squote;
12232 else
12233 quote = '"';
12234 }
12235
12236 repr = PyUnicode_New(osize, max);
12237 if (repr == NULL)
12238 return NULL;
12239 okind = PyUnicode_KIND(repr);
12240 odata = PyUnicode_DATA(repr);
12241
12242 PyUnicode_WRITE(okind, odata, 0, quote);
12243 PyUnicode_WRITE(okind, odata, osize-1, quote);
12244
12245 for (i = 0, o = 1; i < isize; i++) {
12246 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012247
12248 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012249 if ((ch == quote) || (ch == '\\')) {
12250 PyUnicode_WRITE(okind, odata, o++, '\\');
12251 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012252 continue;
12253 }
12254
Benjamin Peterson29060642009-01-31 22:14:21 +000012255 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012256 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012257 PyUnicode_WRITE(okind, odata, o++, '\\');
12258 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012259 }
12260 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012261 PyUnicode_WRITE(okind, odata, o++, '\\');
12262 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012263 }
12264 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012265 PyUnicode_WRITE(okind, odata, o++, '\\');
12266 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012267 }
12268
12269 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012270 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012271 PyUnicode_WRITE(okind, odata, o++, '\\');
12272 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012273 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12274 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012275 }
12276
Georg Brandl559e5d72008-06-11 18:37:52 +000012277 /* Copy ASCII characters as-is */
12278 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012279 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012280 }
12281
Benjamin Peterson29060642009-01-31 22:14:21 +000012282 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012283 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012284 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012285 (categories Z* and C* except ASCII space)
12286 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012287 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012288 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012289 if (ch <= 0xff) {
12290 PyUnicode_WRITE(okind, odata, o++, '\\');
12291 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012292 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12293 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012294 }
12295 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012296 else if (ch >= 0x10000) {
12297 PyUnicode_WRITE(okind, odata, o++, '\\');
12298 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012299 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12300 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12301 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12302 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12303 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12304 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12305 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12306 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012307 }
12308 /* Map 16-bit characters to '\uxxxx' */
12309 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012310 PyUnicode_WRITE(okind, odata, o++, '\\');
12311 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012312 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12313 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12314 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12315 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012316 }
12317 }
12318 /* Copy characters as-is */
12319 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012320 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012321 }
12322 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012323 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012324 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012325 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012326 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012327}
12328
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012329PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012330 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012331\n\
12332Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012333such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012334arguments start and end are interpreted as in slice notation.\n\
12335\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012336Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012337
12338static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012339unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012340{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012341 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012342 Py_ssize_t start;
12343 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012344 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012345
Jesus Ceaac451502011-04-20 17:09:23 +020012346 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12347 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012348 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012349
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012350 if (PyUnicode_READY(self) == -1)
12351 return NULL;
12352 if (PyUnicode_READY(substring) == -1)
12353 return NULL;
12354
Victor Stinner7931d9a2011-11-04 00:22:48 +010012355 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012356
12357 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012358
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012359 if (result == -2)
12360 return NULL;
12361
Christian Heimes217cfd12007-12-02 14:31:20 +000012362 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012363}
12364
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012365PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012366 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012367\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012368Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012369
12370static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012371unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012372{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012373 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012374 Py_ssize_t start;
12375 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012376 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012377
Jesus Ceaac451502011-04-20 17:09:23 +020012378 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12379 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012380 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012381
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012382 if (PyUnicode_READY(self) == -1)
12383 return NULL;
12384 if (PyUnicode_READY(substring) == -1)
12385 return NULL;
12386
Victor Stinner7931d9a2011-11-04 00:22:48 +010012387 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012388
12389 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012390
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012391 if (result == -2)
12392 return NULL;
12393
Guido van Rossumd57fd912000-03-10 22:53:23 +000012394 if (result < 0) {
12395 PyErr_SetString(PyExc_ValueError, "substring not found");
12396 return NULL;
12397 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012398
Christian Heimes217cfd12007-12-02 14:31:20 +000012399 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012400}
12401
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012402PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012403 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012404\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012405Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012406done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012407
12408static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012409unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012410{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012411 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012412 Py_UCS4 fillchar = ' ';
12413
Victor Stinnere9a29352011-10-01 02:14:59 +020012414 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012415 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012416
Benjamin Petersonbac79492012-01-14 13:34:47 -050012417 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012418 return NULL;
12419
Victor Stinnerc4b49542011-12-11 22:44:26 +010012420 if (PyUnicode_GET_LENGTH(self) >= width)
12421 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012422
Victor Stinnerc4b49542011-12-11 22:44:26 +010012423 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012424}
12425
Alexander Belopolsky40018472011-02-26 01:02:56 +000012426PyObject *
12427PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012428{
12429 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012430
Guido van Rossumd57fd912000-03-10 22:53:23 +000012431 s = PyUnicode_FromObject(s);
12432 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012433 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012434 if (sep != NULL) {
12435 sep = PyUnicode_FromObject(sep);
12436 if (sep == NULL) {
12437 Py_DECREF(s);
12438 return NULL;
12439 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012440 }
12441
Victor Stinner9310abb2011-10-05 00:59:23 +020012442 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012443
12444 Py_DECREF(s);
12445 Py_XDECREF(sep);
12446 return result;
12447}
12448
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012449PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012450 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012451\n\
12452Return a list of the words in S, using sep as the\n\
12453delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012454splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012455whitespace string is a separator and empty strings are\n\
12456removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012457
12458static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012459unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012460{
12461 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012462 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012463
Martin v. Löwis18e16552006-02-15 17:27:45 +000012464 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012465 return NULL;
12466
12467 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012468 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012469 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012470 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012471 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012472 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012473}
12474
Thomas Wouters477c8d52006-05-27 19:21:47 +000012475PyObject *
12476PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12477{
12478 PyObject* str_obj;
12479 PyObject* sep_obj;
12480 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012481 int kind1, kind2, kind;
12482 void *buf1 = NULL, *buf2 = NULL;
12483 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012484
12485 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012486 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012487 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012488 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012489 if (!sep_obj) {
12490 Py_DECREF(str_obj);
12491 return NULL;
12492 }
12493 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12494 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012495 Py_DECREF(str_obj);
12496 return NULL;
12497 }
12498
Victor Stinner14f8f022011-10-05 20:58:25 +020012499 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012500 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012501 kind = Py_MAX(kind1, kind2);
12502 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012503 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012504 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012505 if (!buf1)
12506 goto onError;
12507 buf2 = PyUnicode_DATA(sep_obj);
12508 if (kind2 != kind)
12509 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12510 if (!buf2)
12511 goto onError;
12512 len1 = PyUnicode_GET_LENGTH(str_obj);
12513 len2 = PyUnicode_GET_LENGTH(sep_obj);
12514
Benjamin Petersonead6b532011-12-20 17:23:42 -060012515 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012516 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012517 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12518 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12519 else
12520 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012521 break;
12522 case PyUnicode_2BYTE_KIND:
12523 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12524 break;
12525 case PyUnicode_4BYTE_KIND:
12526 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12527 break;
12528 default:
12529 assert(0);
12530 out = 0;
12531 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012532
12533 Py_DECREF(sep_obj);
12534 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012535 if (kind1 != kind)
12536 PyMem_Free(buf1);
12537 if (kind2 != kind)
12538 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012539
12540 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012541 onError:
12542 Py_DECREF(sep_obj);
12543 Py_DECREF(str_obj);
12544 if (kind1 != kind && buf1)
12545 PyMem_Free(buf1);
12546 if (kind2 != kind && buf2)
12547 PyMem_Free(buf2);
12548 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012549}
12550
12551
12552PyObject *
12553PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12554{
12555 PyObject* str_obj;
12556 PyObject* sep_obj;
12557 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012558 int kind1, kind2, kind;
12559 void *buf1 = NULL, *buf2 = NULL;
12560 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012561
12562 str_obj = PyUnicode_FromObject(str_in);
12563 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012564 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012565 sep_obj = PyUnicode_FromObject(sep_in);
12566 if (!sep_obj) {
12567 Py_DECREF(str_obj);
12568 return NULL;
12569 }
12570
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012571 kind1 = PyUnicode_KIND(str_in);
12572 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012573 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012574 buf1 = PyUnicode_DATA(str_in);
12575 if (kind1 != kind)
12576 buf1 = _PyUnicode_AsKind(str_in, kind);
12577 if (!buf1)
12578 goto onError;
12579 buf2 = PyUnicode_DATA(sep_obj);
12580 if (kind2 != kind)
12581 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12582 if (!buf2)
12583 goto onError;
12584 len1 = PyUnicode_GET_LENGTH(str_obj);
12585 len2 = PyUnicode_GET_LENGTH(sep_obj);
12586
Benjamin Petersonead6b532011-12-20 17:23:42 -060012587 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012588 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012589 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12590 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12591 else
12592 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012593 break;
12594 case PyUnicode_2BYTE_KIND:
12595 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12596 break;
12597 case PyUnicode_4BYTE_KIND:
12598 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12599 break;
12600 default:
12601 assert(0);
12602 out = 0;
12603 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012604
12605 Py_DECREF(sep_obj);
12606 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012607 if (kind1 != kind)
12608 PyMem_Free(buf1);
12609 if (kind2 != kind)
12610 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012611
12612 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012613 onError:
12614 Py_DECREF(sep_obj);
12615 Py_DECREF(str_obj);
12616 if (kind1 != kind && buf1)
12617 PyMem_Free(buf1);
12618 if (kind2 != kind && buf2)
12619 PyMem_Free(buf2);
12620 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012621}
12622
12623PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012624 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012625\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012626Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012627the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012628found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012629
12630static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012631unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012632{
Victor Stinner9310abb2011-10-05 00:59:23 +020012633 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012634}
12635
12636PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012637 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012638\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012639Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012640the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012641separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012642
12643static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012644unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012645{
Victor Stinner9310abb2011-10-05 00:59:23 +020012646 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012647}
12648
Alexander Belopolsky40018472011-02-26 01:02:56 +000012649PyObject *
12650PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012651{
12652 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012653
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012654 s = PyUnicode_FromObject(s);
12655 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012656 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012657 if (sep != NULL) {
12658 sep = PyUnicode_FromObject(sep);
12659 if (sep == NULL) {
12660 Py_DECREF(s);
12661 return NULL;
12662 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012663 }
12664
Victor Stinner9310abb2011-10-05 00:59:23 +020012665 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012666
12667 Py_DECREF(s);
12668 Py_XDECREF(sep);
12669 return result;
12670}
12671
12672PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012673 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012674\n\
12675Return a list of the words in S, using sep as the\n\
12676delimiter string, starting at the end of the string and\n\
12677working to the front. If maxsplit is given, at most maxsplit\n\
12678splits are done. If sep is not specified, any whitespace string\n\
12679is a separator.");
12680
12681static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012682unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012683{
12684 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012685 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012686
Martin v. Löwis18e16552006-02-15 17:27:45 +000012687 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012688 return NULL;
12689
12690 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012691 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012692 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012693 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012694 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012695 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012696}
12697
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012698PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012699 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012700\n\
12701Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012702Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012703is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012704
12705static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012706unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012707{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012708 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012709 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012710
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012711 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12712 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012713 return NULL;
12714
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012715 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012716}
12717
12718static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012719PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012720{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012721 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012722}
12723
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012724PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012725 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012726\n\
12727Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012728and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012729
12730static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012731unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012732{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012733 if (PyUnicode_READY(self) == -1)
12734 return NULL;
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012735 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012736}
12737
Georg Brandlceee0772007-11-27 23:48:05 +000012738PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012739 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012740\n\
12741Return a translation table usable for str.translate().\n\
12742If there is only one argument, it must be a dictionary mapping Unicode\n\
12743ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012744Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012745If there are two arguments, they must be strings of equal length, and\n\
12746in the resulting dictionary, each character in x will be mapped to the\n\
12747character at the same position in y. If there is a third argument, it\n\
12748must be a string, whose characters will be mapped to None in the result.");
12749
12750static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012751unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012752{
12753 PyObject *x, *y = NULL, *z = NULL;
12754 PyObject *new = NULL, *key, *value;
12755 Py_ssize_t i = 0;
12756 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012757
Georg Brandlceee0772007-11-27 23:48:05 +000012758 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12759 return NULL;
12760 new = PyDict_New();
12761 if (!new)
12762 return NULL;
12763 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012764 int x_kind, y_kind, z_kind;
12765 void *x_data, *y_data, *z_data;
12766
Georg Brandlceee0772007-11-27 23:48:05 +000012767 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012768 if (!PyUnicode_Check(x)) {
12769 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12770 "be a string if there is a second argument");
12771 goto err;
12772 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012773 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012774 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12775 "arguments must have equal length");
12776 goto err;
12777 }
12778 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012779 x_kind = PyUnicode_KIND(x);
12780 y_kind = PyUnicode_KIND(y);
12781 x_data = PyUnicode_DATA(x);
12782 y_data = PyUnicode_DATA(y);
12783 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12784 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012785 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012786 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012787 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012788 if (!value) {
12789 Py_DECREF(key);
12790 goto err;
12791 }
Georg Brandlceee0772007-11-27 23:48:05 +000012792 res = PyDict_SetItem(new, key, value);
12793 Py_DECREF(key);
12794 Py_DECREF(value);
12795 if (res < 0)
12796 goto err;
12797 }
12798 /* create entries for deleting chars in z */
12799 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012800 z_kind = PyUnicode_KIND(z);
12801 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012802 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012803 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012804 if (!key)
12805 goto err;
12806 res = PyDict_SetItem(new, key, Py_None);
12807 Py_DECREF(key);
12808 if (res < 0)
12809 goto err;
12810 }
12811 }
12812 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012813 int kind;
12814 void *data;
12815
Georg Brandlceee0772007-11-27 23:48:05 +000012816 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012817 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012818 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12819 "to maketrans it must be a dict");
12820 goto err;
12821 }
12822 /* copy entries into the new dict, converting string keys to int keys */
12823 while (PyDict_Next(x, &i, &key, &value)) {
12824 if (PyUnicode_Check(key)) {
12825 /* convert string keys to integer keys */
12826 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012827 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012828 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12829 "table must be of length 1");
12830 goto err;
12831 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012832 kind = PyUnicode_KIND(key);
12833 data = PyUnicode_DATA(key);
12834 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012835 if (!newkey)
12836 goto err;
12837 res = PyDict_SetItem(new, newkey, value);
12838 Py_DECREF(newkey);
12839 if (res < 0)
12840 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012841 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012842 /* just keep integer keys */
12843 if (PyDict_SetItem(new, key, value) < 0)
12844 goto err;
12845 } else {
12846 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12847 "be strings or integers");
12848 goto err;
12849 }
12850 }
12851 }
12852 return new;
12853 err:
12854 Py_DECREF(new);
12855 return NULL;
12856}
12857
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012858PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012859 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012860\n\
12861Return a copy of the string S, where all characters have been mapped\n\
12862through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012863Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012864Unmapped characters are left untouched. Characters mapped to None\n\
12865are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012866
12867static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012868unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012869{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012870 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012871}
12872
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012873PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012874 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012875\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012876Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012877
12878static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012879unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012880{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012881 if (PyUnicode_READY(self) == -1)
12882 return NULL;
12883 if (PyUnicode_IS_ASCII(self))
12884 return ascii_upper_or_lower(self, 0);
12885 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012886}
12887
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012888PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012889 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012890\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012891Pad a numeric string S with zeros on the left, to fill a field\n\
12892of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012893
12894static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012895unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012896{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012897 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012898 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012899 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012900 int kind;
12901 void *data;
12902 Py_UCS4 chr;
12903
Martin v. Löwis18e16552006-02-15 17:27:45 +000012904 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012905 return NULL;
12906
Benjamin Petersonbac79492012-01-14 13:34:47 -050012907 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012908 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012909
Victor Stinnerc4b49542011-12-11 22:44:26 +010012910 if (PyUnicode_GET_LENGTH(self) >= width)
12911 return unicode_result_unchanged(self);
12912
12913 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012914
12915 u = pad(self, fill, 0, '0');
12916
Walter Dörwald068325e2002-04-15 13:36:47 +000012917 if (u == NULL)
12918 return NULL;
12919
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012920 kind = PyUnicode_KIND(u);
12921 data = PyUnicode_DATA(u);
12922 chr = PyUnicode_READ(kind, data, fill);
12923
12924 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012925 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012926 PyUnicode_WRITE(kind, data, 0, chr);
12927 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012928 }
12929
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012930 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012931 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012932}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012933
12934#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012935static PyObject *
12936unicode__decimal2ascii(PyObject *self)
12937{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012938 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012939}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012940#endif
12941
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012942PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012943 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012944\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012945Return True if S starts with the specified prefix, False otherwise.\n\
12946With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012947With optional end, stop comparing S at that position.\n\
12948prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012949
12950static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012951unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012952 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012953{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012954 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012955 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012956 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012957 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012958 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012959
Jesus Ceaac451502011-04-20 17:09:23 +020012960 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012961 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012962 if (PyTuple_Check(subobj)) {
12963 Py_ssize_t i;
12964 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012965 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012966 if (substring == NULL)
12967 return NULL;
12968 result = tailmatch(self, substring, start, end, -1);
12969 Py_DECREF(substring);
12970 if (result) {
12971 Py_RETURN_TRUE;
12972 }
12973 }
12974 /* nothing matched */
12975 Py_RETURN_FALSE;
12976 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012977 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012978 if (substring == NULL) {
12979 if (PyErr_ExceptionMatches(PyExc_TypeError))
12980 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12981 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012982 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012983 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012984 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012985 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012986 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012987}
12988
12989
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012990PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012991 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012992\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012993Return True if S ends with the specified suffix, False otherwise.\n\
12994With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012995With optional end, stop comparing S at that position.\n\
12996suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012997
12998static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012999unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013000 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013001{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013002 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013003 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013004 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013005 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013006 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013007
Jesus Ceaac451502011-04-20 17:09:23 +020013008 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013009 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013010 if (PyTuple_Check(subobj)) {
13011 Py_ssize_t i;
13012 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013013 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013014 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013015 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013016 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013017 result = tailmatch(self, substring, start, end, +1);
13018 Py_DECREF(substring);
13019 if (result) {
13020 Py_RETURN_TRUE;
13021 }
13022 }
13023 Py_RETURN_FALSE;
13024 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013025 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013026 if (substring == NULL) {
13027 if (PyErr_ExceptionMatches(PyExc_TypeError))
13028 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13029 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013030 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013031 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013032 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013033 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013034 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013035}
13036
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013037#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013038
13039PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013040 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013041\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013042Return a formatted version of S, using substitutions from args and kwargs.\n\
13043The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013044
Eric Smith27bbca62010-11-04 17:06:58 +000013045PyDoc_STRVAR(format_map__doc__,
13046 "S.format_map(mapping) -> str\n\
13047\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013048Return a formatted version of S, using substitutions from mapping.\n\
13049The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013050
Eric Smith4a7d76d2008-05-30 18:10:19 +000013051static PyObject *
13052unicode__format__(PyObject* self, PyObject* args)
13053{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013054 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013055
13056 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13057 return NULL;
13058
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013059 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013060 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013061 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013062}
13063
Eric Smith8c663262007-08-25 02:26:07 +000013064PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013065 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013066\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013067Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013068
13069static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013070unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013071{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013072 Py_ssize_t size;
13073
13074 /* If it's a compact object, account for base structure +
13075 character data. */
13076 if (PyUnicode_IS_COMPACT_ASCII(v))
13077 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13078 else if (PyUnicode_IS_COMPACT(v))
13079 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013080 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013081 else {
13082 /* If it is a two-block object, account for base object, and
13083 for character block if present. */
13084 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013085 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013086 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013087 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013088 }
13089 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013090 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013091 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013092 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013093 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013094 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013095
13096 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013097}
13098
13099PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013100 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013101
13102static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013103unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013104{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013105 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013106 if (!copy)
13107 return NULL;
13108 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013109}
13110
Guido van Rossumd57fd912000-03-10 22:53:23 +000013111static PyMethodDef unicode_methods[] = {
13112
13113 /* Order is according to common usage: often used methods should
13114 appear first, since lookup is done sequentially. */
13115
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013116 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013117 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
13118 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013119 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013120 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13121 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013122 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013123 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13124 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13125 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13126 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13127 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013128 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013129 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13130 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13131 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013132 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013133 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13134 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13135 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013136 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013137 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013138 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013139 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013140 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13141 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13142 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13143 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13144 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13145 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13146 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13147 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13148 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13149 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13150 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13151 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13152 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13153 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013154 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013155 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013156 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013157 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013158 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013159 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013160 {"maketrans", (PyCFunction) unicode_maketrans,
13161 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013162 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013163#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013164 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013165 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013166#endif
13167
Benjamin Peterson14339b62009-01-31 16:36:08 +000013168 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013169 {NULL, NULL}
13170};
13171
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013172static PyObject *
13173unicode_mod(PyObject *v, PyObject *w)
13174{
Brian Curtindfc80e32011-08-10 20:28:54 -050013175 if (!PyUnicode_Check(v))
13176 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013177 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013178}
13179
13180static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013181 0, /*nb_add*/
13182 0, /*nb_subtract*/
13183 0, /*nb_multiply*/
13184 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013185};
13186
Guido van Rossumd57fd912000-03-10 22:53:23 +000013187static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013188 (lenfunc) unicode_length, /* sq_length */
13189 PyUnicode_Concat, /* sq_concat */
13190 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13191 (ssizeargfunc) unicode_getitem, /* sq_item */
13192 0, /* sq_slice */
13193 0, /* sq_ass_item */
13194 0, /* sq_ass_slice */
13195 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013196};
13197
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013198static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013199unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013200{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013201 if (PyUnicode_READY(self) == -1)
13202 return NULL;
13203
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013204 if (PyIndex_Check(item)) {
13205 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013206 if (i == -1 && PyErr_Occurred())
13207 return NULL;
13208 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013209 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013210 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013211 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013212 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013213 PyObject *result;
13214 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013215 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013216 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013217
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013218 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013219 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013220 return NULL;
13221 }
13222
13223 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013224 Py_INCREF(unicode_empty);
13225 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013226 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013227 slicelength == PyUnicode_GET_LENGTH(self)) {
13228 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013229 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013230 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013231 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013232 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013233 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013234 src_kind = PyUnicode_KIND(self);
13235 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013236 if (!PyUnicode_IS_ASCII(self)) {
13237 kind_limit = kind_maxchar_limit(src_kind);
13238 max_char = 0;
13239 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13240 ch = PyUnicode_READ(src_kind, src_data, cur);
13241 if (ch > max_char) {
13242 max_char = ch;
13243 if (max_char >= kind_limit)
13244 break;
13245 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013246 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013247 }
Victor Stinner55c99112011-10-13 01:17:06 +020013248 else
13249 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013250 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013251 if (result == NULL)
13252 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013253 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013254 dest_data = PyUnicode_DATA(result);
13255
13256 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013257 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13258 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013259 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013260 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013261 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013262 } else {
13263 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13264 return NULL;
13265 }
13266}
13267
13268static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013269 (lenfunc)unicode_length, /* mp_length */
13270 (binaryfunc)unicode_subscript, /* mp_subscript */
13271 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013272};
13273
Guido van Rossumd57fd912000-03-10 22:53:23 +000013274
Guido van Rossumd57fd912000-03-10 22:53:23 +000013275/* Helpers for PyUnicode_Format() */
13276
13277static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013278getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013279{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013280 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013281 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013282 (*p_argidx)++;
13283 if (arglen < 0)
13284 return args;
13285 else
13286 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013287 }
13288 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013289 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013290 return NULL;
13291}
13292
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013293/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013294
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013295static PyObject *
13296formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013297{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013298 char *p;
13299 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013300 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013301
Guido van Rossumd57fd912000-03-10 22:53:23 +000013302 x = PyFloat_AsDouble(v);
13303 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013304 return NULL;
13305
Guido van Rossumd57fd912000-03-10 22:53:23 +000013306 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013307 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013308
Eric Smith0923d1d2009-04-16 20:16:10 +000013309 p = PyOS_double_to_string(x, type, prec,
13310 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013311 if (p == NULL)
13312 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013313 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013314 PyMem_Free(p);
13315 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013316}
13317
Tim Peters38fd5b62000-09-21 05:43:11 +000013318static PyObject*
13319formatlong(PyObject *val, int flags, int prec, int type)
13320{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013321 char *buf;
13322 int len;
13323 PyObject *str; /* temporary string object. */
13324 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013325
Benjamin Peterson14339b62009-01-31 16:36:08 +000013326 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13327 if (!str)
13328 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013329 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013330 Py_DECREF(str);
13331 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013332}
13333
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013334static Py_UCS4
13335formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013336{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013337 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013338 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013339 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013340 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013341 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013342 goto onError;
13343 }
13344 else {
13345 /* Integer input truncated to a character */
13346 long x;
13347 x = PyLong_AsLong(v);
13348 if (x == -1 && PyErr_Occurred())
13349 goto onError;
13350
Victor Stinner8faf8212011-12-08 22:14:11 +010013351 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013352 PyErr_SetString(PyExc_OverflowError,
13353 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013354 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013355 }
13356
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013357 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013358 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013359
Benjamin Peterson29060642009-01-31 22:14:21 +000013360 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013361 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013362 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013363 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013364}
13365
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013366static int
13367repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13368{
13369 int r;
13370 assert(count > 0);
13371 assert(PyUnicode_Check(obj));
13372 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013373 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013374 if (repeated == NULL)
13375 return -1;
13376 r = _PyAccu_Accumulate(acc, repeated);
13377 Py_DECREF(repeated);
13378 return r;
13379 }
13380 else {
13381 do {
13382 if (_PyAccu_Accumulate(acc, obj))
13383 return -1;
13384 } while (--count);
13385 return 0;
13386 }
13387}
13388
Alexander Belopolsky40018472011-02-26 01:02:56 +000013389PyObject *
13390PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013391{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013392 void *fmt;
13393 int fmtkind;
13394 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013395 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013396 int r;
13397 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013398 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013399 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013400 PyObject *temp = NULL;
13401 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013402 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013403 _PyAccu acc;
13404 static PyObject *plus, *minus, *blank, *zero, *percent;
13405
13406 if (!plus && !(plus = get_latin1_char('+')))
13407 return NULL;
13408 if (!minus && !(minus = get_latin1_char('-')))
13409 return NULL;
13410 if (!blank && !(blank = get_latin1_char(' ')))
13411 return NULL;
13412 if (!zero && !(zero = get_latin1_char('0')))
13413 return NULL;
13414 if (!percent && !(percent = get_latin1_char('%')))
13415 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013416
Guido van Rossumd57fd912000-03-10 22:53:23 +000013417 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013418 PyErr_BadInternalCall();
13419 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013420 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013421 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013422 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013423 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013424 if (PyUnicode_READY(uformat) == -1)
13425 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013426 if (_PyAccu_Init(&acc))
13427 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013428 fmt = PyUnicode_DATA(uformat);
13429 fmtkind = PyUnicode_KIND(uformat);
13430 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13431 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013432
Guido van Rossumd57fd912000-03-10 22:53:23 +000013433 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013434 arglen = PyTuple_Size(args);
13435 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013436 }
13437 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013438 arglen = -1;
13439 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013440 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013441 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013442 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013443 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013444
13445 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013446 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013447 PyObject *nonfmt;
13448 Py_ssize_t nonfmtpos;
13449 nonfmtpos = fmtpos++;
13450 while (fmtcnt >= 0 &&
13451 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13452 fmtpos++;
13453 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013454 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013455 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013456 if (nonfmt == NULL)
13457 goto onError;
13458 r = _PyAccu_Accumulate(&acc, nonfmt);
13459 Py_DECREF(nonfmt);
13460 if (r)
13461 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013462 }
13463 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013464 /* Got a format specifier */
13465 int flags = 0;
13466 Py_ssize_t width = -1;
13467 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013468 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013469 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013470 int isnumok;
13471 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013472 void *pbuf = NULL;
13473 Py_ssize_t pindex, len;
13474 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013476 fmtpos++;
13477 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13478 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013479 Py_ssize_t keylen;
13480 PyObject *key;
13481 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013482
Benjamin Peterson29060642009-01-31 22:14:21 +000013483 if (dict == NULL) {
13484 PyErr_SetString(PyExc_TypeError,
13485 "format requires a mapping");
13486 goto onError;
13487 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013488 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013489 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013490 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013491 /* Skip over balanced parentheses */
13492 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013493 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013494 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013495 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013496 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013497 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013498 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013499 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013500 if (fmtcnt < 0 || pcount > 0) {
13501 PyErr_SetString(PyExc_ValueError,
13502 "incomplete format key");
13503 goto onError;
13504 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013505 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013506 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013507 if (key == NULL)
13508 goto onError;
13509 if (args_owned) {
13510 Py_DECREF(args);
13511 args_owned = 0;
13512 }
13513 args = PyObject_GetItem(dict, key);
13514 Py_DECREF(key);
13515 if (args == NULL) {
13516 goto onError;
13517 }
13518 args_owned = 1;
13519 arglen = -1;
13520 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013521 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013522 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013523 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013524 case '-': flags |= F_LJUST; continue;
13525 case '+': flags |= F_SIGN; continue;
13526 case ' ': flags |= F_BLANK; continue;
13527 case '#': flags |= F_ALT; continue;
13528 case '0': flags |= F_ZERO; continue;
13529 }
13530 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013531 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013532 if (c == '*') {
13533 v = getnextarg(args, arglen, &argidx);
13534 if (v == NULL)
13535 goto onError;
13536 if (!PyLong_Check(v)) {
13537 PyErr_SetString(PyExc_TypeError,
13538 "* wants int");
13539 goto onError;
13540 }
13541 width = PyLong_AsLong(v);
13542 if (width == -1 && PyErr_Occurred())
13543 goto onError;
13544 if (width < 0) {
13545 flags |= F_LJUST;
13546 width = -width;
13547 }
13548 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013549 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013550 }
13551 else if (c >= '0' && c <= '9') {
13552 width = c - '0';
13553 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013554 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013555 if (c < '0' || c > '9')
13556 break;
13557 if ((width*10) / 10 != width) {
13558 PyErr_SetString(PyExc_ValueError,
13559 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013560 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013561 }
13562 width = width*10 + (c - '0');
13563 }
13564 }
13565 if (c == '.') {
13566 prec = 0;
13567 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013568 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013569 if (c == '*') {
13570 v = getnextarg(args, arglen, &argidx);
13571 if (v == NULL)
13572 goto onError;
13573 if (!PyLong_Check(v)) {
13574 PyErr_SetString(PyExc_TypeError,
13575 "* wants int");
13576 goto onError;
13577 }
13578 prec = PyLong_AsLong(v);
13579 if (prec == -1 && PyErr_Occurred())
13580 goto onError;
13581 if (prec < 0)
13582 prec = 0;
13583 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013584 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013585 }
13586 else if (c >= '0' && c <= '9') {
13587 prec = c - '0';
13588 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013589 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013590 if (c < '0' || c > '9')
13591 break;
13592 if ((prec*10) / 10 != prec) {
13593 PyErr_SetString(PyExc_ValueError,
13594 "prec too big");
13595 goto onError;
13596 }
13597 prec = prec*10 + (c - '0');
13598 }
13599 }
13600 } /* prec */
13601 if (fmtcnt >= 0) {
13602 if (c == 'h' || c == 'l' || c == 'L') {
13603 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013604 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013605 }
13606 }
13607 if (fmtcnt < 0) {
13608 PyErr_SetString(PyExc_ValueError,
13609 "incomplete format");
13610 goto onError;
13611 }
13612 if (c != '%') {
13613 v = getnextarg(args, arglen, &argidx);
13614 if (v == NULL)
13615 goto onError;
13616 }
13617 sign = 0;
13618 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013619 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013620 switch (c) {
13621
13622 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013623 _PyAccu_Accumulate(&acc, percent);
13624 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013625
13626 case 's':
13627 case 'r':
13628 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013629 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013630 temp = v;
13631 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013632 }
13633 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013634 if (c == 's')
13635 temp = PyObject_Str(v);
13636 else if (c == 'r')
13637 temp = PyObject_Repr(v);
13638 else
13639 temp = PyObject_ASCII(v);
13640 if (temp == NULL)
13641 goto onError;
13642 if (PyUnicode_Check(temp))
13643 /* nothing to do */;
13644 else {
13645 Py_DECREF(temp);
13646 PyErr_SetString(PyExc_TypeError,
13647 "%s argument has non-string str()");
13648 goto onError;
13649 }
13650 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013651 if (PyUnicode_READY(temp) == -1) {
13652 Py_CLEAR(temp);
13653 goto onError;
13654 }
13655 pbuf = PyUnicode_DATA(temp);
13656 kind = PyUnicode_KIND(temp);
13657 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013658 if (prec >= 0 && len > prec)
13659 len = prec;
13660 break;
13661
13662 case 'i':
13663 case 'd':
13664 case 'u':
13665 case 'o':
13666 case 'x':
13667 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013668 isnumok = 0;
13669 if (PyNumber_Check(v)) {
13670 PyObject *iobj=NULL;
13671
13672 if (PyLong_Check(v)) {
13673 iobj = v;
13674 Py_INCREF(iobj);
13675 }
13676 else {
13677 iobj = PyNumber_Long(v);
13678 }
13679 if (iobj!=NULL) {
13680 if (PyLong_Check(iobj)) {
13681 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013682 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013683 Py_DECREF(iobj);
13684 if (!temp)
13685 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013686 if (PyUnicode_READY(temp) == -1) {
13687 Py_CLEAR(temp);
13688 goto onError;
13689 }
13690 pbuf = PyUnicode_DATA(temp);
13691 kind = PyUnicode_KIND(temp);
13692 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013693 sign = 1;
13694 }
13695 else {
13696 Py_DECREF(iobj);
13697 }
13698 }
13699 }
13700 if (!isnumok) {
13701 PyErr_Format(PyExc_TypeError,
13702 "%%%c format: a number is required, "
13703 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13704 goto onError;
13705 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013706 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013707 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013708 fillobj = zero;
13709 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013710 break;
13711
13712 case 'e':
13713 case 'E':
13714 case 'f':
13715 case 'F':
13716 case 'g':
13717 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013718 temp = formatfloat(v, flags, prec, c);
13719 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013720 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013721 if (PyUnicode_READY(temp) == -1) {
13722 Py_CLEAR(temp);
13723 goto onError;
13724 }
13725 pbuf = PyUnicode_DATA(temp);
13726 kind = PyUnicode_KIND(temp);
13727 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013728 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013729 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013730 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013731 fillobj = zero;
13732 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013733 break;
13734
13735 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013736 {
13737 Py_UCS4 ch = formatchar(v);
13738 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013739 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013740 temp = _PyUnicode_FromUCS4(&ch, 1);
13741 if (temp == NULL)
13742 goto onError;
13743 pbuf = PyUnicode_DATA(temp);
13744 kind = PyUnicode_KIND(temp);
13745 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013746 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013747 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013748
13749 default:
13750 PyErr_Format(PyExc_ValueError,
13751 "unsupported format character '%c' (0x%x) "
13752 "at index %zd",
13753 (31<=c && c<=126) ? (char)c : '?',
13754 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013755 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013756 goto onError;
13757 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013758 /* pbuf is initialized here. */
13759 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013760 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013761 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13762 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013763 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013764 pindex++;
13765 }
13766 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13767 signobj = plus;
13768 len--;
13769 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013770 }
13771 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013772 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013773 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013774 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013775 else
13776 sign = 0;
13777 }
13778 if (width < len)
13779 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013780 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013781 if (fill != ' ') {
13782 assert(signobj != NULL);
13783 if (_PyAccu_Accumulate(&acc, signobj))
13784 goto onError;
13785 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013786 if (width > len)
13787 width--;
13788 }
13789 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013790 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013791 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013792 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013793 second = get_latin1_char(
13794 PyUnicode_READ(kind, pbuf, pindex + 1));
13795 pindex += 2;
13796 if (second == NULL ||
13797 _PyAccu_Accumulate(&acc, zero) ||
13798 _PyAccu_Accumulate(&acc, second))
13799 goto onError;
13800 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013801 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013802 width -= 2;
13803 if (width < 0)
13804 width = 0;
13805 len -= 2;
13806 }
13807 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013808 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013809 if (repeat_accumulate(&acc, fillobj, width - len))
13810 goto onError;
13811 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013812 }
13813 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013814 if (sign) {
13815 assert(signobj != NULL);
13816 if (_PyAccu_Accumulate(&acc, signobj))
13817 goto onError;
13818 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013819 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013820 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13821 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013822 second = get_latin1_char(
13823 PyUnicode_READ(kind, pbuf, pindex + 1));
13824 pindex += 2;
13825 if (second == NULL ||
13826 _PyAccu_Accumulate(&acc, zero) ||
13827 _PyAccu_Accumulate(&acc, second))
13828 goto onError;
13829 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013830 }
13831 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013832 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013833 if (temp != NULL) {
13834 assert(pbuf == PyUnicode_DATA(temp));
13835 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013836 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013837 else {
13838 const char *p = (const char *) pbuf;
13839 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013840 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013841 v = PyUnicode_FromKindAndData(kind, p, len);
13842 }
13843 if (v == NULL)
13844 goto onError;
13845 r = _PyAccu_Accumulate(&acc, v);
13846 Py_DECREF(v);
13847 if (r)
13848 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013849 if (width > len && repeat_accumulate(&acc, blank, width - len))
13850 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013851 if (dict && (argidx < arglen) && c != '%') {
13852 PyErr_SetString(PyExc_TypeError,
13853 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013854 goto onError;
13855 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013856 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013857 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013858 } /* until end */
13859 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013860 PyErr_SetString(PyExc_TypeError,
13861 "not all arguments converted during string formatting");
13862 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013863 }
13864
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013865 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013866 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013867 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013868 }
13869 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013870 Py_XDECREF(temp);
13871 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013872 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013873
Benjamin Peterson29060642009-01-31 22:14:21 +000013874 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013875 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013876 Py_XDECREF(temp);
13877 Py_XDECREF(second);
13878 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013879 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013880 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013881 }
13882 return NULL;
13883}
13884
Jeremy Hylton938ace62002-07-17 16:30:39 +000013885static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013886unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13887
Tim Peters6d6c1a32001-08-02 04:15:00 +000013888static PyObject *
13889unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13890{
Benjamin Peterson29060642009-01-31 22:14:21 +000013891 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013892 static char *kwlist[] = {"object", "encoding", "errors", 0};
13893 char *encoding = NULL;
13894 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013895
Benjamin Peterson14339b62009-01-31 16:36:08 +000013896 if (type != &PyUnicode_Type)
13897 return unicode_subtype_new(type, args, kwds);
13898 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013899 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013900 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013901 if (x == NULL) {
13902 Py_INCREF(unicode_empty);
13903 return unicode_empty;
13904 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013905 if (encoding == NULL && errors == NULL)
13906 return PyObject_Str(x);
13907 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013908 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013909}
13910
Guido van Rossume023fe02001-08-30 03:12:59 +000013911static PyObject *
13912unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13913{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013914 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013915 Py_ssize_t length, char_size;
13916 int share_wstr, share_utf8;
13917 unsigned int kind;
13918 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013919
Benjamin Peterson14339b62009-01-31 16:36:08 +000013920 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013921
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013922 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013923 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013924 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013925 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050013926 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013927 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013928 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013929 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013930
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013931 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013932 if (self == NULL) {
13933 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013934 return NULL;
13935 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013936 kind = PyUnicode_KIND(unicode);
13937 length = PyUnicode_GET_LENGTH(unicode);
13938
13939 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013940#ifdef Py_DEBUG
13941 _PyUnicode_HASH(self) = -1;
13942#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013943 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013944#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013945 _PyUnicode_STATE(self).interned = 0;
13946 _PyUnicode_STATE(self).kind = kind;
13947 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013948 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013949 _PyUnicode_STATE(self).ready = 1;
13950 _PyUnicode_WSTR(self) = NULL;
13951 _PyUnicode_UTF8_LENGTH(self) = 0;
13952 _PyUnicode_UTF8(self) = NULL;
13953 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013954 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013955
13956 share_utf8 = 0;
13957 share_wstr = 0;
13958 if (kind == PyUnicode_1BYTE_KIND) {
13959 char_size = 1;
13960 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13961 share_utf8 = 1;
13962 }
13963 else if (kind == PyUnicode_2BYTE_KIND) {
13964 char_size = 2;
13965 if (sizeof(wchar_t) == 2)
13966 share_wstr = 1;
13967 }
13968 else {
13969 assert(kind == PyUnicode_4BYTE_KIND);
13970 char_size = 4;
13971 if (sizeof(wchar_t) == 4)
13972 share_wstr = 1;
13973 }
13974
13975 /* Ensure we won't overflow the length. */
13976 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13977 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013978 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013979 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013980 data = PyObject_MALLOC((length + 1) * char_size);
13981 if (data == NULL) {
13982 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013983 goto onError;
13984 }
13985
Victor Stinnerc3c74152011-10-02 20:39:55 +020013986 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013987 if (share_utf8) {
13988 _PyUnicode_UTF8_LENGTH(self) = length;
13989 _PyUnicode_UTF8(self) = data;
13990 }
13991 if (share_wstr) {
13992 _PyUnicode_WSTR_LENGTH(self) = length;
13993 _PyUnicode_WSTR(self) = (wchar_t *)data;
13994 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013995
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013996 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013997 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013998 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013999#ifdef Py_DEBUG
14000 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14001#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014002 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014003 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014004
14005onError:
14006 Py_DECREF(unicode);
14007 Py_DECREF(self);
14008 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014009}
14010
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014011PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000014012 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014013\n\
Collin Winterd474ce82007-08-07 19:42:11 +000014014Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000014015encoding defaults to the current default string encoding.\n\
14016errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014017
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014018static PyObject *unicode_iter(PyObject *seq);
14019
Guido van Rossumd57fd912000-03-10 22:53:23 +000014020PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014021 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014022 "str", /* tp_name */
14023 sizeof(PyUnicodeObject), /* tp_size */
14024 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014025 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014026 (destructor)unicode_dealloc, /* tp_dealloc */
14027 0, /* tp_print */
14028 0, /* tp_getattr */
14029 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014030 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014031 unicode_repr, /* tp_repr */
14032 &unicode_as_number, /* tp_as_number */
14033 &unicode_as_sequence, /* tp_as_sequence */
14034 &unicode_as_mapping, /* tp_as_mapping */
14035 (hashfunc) unicode_hash, /* tp_hash*/
14036 0, /* tp_call*/
14037 (reprfunc) unicode_str, /* tp_str */
14038 PyObject_GenericGetAttr, /* tp_getattro */
14039 0, /* tp_setattro */
14040 0, /* tp_as_buffer */
14041 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014042 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014043 unicode_doc, /* tp_doc */
14044 0, /* tp_traverse */
14045 0, /* tp_clear */
14046 PyUnicode_RichCompare, /* tp_richcompare */
14047 0, /* tp_weaklistoffset */
14048 unicode_iter, /* tp_iter */
14049 0, /* tp_iternext */
14050 unicode_methods, /* tp_methods */
14051 0, /* tp_members */
14052 0, /* tp_getset */
14053 &PyBaseObject_Type, /* tp_base */
14054 0, /* tp_dict */
14055 0, /* tp_descr_get */
14056 0, /* tp_descr_set */
14057 0, /* tp_dictoffset */
14058 0, /* tp_init */
14059 0, /* tp_alloc */
14060 unicode_new, /* tp_new */
14061 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014062};
14063
14064/* Initialize the Unicode implementation */
14065
Victor Stinner3a50e702011-10-18 21:21:00 +020014066int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014067{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014068 int i;
14069
Thomas Wouters477c8d52006-05-27 19:21:47 +000014070 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014071 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014072 0x000A, /* LINE FEED */
14073 0x000D, /* CARRIAGE RETURN */
14074 0x001C, /* FILE SEPARATOR */
14075 0x001D, /* GROUP SEPARATOR */
14076 0x001E, /* RECORD SEPARATOR */
14077 0x0085, /* NEXT LINE */
14078 0x2028, /* LINE SEPARATOR */
14079 0x2029, /* PARAGRAPH SEPARATOR */
14080 };
14081
Fred Drakee4315f52000-05-09 19:53:39 +000014082 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014083 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014084 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014085 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014086 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014087
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014088 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014089 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014090 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014091 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014092
14093 /* initialize the linebreak bloom filter */
14094 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014095 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014096 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014097
14098 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014099
14100#ifdef HAVE_MBCS
14101 winver.dwOSVersionInfoSize = sizeof(winver);
14102 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14103 PyErr_SetFromWindowsErr(0);
14104 return -1;
14105 }
14106#endif
14107 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014108}
14109
14110/* Finalize the Unicode implementation */
14111
Christian Heimesa156e092008-02-16 07:38:31 +000014112int
14113PyUnicode_ClearFreeList(void)
14114{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014115 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014116}
14117
Guido van Rossumd57fd912000-03-10 22:53:23 +000014118void
Thomas Wouters78890102000-07-22 19:25:51 +000014119_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014120{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014121 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014122
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014123 Py_XDECREF(unicode_empty);
14124 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014125
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014126 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014127 if (unicode_latin1[i]) {
14128 Py_DECREF(unicode_latin1[i]);
14129 unicode_latin1[i] = NULL;
14130 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014131 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014132 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014133 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014134}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014135
Walter Dörwald16807132007-05-25 13:52:07 +000014136void
14137PyUnicode_InternInPlace(PyObject **p)
14138{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014139 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014140 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014141#ifdef Py_DEBUG
14142 assert(s != NULL);
14143 assert(_PyUnicode_CHECK(s));
14144#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014145 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014146 return;
14147#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014148 /* If it's a subclass, we don't really know what putting
14149 it in the interned dict might do. */
14150 if (!PyUnicode_CheckExact(s))
14151 return;
14152 if (PyUnicode_CHECK_INTERNED(s))
14153 return;
14154 if (interned == NULL) {
14155 interned = PyDict_New();
14156 if (interned == NULL) {
14157 PyErr_Clear(); /* Don't leave an exception */
14158 return;
14159 }
14160 }
14161 /* It might be that the GetItem call fails even
14162 though the key is present in the dictionary,
14163 namely when this happens during a stack overflow. */
14164 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014165 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014166 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014167
Benjamin Peterson29060642009-01-31 22:14:21 +000014168 if (t) {
14169 Py_INCREF(t);
14170 Py_DECREF(*p);
14171 *p = t;
14172 return;
14173 }
Walter Dörwald16807132007-05-25 13:52:07 +000014174
Benjamin Peterson14339b62009-01-31 16:36:08 +000014175 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014176 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014177 PyErr_Clear();
14178 PyThreadState_GET()->recursion_critical = 0;
14179 return;
14180 }
14181 PyThreadState_GET()->recursion_critical = 0;
14182 /* The two references in interned are not counted by refcnt.
14183 The deallocator will take care of this */
14184 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014185 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014186}
14187
14188void
14189PyUnicode_InternImmortal(PyObject **p)
14190{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014191 PyUnicode_InternInPlace(p);
14192 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014193 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014194 Py_INCREF(*p);
14195 }
Walter Dörwald16807132007-05-25 13:52:07 +000014196}
14197
14198PyObject *
14199PyUnicode_InternFromString(const char *cp)
14200{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014201 PyObject *s = PyUnicode_FromString(cp);
14202 if (s == NULL)
14203 return NULL;
14204 PyUnicode_InternInPlace(&s);
14205 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014206}
14207
Alexander Belopolsky40018472011-02-26 01:02:56 +000014208void
14209_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014210{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014211 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014212 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014213 Py_ssize_t i, n;
14214 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014215
Benjamin Peterson14339b62009-01-31 16:36:08 +000014216 if (interned == NULL || !PyDict_Check(interned))
14217 return;
14218 keys = PyDict_Keys(interned);
14219 if (keys == NULL || !PyList_Check(keys)) {
14220 PyErr_Clear();
14221 return;
14222 }
Walter Dörwald16807132007-05-25 13:52:07 +000014223
Benjamin Peterson14339b62009-01-31 16:36:08 +000014224 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14225 detector, interned unicode strings are not forcibly deallocated;
14226 rather, we give them their stolen references back, and then clear
14227 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014228
Benjamin Peterson14339b62009-01-31 16:36:08 +000014229 n = PyList_GET_SIZE(keys);
14230 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014231 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014232 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014233 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014234 if (PyUnicode_READY(s) == -1) {
14235 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014236 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014237 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014238 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014239 case SSTATE_NOT_INTERNED:
14240 /* XXX Shouldn't happen */
14241 break;
14242 case SSTATE_INTERNED_IMMORTAL:
14243 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014244 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014245 break;
14246 case SSTATE_INTERNED_MORTAL:
14247 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014248 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014249 break;
14250 default:
14251 Py_FatalError("Inconsistent interned string state.");
14252 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014253 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014254 }
14255 fprintf(stderr, "total size of all interned strings: "
14256 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14257 "mortal/immortal\n", mortal_size, immortal_size);
14258 Py_DECREF(keys);
14259 PyDict_Clear(interned);
14260 Py_DECREF(interned);
14261 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014262}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014263
14264
14265/********************* Unicode Iterator **************************/
14266
14267typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014268 PyObject_HEAD
14269 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014270 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014271} unicodeiterobject;
14272
14273static void
14274unicodeiter_dealloc(unicodeiterobject *it)
14275{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014276 _PyObject_GC_UNTRACK(it);
14277 Py_XDECREF(it->it_seq);
14278 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014279}
14280
14281static int
14282unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14283{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014284 Py_VISIT(it->it_seq);
14285 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014286}
14287
14288static PyObject *
14289unicodeiter_next(unicodeiterobject *it)
14290{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014291 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014292
Benjamin Peterson14339b62009-01-31 16:36:08 +000014293 assert(it != NULL);
14294 seq = it->it_seq;
14295 if (seq == NULL)
14296 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014297 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014298
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014299 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14300 int kind = PyUnicode_KIND(seq);
14301 void *data = PyUnicode_DATA(seq);
14302 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14303 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014304 if (item != NULL)
14305 ++it->it_index;
14306 return item;
14307 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014308
Benjamin Peterson14339b62009-01-31 16:36:08 +000014309 Py_DECREF(seq);
14310 it->it_seq = NULL;
14311 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014312}
14313
14314static PyObject *
14315unicodeiter_len(unicodeiterobject *it)
14316{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014317 Py_ssize_t len = 0;
14318 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014319 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014320 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014321}
14322
14323PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14324
14325static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014326 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014327 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014328 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014329};
14330
14331PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014332 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14333 "str_iterator", /* tp_name */
14334 sizeof(unicodeiterobject), /* tp_basicsize */
14335 0, /* tp_itemsize */
14336 /* methods */
14337 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14338 0, /* tp_print */
14339 0, /* tp_getattr */
14340 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014341 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014342 0, /* tp_repr */
14343 0, /* tp_as_number */
14344 0, /* tp_as_sequence */
14345 0, /* tp_as_mapping */
14346 0, /* tp_hash */
14347 0, /* tp_call */
14348 0, /* tp_str */
14349 PyObject_GenericGetAttr, /* tp_getattro */
14350 0, /* tp_setattro */
14351 0, /* tp_as_buffer */
14352 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14353 0, /* tp_doc */
14354 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14355 0, /* tp_clear */
14356 0, /* tp_richcompare */
14357 0, /* tp_weaklistoffset */
14358 PyObject_SelfIter, /* tp_iter */
14359 (iternextfunc)unicodeiter_next, /* tp_iternext */
14360 unicodeiter_methods, /* tp_methods */
14361 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014362};
14363
14364static PyObject *
14365unicode_iter(PyObject *seq)
14366{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014367 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014368
Benjamin Peterson14339b62009-01-31 16:36:08 +000014369 if (!PyUnicode_Check(seq)) {
14370 PyErr_BadInternalCall();
14371 return NULL;
14372 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014373 if (PyUnicode_READY(seq) == -1)
14374 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014375 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14376 if (it == NULL)
14377 return NULL;
14378 it->it_index = 0;
14379 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014380 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014381 _PyObject_GC_TRACK(it);
14382 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014383}
14384
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014385
14386size_t
14387Py_UNICODE_strlen(const Py_UNICODE *u)
14388{
14389 int res = 0;
14390 while(*u++)
14391 res++;
14392 return res;
14393}
14394
14395Py_UNICODE*
14396Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14397{
14398 Py_UNICODE *u = s1;
14399 while ((*u++ = *s2++));
14400 return s1;
14401}
14402
14403Py_UNICODE*
14404Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14405{
14406 Py_UNICODE *u = s1;
14407 while ((*u++ = *s2++))
14408 if (n-- == 0)
14409 break;
14410 return s1;
14411}
14412
14413Py_UNICODE*
14414Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14415{
14416 Py_UNICODE *u1 = s1;
14417 u1 += Py_UNICODE_strlen(u1);
14418 Py_UNICODE_strcpy(u1, s2);
14419 return s1;
14420}
14421
14422int
14423Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14424{
14425 while (*s1 && *s2 && *s1 == *s2)
14426 s1++, s2++;
14427 if (*s1 && *s2)
14428 return (*s1 < *s2) ? -1 : +1;
14429 if (*s1)
14430 return 1;
14431 if (*s2)
14432 return -1;
14433 return 0;
14434}
14435
14436int
14437Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14438{
14439 register Py_UNICODE u1, u2;
14440 for (; n != 0; n--) {
14441 u1 = *s1;
14442 u2 = *s2;
14443 if (u1 != u2)
14444 return (u1 < u2) ? -1 : +1;
14445 if (u1 == '\0')
14446 return 0;
14447 s1++;
14448 s2++;
14449 }
14450 return 0;
14451}
14452
14453Py_UNICODE*
14454Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14455{
14456 const Py_UNICODE *p;
14457 for (p = s; *p; p++)
14458 if (*p == c)
14459 return (Py_UNICODE*)p;
14460 return NULL;
14461}
14462
14463Py_UNICODE*
14464Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14465{
14466 const Py_UNICODE *p;
14467 p = s + Py_UNICODE_strlen(s);
14468 while (p != s) {
14469 p--;
14470 if (*p == c)
14471 return (Py_UNICODE*)p;
14472 }
14473 return NULL;
14474}
Victor Stinner331ea922010-08-10 16:37:20 +000014475
Victor Stinner71133ff2010-09-01 23:43:53 +000014476Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014477PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014478{
Victor Stinner577db2c2011-10-11 22:12:48 +020014479 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014480 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014481
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014482 if (!PyUnicode_Check(unicode)) {
14483 PyErr_BadArgument();
14484 return NULL;
14485 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014486 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014487 if (u == NULL)
14488 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014489 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014490 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014491 PyErr_NoMemory();
14492 return NULL;
14493 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014494 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014495 size *= sizeof(Py_UNICODE);
14496 copy = PyMem_Malloc(size);
14497 if (copy == NULL) {
14498 PyErr_NoMemory();
14499 return NULL;
14500 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014501 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014502 return copy;
14503}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014504
Georg Brandl66c221e2010-10-14 07:04:07 +000014505/* A _string module, to export formatter_parser and formatter_field_name_split
14506 to the string.Formatter class implemented in Python. */
14507
14508static PyMethodDef _string_methods[] = {
14509 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14510 METH_O, PyDoc_STR("split the argument as a field name")},
14511 {"formatter_parser", (PyCFunction) formatter_parser,
14512 METH_O, PyDoc_STR("parse the argument as a format string")},
14513 {NULL, NULL}
14514};
14515
14516static struct PyModuleDef _string_module = {
14517 PyModuleDef_HEAD_INIT,
14518 "_string",
14519 PyDoc_STR("string helper module"),
14520 0,
14521 _string_methods,
14522 NULL,
14523 NULL,
14524 NULL,
14525 NULL
14526};
14527
14528PyMODINIT_FUNC
14529PyInit__string(void)
14530{
14531 return PyModule_Create(&_string_module);
14532}
14533
14534
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014535#ifdef __cplusplus
14536}
14537#endif