blob: 5c1071325d31cf5a4b672828f742b2a63cfec2c9 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050044#include "bytes_methods.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000045
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000046#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000047#include <windows.h>
48#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000049
Guido van Rossumd57fd912000-03-10 22:53:23 +000050/* Endianness switches; defaults to little endian */
51
52#ifdef WORDS_BIGENDIAN
53# define BYTEORDER_IS_BIG_ENDIAN
54#else
55# define BYTEORDER_IS_LITTLE_ENDIAN
56#endif
57
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000058/* --- Globals ------------------------------------------------------------
59
60 The globals are initialized by the _PyUnicode_Init() API and should
61 not be used before calling that API.
62
63*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000064
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000065
66#ifdef __cplusplus
67extern "C" {
68#endif
69
Victor Stinner8faf8212011-12-08 22:14:11 +010070/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
71#define MAX_UNICODE 0x10ffff
72
Victor Stinner910337b2011-10-03 03:20:16 +020073#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020074# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020075#else
76# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
77#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020078
Victor Stinnere90fe6a2011-10-01 16:48:13 +020079#define _PyUnicode_UTF8(op) \
80 (((PyCompactUnicodeObject*)(op))->utf8)
81#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020082 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020083 assert(PyUnicode_IS_READY(op)), \
84 PyUnicode_IS_COMPACT_ASCII(op) ? \
85 ((char*)((PyASCIIObject*)(op) + 1)) : \
86 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020087#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020088 (((PyCompactUnicodeObject*)(op))->utf8_length)
89#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020090 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020091 assert(PyUnicode_IS_READY(op)), \
92 PyUnicode_IS_COMPACT_ASCII(op) ? \
93 ((PyASCIIObject*)(op))->length : \
94 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020095#define _PyUnicode_WSTR(op) \
96 (((PyASCIIObject*)(op))->wstr)
97#define _PyUnicode_WSTR_LENGTH(op) \
98 (((PyCompactUnicodeObject*)(op))->wstr_length)
99#define _PyUnicode_LENGTH(op) \
100 (((PyASCIIObject *)(op))->length)
101#define _PyUnicode_STATE(op) \
102 (((PyASCIIObject *)(op))->state)
103#define _PyUnicode_HASH(op) \
104 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200105#define _PyUnicode_KIND(op) \
106 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200107 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200108#define _PyUnicode_GET_LENGTH(op) \
109 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200110 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200111#define _PyUnicode_DATA_ANY(op) \
112 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200113
Victor Stinner910337b2011-10-03 03:20:16 +0200114#undef PyUnicode_READY
115#define PyUnicode_READY(op) \
116 (assert(_PyUnicode_CHECK(op)), \
117 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200118 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100119 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200120
Victor Stinnerc379ead2011-10-03 12:52:27 +0200121#define _PyUnicode_SHARE_UTF8(op) \
122 (assert(_PyUnicode_CHECK(op)), \
123 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
124 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
125#define _PyUnicode_SHARE_WSTR(op) \
126 (assert(_PyUnicode_CHECK(op)), \
127 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
128
Victor Stinner829c0ad2011-10-03 01:08:02 +0200129/* true if the Unicode object has an allocated UTF-8 memory block
130 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200131#define _PyUnicode_HAS_UTF8_MEMORY(op) \
132 (assert(_PyUnicode_CHECK(op)), \
133 (!PyUnicode_IS_COMPACT_ASCII(op) \
134 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200135 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
136
Victor Stinner03490912011-10-03 23:45:12 +0200137/* true if the Unicode object has an allocated wstr memory block
138 (not shared with other data) */
139#define _PyUnicode_HAS_WSTR_MEMORY(op) \
140 (assert(_PyUnicode_CHECK(op)), \
141 (_PyUnicode_WSTR(op) && \
142 (!PyUnicode_IS_READY(op) || \
143 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
144
Victor Stinner910337b2011-10-03 03:20:16 +0200145/* Generic helper macro to convert characters of different types.
146 from_type and to_type have to be valid type names, begin and end
147 are pointers to the source characters which should be of type
148 "from_type *". to is a pointer of type "to_type *" and points to the
149 buffer where the result characters are written to. */
150#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
151 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200152 to_type *_to = (to_type *) to; \
153 const from_type *_iter = (begin); \
154 const from_type *_end = (end); \
155 Py_ssize_t n = (_end) - (_iter); \
156 const from_type *_unrolled_end = \
157 _iter + (n & ~ (Py_ssize_t) 3); \
158 while (_iter < (_unrolled_end)) { \
159 _to[0] = (to_type) _iter[0]; \
160 _to[1] = (to_type) _iter[1]; \
161 _to[2] = (to_type) _iter[2]; \
162 _to[3] = (to_type) _iter[3]; \
163 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200164 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200165 while (_iter < (_end)) \
166 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200167 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200168
Walter Dörwald16807132007-05-25 13:52:07 +0000169/* This dictionary holds all interned unicode strings. Note that references
170 to strings in this dictionary are *not* counted in the string's ob_refcnt.
171 When the interned string reaches a refcnt of 0 the string deallocation
172 function will delete the reference from this dictionary.
173
174 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000175 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000176*/
177static PyObject *interned;
178
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000179/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200180static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000181
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200182/* List of static strings. */
183static _Py_Identifier *static_strings;
184
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000185/* Single character Unicode strings in the Latin-1 range are being
186 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200187static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000188
Christian Heimes190d79e2008-01-30 11:58:22 +0000189/* Fast detection of the most frequent whitespace characters */
190const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000191 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000192/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000193/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000194/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000195/* case 0x000C: * FORM FEED */
196/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000197 0, 1, 1, 1, 1, 1, 0, 0,
198 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000199/* case 0x001C: * FILE SEPARATOR */
200/* case 0x001D: * GROUP SEPARATOR */
201/* case 0x001E: * RECORD SEPARATOR */
202/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000203 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000204/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000205 1, 0, 0, 0, 0, 0, 0, 0,
206 0, 0, 0, 0, 0, 0, 0, 0,
207 0, 0, 0, 0, 0, 0, 0, 0,
208 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000209
Benjamin Peterson14339b62009-01-31 16:36:08 +0000210 0, 0, 0, 0, 0, 0, 0, 0,
211 0, 0, 0, 0, 0, 0, 0, 0,
212 0, 0, 0, 0, 0, 0, 0, 0,
213 0, 0, 0, 0, 0, 0, 0, 0,
214 0, 0, 0, 0, 0, 0, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0,
217 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000218};
219
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200220/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200221static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200222static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200223static void copy_characters(
224 PyObject *to, Py_ssize_t to_start,
225 PyObject *from, Py_ssize_t from_start,
226 Py_ssize_t how_many);
Victor Stinner488fa492011-12-12 00:01:39 +0100227static int unicode_modifiable(PyObject *unicode);
228
Victor Stinnerfe226c02011-10-03 03:52:20 +0200229
Alexander Belopolsky40018472011-02-26 01:02:56 +0000230static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200231unicode_fromascii(const unsigned char *s, Py_ssize_t size);
232static PyObject *
233_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
234static PyObject *
235_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
236static PyObject *
237_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
238
239static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000240unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000241 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100242 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000243 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
244
Alexander Belopolsky40018472011-02-26 01:02:56 +0000245static void
246raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300247 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100248 PyObject *unicode,
249 Py_ssize_t startpos, Py_ssize_t endpos,
250 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000251
Christian Heimes190d79e2008-01-30 11:58:22 +0000252/* Same for linebreaks */
253static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000254 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000255/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000256/* 0x000B, * LINE TABULATION */
257/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000258/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000259 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000260 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000261/* 0x001C, * FILE SEPARATOR */
262/* 0x001D, * GROUP SEPARATOR */
263/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000264 0, 0, 0, 0, 1, 1, 1, 0,
265 0, 0, 0, 0, 0, 0, 0, 0,
266 0, 0, 0, 0, 0, 0, 0, 0,
267 0, 0, 0, 0, 0, 0, 0, 0,
268 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000269
Benjamin Peterson14339b62009-01-31 16:36:08 +0000270 0, 0, 0, 0, 0, 0, 0, 0,
271 0, 0, 0, 0, 0, 0, 0, 0,
272 0, 0, 0, 0, 0, 0, 0, 0,
273 0, 0, 0, 0, 0, 0, 0, 0,
274 0, 0, 0, 0, 0, 0, 0, 0,
275 0, 0, 0, 0, 0, 0, 0, 0,
276 0, 0, 0, 0, 0, 0, 0, 0,
277 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000278};
279
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300280/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
281 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000282Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000283PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000284{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000285#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000286 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000287#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000288 /* This is actually an illegal character, so it should
289 not be passed to unichr. */
290 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000291#endif
292}
293
Victor Stinner910337b2011-10-03 03:20:16 +0200294#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200295int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100296_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200297{
298 PyASCIIObject *ascii;
299 unsigned int kind;
300
301 assert(PyUnicode_Check(op));
302
303 ascii = (PyASCIIObject *)op;
304 kind = ascii->state.kind;
305
Victor Stinnera3b334d2011-10-03 13:53:37 +0200306 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200307 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200308 assert(ascii->state.ready == 1);
309 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200310 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200311 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200312 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200313
Victor Stinnera41463c2011-10-04 01:05:08 +0200314 if (ascii->state.compact == 1) {
315 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200316 assert(kind == PyUnicode_1BYTE_KIND
317 || kind == PyUnicode_2BYTE_KIND
318 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200319 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200320 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200321 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100322 }
323 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200324 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
325
326 data = unicode->data.any;
327 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100328 assert(ascii->length == 0);
329 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200330 assert(ascii->state.compact == 0);
331 assert(ascii->state.ascii == 0);
332 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100333 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 assert(ascii->wstr != NULL);
335 assert(data == NULL);
336 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200337 }
338 else {
339 assert(kind == PyUnicode_1BYTE_KIND
340 || kind == PyUnicode_2BYTE_KIND
341 || kind == PyUnicode_4BYTE_KIND);
342 assert(ascii->state.compact == 0);
343 assert(ascii->state.ready == 1);
344 assert(data != NULL);
345 if (ascii->state.ascii) {
346 assert (compact->utf8 == data);
347 assert (compact->utf8_length == ascii->length);
348 }
349 else
350 assert (compact->utf8 != data);
351 }
352 }
353 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200354 if (
355#if SIZEOF_WCHAR_T == 2
356 kind == PyUnicode_2BYTE_KIND
357#else
358 kind == PyUnicode_4BYTE_KIND
359#endif
360 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200361 {
362 assert(ascii->wstr == data);
363 assert(compact->wstr_length == ascii->length);
364 } else
365 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200366 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200367
368 if (compact->utf8 == NULL)
369 assert(compact->utf8_length == 0);
370 if (ascii->wstr == NULL)
371 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200372 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200373 /* check that the best kind is used */
374 if (check_content && kind != PyUnicode_WCHAR_KIND)
375 {
376 Py_ssize_t i;
377 Py_UCS4 maxchar = 0;
378 void *data = PyUnicode_DATA(ascii);
379 for (i=0; i < ascii->length; i++)
380 {
381 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
382 if (ch > maxchar)
383 maxchar = ch;
384 }
385 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100386 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200387 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100388 assert(maxchar <= 255);
389 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200390 else
391 assert(maxchar < 128);
392 }
Victor Stinner77faf692011-11-20 18:56:05 +0100393 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200394 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100395 assert(maxchar <= 0xFFFF);
396 }
397 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200398 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100399 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100400 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200401 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400402 return 1;
403}
Victor Stinner910337b2011-10-03 03:20:16 +0200404#endif
405
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100406static PyObject*
407unicode_result_wchar(PyObject *unicode)
408{
409#ifndef Py_DEBUG
410 Py_ssize_t len;
411
412 assert(Py_REFCNT(unicode) == 1);
413
414 len = _PyUnicode_WSTR_LENGTH(unicode);
415 if (len == 0) {
416 Py_INCREF(unicode_empty);
417 Py_DECREF(unicode);
418 return unicode_empty;
419 }
420
421 if (len == 1) {
422 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
423 if (ch < 256) {
424 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
425 Py_DECREF(unicode);
426 return latin1_char;
427 }
428 }
429
430 if (_PyUnicode_Ready(unicode) < 0) {
431 Py_XDECREF(unicode);
432 return NULL;
433 }
434#else
435 /* don't make the result ready in debug mode to ensure that the caller
436 makes the string ready before using it */
437 assert(_PyUnicode_CheckConsistency(unicode, 1));
438#endif
439 return unicode;
440}
441
442static PyObject*
443unicode_result_ready(PyObject *unicode)
444{
445 Py_ssize_t length;
446
447 length = PyUnicode_GET_LENGTH(unicode);
448 if (length == 0) {
449 if (unicode != unicode_empty) {
450 Py_INCREF(unicode_empty);
451 Py_DECREF(unicode);
452 }
453 return unicode_empty;
454 }
455
456 if (length == 1) {
457 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
458 if (ch < 256) {
459 PyObject *latin1_char = unicode_latin1[ch];
460 if (latin1_char != NULL) {
461 if (unicode != latin1_char) {
462 Py_INCREF(latin1_char);
463 Py_DECREF(unicode);
464 }
465 return latin1_char;
466 }
467 else {
468 assert(_PyUnicode_CheckConsistency(unicode, 1));
469 Py_INCREF(unicode);
470 unicode_latin1[ch] = unicode;
471 return unicode;
472 }
473 }
474 }
475
476 assert(_PyUnicode_CheckConsistency(unicode, 1));
477 return unicode;
478}
479
480static PyObject*
481unicode_result(PyObject *unicode)
482{
483 assert(_PyUnicode_CHECK(unicode));
484 if (PyUnicode_IS_READY(unicode))
485 return unicode_result_ready(unicode);
486 else
487 return unicode_result_wchar(unicode);
488}
489
Victor Stinnerc4b49542011-12-11 22:44:26 +0100490static PyObject*
491unicode_result_unchanged(PyObject *unicode)
492{
493 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500494 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100495 return NULL;
496 Py_INCREF(unicode);
497 return unicode;
498 }
499 else
500 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100501 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100502}
503
Victor Stinner3a50e702011-10-18 21:21:00 +0200504#ifdef HAVE_MBCS
505static OSVERSIONINFOEX winver;
506#endif
507
Thomas Wouters477c8d52006-05-27 19:21:47 +0000508/* --- Bloom Filters ----------------------------------------------------- */
509
510/* stuff to implement simple "bloom filters" for Unicode characters.
511 to keep things simple, we use a single bitmask, using the least 5
512 bits from each unicode characters as the bit index. */
513
514/* the linebreak mask is set up by Unicode_Init below */
515
Antoine Pitrouf068f942010-01-13 14:19:12 +0000516#if LONG_BIT >= 128
517#define BLOOM_WIDTH 128
518#elif LONG_BIT >= 64
519#define BLOOM_WIDTH 64
520#elif LONG_BIT >= 32
521#define BLOOM_WIDTH 32
522#else
523#error "LONG_BIT is smaller than 32"
524#endif
525
Thomas Wouters477c8d52006-05-27 19:21:47 +0000526#define BLOOM_MASK unsigned long
527
528static BLOOM_MASK bloom_linebreak;
529
Antoine Pitrouf068f942010-01-13 14:19:12 +0000530#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
531#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000532
Benjamin Peterson29060642009-01-31 22:14:21 +0000533#define BLOOM_LINEBREAK(ch) \
534 ((ch) < 128U ? ascii_linebreak[(ch)] : \
535 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000536
Alexander Belopolsky40018472011-02-26 01:02:56 +0000537Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200538make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539{
540 /* calculate simple bloom-style bitmask for a given unicode string */
541
Antoine Pitrouf068f942010-01-13 14:19:12 +0000542 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543 Py_ssize_t i;
544
545 mask = 0;
546 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200547 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000548
549 return mask;
550}
551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200552#define BLOOM_MEMBER(mask, chr, str) \
553 (BLOOM(mask, chr) \
554 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000555
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200556/* Compilation of templated routines */
557
558#include "stringlib/asciilib.h"
559#include "stringlib/fastsearch.h"
560#include "stringlib/partition.h"
561#include "stringlib/split.h"
562#include "stringlib/count.h"
563#include "stringlib/find.h"
564#include "stringlib/find_max_char.h"
565#include "stringlib/localeutil.h"
566#include "stringlib/undef.h"
567
568#include "stringlib/ucs1lib.h"
569#include "stringlib/fastsearch.h"
570#include "stringlib/partition.h"
571#include "stringlib/split.h"
572#include "stringlib/count.h"
573#include "stringlib/find.h"
574#include "stringlib/find_max_char.h"
575#include "stringlib/localeutil.h"
576#include "stringlib/undef.h"
577
578#include "stringlib/ucs2lib.h"
579#include "stringlib/fastsearch.h"
580#include "stringlib/partition.h"
581#include "stringlib/split.h"
582#include "stringlib/count.h"
583#include "stringlib/find.h"
584#include "stringlib/find_max_char.h"
585#include "stringlib/localeutil.h"
586#include "stringlib/undef.h"
587
588#include "stringlib/ucs4lib.h"
589#include "stringlib/fastsearch.h"
590#include "stringlib/partition.h"
591#include "stringlib/split.h"
592#include "stringlib/count.h"
593#include "stringlib/find.h"
594#include "stringlib/find_max_char.h"
595#include "stringlib/localeutil.h"
596#include "stringlib/undef.h"
597
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200598#include "stringlib/unicodedefs.h"
599#include "stringlib/fastsearch.h"
600#include "stringlib/count.h"
601#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100602#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200603
Guido van Rossumd57fd912000-03-10 22:53:23 +0000604/* --- Unicode Object ----------------------------------------------------- */
605
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200606static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200607fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200608
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200609Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
610 Py_ssize_t size, Py_UCS4 ch,
611 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200612{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200613 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
614
615 switch (kind) {
616 case PyUnicode_1BYTE_KIND:
617 {
618 Py_UCS1 ch1 = (Py_UCS1) ch;
619 if (ch1 == ch)
620 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
621 else
622 return -1;
623 }
624 case PyUnicode_2BYTE_KIND:
625 {
626 Py_UCS2 ch2 = (Py_UCS2) ch;
627 if (ch2 == ch)
628 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
629 else
630 return -1;
631 }
632 case PyUnicode_4BYTE_KIND:
633 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
634 default:
635 assert(0);
636 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200637 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200638}
639
Victor Stinnerfe226c02011-10-03 03:52:20 +0200640static PyObject*
641resize_compact(PyObject *unicode, Py_ssize_t length)
642{
643 Py_ssize_t char_size;
644 Py_ssize_t struct_size;
645 Py_ssize_t new_size;
646 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100647 PyObject *new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200648 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100649 assert(PyUnicode_IS_COMPACT(unicode));
650
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200651 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100652 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200653 struct_size = sizeof(PyASCIIObject);
654 else
655 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200656 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200657
Victor Stinnerfe226c02011-10-03 03:52:20 +0200658 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
659 PyErr_NoMemory();
660 return NULL;
661 }
662 new_size = (struct_size + (length + 1) * char_size);
663
Victor Stinner84def372011-12-11 20:04:56 +0100664 _Py_DEC_REFTOTAL;
665 _Py_ForgetReference(unicode);
666
667 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
668 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100669 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200670 PyErr_NoMemory();
671 return NULL;
672 }
Victor Stinner84def372011-12-11 20:04:56 +0100673 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200674 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100675
Victor Stinnerfe226c02011-10-03 03:52:20 +0200676 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200677 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200678 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100679 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200680 _PyUnicode_WSTR_LENGTH(unicode) = length;
681 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200682 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
683 length, 0);
684 return unicode;
685}
686
Alexander Belopolsky40018472011-02-26 01:02:56 +0000687static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200688resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000689{
Victor Stinner95663112011-10-04 01:03:50 +0200690 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100691 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200692 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200693 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000694
Victor Stinnerfe226c02011-10-03 03:52:20 +0200695 if (PyUnicode_IS_READY(unicode)) {
696 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200697 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200698 void *data;
699
700 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200701 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200702 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
703 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200704
705 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
706 PyErr_NoMemory();
707 return -1;
708 }
709 new_size = (length + 1) * char_size;
710
Victor Stinner7a9105a2011-12-12 00:13:42 +0100711 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
712 {
713 PyObject_DEL(_PyUnicode_UTF8(unicode));
714 _PyUnicode_UTF8(unicode) = NULL;
715 _PyUnicode_UTF8_LENGTH(unicode) = 0;
716 }
717
Victor Stinnerfe226c02011-10-03 03:52:20 +0200718 data = (PyObject *)PyObject_REALLOC(data, new_size);
719 if (data == NULL) {
720 PyErr_NoMemory();
721 return -1;
722 }
723 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200724 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200725 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200726 _PyUnicode_WSTR_LENGTH(unicode) = length;
727 }
728 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200729 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200730 _PyUnicode_UTF8_LENGTH(unicode) = length;
731 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200732 _PyUnicode_LENGTH(unicode) = length;
733 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200734 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200735 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200736 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200737 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200738 }
Victor Stinner95663112011-10-04 01:03:50 +0200739 assert(_PyUnicode_WSTR(unicode) != NULL);
740
741 /* check for integer overflow */
742 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
743 PyErr_NoMemory();
744 return -1;
745 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100746 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200747 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100748 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200749 if (!wstr) {
750 PyErr_NoMemory();
751 return -1;
752 }
753 _PyUnicode_WSTR(unicode) = wstr;
754 _PyUnicode_WSTR(unicode)[length] = 0;
755 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200756 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000757 return 0;
758}
759
Victor Stinnerfe226c02011-10-03 03:52:20 +0200760static PyObject*
761resize_copy(PyObject *unicode, Py_ssize_t length)
762{
763 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100764 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200765 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100766
Benjamin Petersonbac79492012-01-14 13:34:47 -0500767 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100768 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200769
770 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
771 if (copy == NULL)
772 return NULL;
773
774 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200775 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200776 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200777 }
778 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200779 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100780
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200781 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200782 if (w == NULL)
783 return NULL;
784 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
785 copy_length = Py_MIN(copy_length, length);
786 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
787 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200788 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200789 }
790}
791
Guido van Rossumd57fd912000-03-10 22:53:23 +0000792/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000793 Ux0000 terminated; some code (e.g. new_identifier)
794 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000795
796 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000797 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000798
799*/
800
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200801#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200802static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200803#endif
804
Alexander Belopolsky40018472011-02-26 01:02:56 +0000805static PyUnicodeObject *
806_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000807{
808 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200809 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000810
Thomas Wouters477c8d52006-05-27 19:21:47 +0000811 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000812 if (length == 0 && unicode_empty != NULL) {
813 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200814 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000815 }
816
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000817 /* Ensure we won't overflow the size. */
818 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
819 return (PyUnicodeObject *)PyErr_NoMemory();
820 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200821 if (length < 0) {
822 PyErr_SetString(PyExc_SystemError,
823 "Negative size passed to _PyUnicode_New");
824 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000825 }
826
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200827#ifdef Py_DEBUG
828 ++unicode_old_new_calls;
829#endif
830
831 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
832 if (unicode == NULL)
833 return NULL;
834 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
835 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
836 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100837 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000838 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100839 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000840 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200841
Jeremy Hyltond8082792003-09-16 19:41:39 +0000842 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000843 * the caller fails before initializing str -- unicode_resize()
844 * reads str[0], and the Keep-Alive optimization can keep memory
845 * allocated for str alive across a call to unicode_dealloc(unicode).
846 * We don't want unicode_resize to read uninitialized memory in
847 * that case.
848 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200849 _PyUnicode_WSTR(unicode)[0] = 0;
850 _PyUnicode_WSTR(unicode)[length] = 0;
851 _PyUnicode_WSTR_LENGTH(unicode) = length;
852 _PyUnicode_HASH(unicode) = -1;
853 _PyUnicode_STATE(unicode).interned = 0;
854 _PyUnicode_STATE(unicode).kind = 0;
855 _PyUnicode_STATE(unicode).compact = 0;
856 _PyUnicode_STATE(unicode).ready = 0;
857 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200858 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200859 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200860 _PyUnicode_UTF8(unicode) = NULL;
861 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100862 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000863 return unicode;
864}
865
Victor Stinnerf42dc442011-10-02 23:33:16 +0200866static const char*
867unicode_kind_name(PyObject *unicode)
868{
Victor Stinner42dfd712011-10-03 14:41:45 +0200869 /* don't check consistency: unicode_kind_name() is called from
870 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200871 if (!PyUnicode_IS_COMPACT(unicode))
872 {
873 if (!PyUnicode_IS_READY(unicode))
874 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600875 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200876 {
877 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200878 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200879 return "legacy ascii";
880 else
881 return "legacy latin1";
882 case PyUnicode_2BYTE_KIND:
883 return "legacy UCS2";
884 case PyUnicode_4BYTE_KIND:
885 return "legacy UCS4";
886 default:
887 return "<legacy invalid kind>";
888 }
889 }
890 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600891 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200892 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200893 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200894 return "ascii";
895 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200896 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200897 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200898 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200899 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200900 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200901 default:
902 return "<invalid compact kind>";
903 }
904}
905
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200906#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200907static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200908
909/* Functions wrapping macros for use in debugger */
910char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200911 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200912}
913
914void *_PyUnicode_compact_data(void *unicode) {
915 return _PyUnicode_COMPACT_DATA(unicode);
916}
917void *_PyUnicode_data(void *unicode){
918 printf("obj %p\n", unicode);
919 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
920 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
921 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
922 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
923 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
924 return PyUnicode_DATA(unicode);
925}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200926
927void
928_PyUnicode_Dump(PyObject *op)
929{
930 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200931 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
932 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
933 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200934
Victor Stinnera849a4b2011-10-03 12:12:11 +0200935 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200936 {
937 if (ascii->state.ascii)
938 data = (ascii + 1);
939 else
940 data = (compact + 1);
941 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200942 else
943 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200944 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
945
Victor Stinnera849a4b2011-10-03 12:12:11 +0200946 if (ascii->wstr == data)
947 printf("shared ");
948 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200949
Victor Stinnera3b334d2011-10-03 13:53:37 +0200950 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200951 printf(" (%zu), ", compact->wstr_length);
952 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
953 printf("shared ");
954 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200955 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200956 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200957}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200958#endif
959
960PyObject *
961PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
962{
963 PyObject *obj;
964 PyCompactUnicodeObject *unicode;
965 void *data;
966 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200967 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200968 Py_ssize_t char_size;
969 Py_ssize_t struct_size;
970
971 /* Optimization for empty strings */
972 if (size == 0 && unicode_empty != NULL) {
973 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200974 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200975 }
976
977#ifdef Py_DEBUG
978 ++unicode_new_new_calls;
979#endif
980
Victor Stinner9e9d6892011-10-04 01:02:02 +0200981 is_ascii = 0;
982 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200983 struct_size = sizeof(PyCompactUnicodeObject);
984 if (maxchar < 128) {
985 kind_state = PyUnicode_1BYTE_KIND;
986 char_size = 1;
987 is_ascii = 1;
988 struct_size = sizeof(PyASCIIObject);
989 }
990 else if (maxchar < 256) {
991 kind_state = PyUnicode_1BYTE_KIND;
992 char_size = 1;
993 }
994 else if (maxchar < 65536) {
995 kind_state = PyUnicode_2BYTE_KIND;
996 char_size = 2;
997 if (sizeof(wchar_t) == 2)
998 is_sharing = 1;
999 }
1000 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001001 if (maxchar > MAX_UNICODE) {
1002 PyErr_SetString(PyExc_SystemError,
1003 "invalid maximum character passed to PyUnicode_New");
1004 return NULL;
1005 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001006 kind_state = PyUnicode_4BYTE_KIND;
1007 char_size = 4;
1008 if (sizeof(wchar_t) == 4)
1009 is_sharing = 1;
1010 }
1011
1012 /* Ensure we won't overflow the size. */
1013 if (size < 0) {
1014 PyErr_SetString(PyExc_SystemError,
1015 "Negative size passed to PyUnicode_New");
1016 return NULL;
1017 }
1018 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1019 return PyErr_NoMemory();
1020
1021 /* Duplicated allocation code from _PyObject_New() instead of a call to
1022 * PyObject_New() so we are able to allocate space for the object and
1023 * it's data buffer.
1024 */
1025 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1026 if (obj == NULL)
1027 return PyErr_NoMemory();
1028 obj = PyObject_INIT(obj, &PyUnicode_Type);
1029 if (obj == NULL)
1030 return NULL;
1031
1032 unicode = (PyCompactUnicodeObject *)obj;
1033 if (is_ascii)
1034 data = ((PyASCIIObject*)obj) + 1;
1035 else
1036 data = unicode + 1;
1037 _PyUnicode_LENGTH(unicode) = size;
1038 _PyUnicode_HASH(unicode) = -1;
1039 _PyUnicode_STATE(unicode).interned = 0;
1040 _PyUnicode_STATE(unicode).kind = kind_state;
1041 _PyUnicode_STATE(unicode).compact = 1;
1042 _PyUnicode_STATE(unicode).ready = 1;
1043 _PyUnicode_STATE(unicode).ascii = is_ascii;
1044 if (is_ascii) {
1045 ((char*)data)[size] = 0;
1046 _PyUnicode_WSTR(unicode) = NULL;
1047 }
1048 else if (kind_state == PyUnicode_1BYTE_KIND) {
1049 ((char*)data)[size] = 0;
1050 _PyUnicode_WSTR(unicode) = NULL;
1051 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001053 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054 }
1055 else {
1056 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001057 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001058 if (kind_state == PyUnicode_2BYTE_KIND)
1059 ((Py_UCS2*)data)[size] = 0;
1060 else /* kind_state == PyUnicode_4BYTE_KIND */
1061 ((Py_UCS4*)data)[size] = 0;
1062 if (is_sharing) {
1063 _PyUnicode_WSTR_LENGTH(unicode) = size;
1064 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1065 }
1066 else {
1067 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1068 _PyUnicode_WSTR(unicode) = NULL;
1069 }
1070 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01001071 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001072 return obj;
1073}
1074
1075#if SIZEOF_WCHAR_T == 2
1076/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1077 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001078 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001079
1080 This function assumes that unicode can hold one more code point than wstr
1081 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001082static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001083unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001084 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001085{
1086 const wchar_t *iter;
1087 Py_UCS4 *ucs4_out;
1088
Victor Stinner910337b2011-10-03 03:20:16 +02001089 assert(unicode != NULL);
1090 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001091 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1092 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1093
1094 for (iter = begin; iter < end; ) {
1095 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1096 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001097 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1098 && (iter+1) < end
1099 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001100 {
Victor Stinner551ac952011-11-29 22:58:13 +01001101 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001102 iter += 2;
1103 }
1104 else {
1105 *ucs4_out++ = *iter;
1106 iter++;
1107 }
1108 }
1109 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1110 _PyUnicode_GET_LENGTH(unicode)));
1111
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001112}
1113#endif
1114
Victor Stinnercd9950f2011-10-02 00:34:53 +02001115static int
Victor Stinner488fa492011-12-12 00:01:39 +01001116unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001117{
Victor Stinner488fa492011-12-12 00:01:39 +01001118 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001119 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001120 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001121 return -1;
1122 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001123 return 0;
1124}
1125
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001126static int
1127_copy_characters(PyObject *to, Py_ssize_t to_start,
1128 PyObject *from, Py_ssize_t from_start,
1129 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001130{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001131 unsigned int from_kind, to_kind;
1132 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001133 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001134
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001135 assert(PyUnicode_Check(from));
1136 assert(PyUnicode_Check(to));
1137 assert(PyUnicode_IS_READY(from));
1138 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001139
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001140 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1141 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1142 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001143
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001144 if (how_many == 0)
1145 return 0;
1146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001147 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001148 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001149 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001150 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001151
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001152#ifdef Py_DEBUG
1153 if (!check_maxchar
1154 && (from_kind > to_kind
1155 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001156 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001157 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1158 Py_UCS4 ch;
1159 Py_ssize_t i;
1160 for (i=0; i < how_many; i++) {
1161 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1162 assert(ch <= to_maxchar);
1163 }
1164 }
1165#endif
1166 fast = (from_kind == to_kind);
1167 if (check_maxchar
1168 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1169 {
1170 /* deny latin1 => ascii */
1171 fast = 0;
1172 }
1173
1174 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001175 Py_MEMCPY((char*)to_data + to_kind * to_start,
1176 (char*)from_data + from_kind * from_start,
1177 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001178 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001179 else if (from_kind == PyUnicode_1BYTE_KIND
1180 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001181 {
1182 _PyUnicode_CONVERT_BYTES(
1183 Py_UCS1, Py_UCS2,
1184 PyUnicode_1BYTE_DATA(from) + from_start,
1185 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1186 PyUnicode_2BYTE_DATA(to) + to_start
1187 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001188 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001189 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001190 && to_kind == PyUnicode_4BYTE_KIND)
1191 {
1192 _PyUnicode_CONVERT_BYTES(
1193 Py_UCS1, Py_UCS4,
1194 PyUnicode_1BYTE_DATA(from) + from_start,
1195 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1196 PyUnicode_4BYTE_DATA(to) + to_start
1197 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001198 }
1199 else if (from_kind == PyUnicode_2BYTE_KIND
1200 && to_kind == PyUnicode_4BYTE_KIND)
1201 {
1202 _PyUnicode_CONVERT_BYTES(
1203 Py_UCS2, Py_UCS4,
1204 PyUnicode_2BYTE_DATA(from) + from_start,
1205 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1206 PyUnicode_4BYTE_DATA(to) + to_start
1207 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001208 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001209 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001210 /* check if max_char(from substring) <= max_char(to) */
1211 if (from_kind > to_kind
1212 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001213 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001214 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001215 /* slow path to check for character overflow */
1216 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001217 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001218 Py_ssize_t i;
1219
Victor Stinner56c161a2011-10-06 02:47:11 +02001220#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001221 for (i=0; i < how_many; i++) {
1222 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001223 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001224 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1225 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001226#else
1227 if (!check_maxchar) {
1228 for (i=0; i < how_many; i++) {
1229 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1230 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1231 }
1232 }
1233 else {
1234 for (i=0; i < how_many; i++) {
1235 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1236 if (ch > to_maxchar)
1237 return 1;
1238 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1239 }
1240 }
1241#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001242 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001243 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001244 assert(0 && "inconsistent state");
1245 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001246 }
1247 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001248 return 0;
1249}
1250
1251static void
1252copy_characters(PyObject *to, Py_ssize_t to_start,
1253 PyObject *from, Py_ssize_t from_start,
1254 Py_ssize_t how_many)
1255{
1256 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1257}
1258
1259Py_ssize_t
1260PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1261 PyObject *from, Py_ssize_t from_start,
1262 Py_ssize_t how_many)
1263{
1264 int err;
1265
1266 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1267 PyErr_BadInternalCall();
1268 return -1;
1269 }
1270
Benjamin Petersonbac79492012-01-14 13:34:47 -05001271 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001272 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001273 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001274 return -1;
1275
1276 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1277 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1278 PyErr_Format(PyExc_SystemError,
1279 "Cannot write %zi characters at %zi "
1280 "in a string of %zi characters",
1281 how_many, to_start, PyUnicode_GET_LENGTH(to));
1282 return -1;
1283 }
1284
1285 if (how_many == 0)
1286 return 0;
1287
Victor Stinner488fa492011-12-12 00:01:39 +01001288 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001289 return -1;
1290
1291 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1292 if (err) {
1293 PyErr_Format(PyExc_SystemError,
1294 "Cannot copy %s characters "
1295 "into a string of %s characters",
1296 unicode_kind_name(from),
1297 unicode_kind_name(to));
1298 return -1;
1299 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001300 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001301}
1302
Victor Stinner17222162011-09-28 22:15:37 +02001303/* Find the maximum code point and count the number of surrogate pairs so a
1304 correct string length can be computed before converting a string to UCS4.
1305 This function counts single surrogates as a character and not as a pair.
1306
1307 Return 0 on success, or -1 on error. */
1308static int
1309find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1310 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001311{
1312 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001313 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001314
Victor Stinnerc53be962011-10-02 21:33:54 +02001315 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316 *num_surrogates = 0;
1317 *maxchar = 0;
1318
1319 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001321 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1322 && (iter+1) < end
1323 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001325 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001326 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001327 iter += 2;
1328 }
1329 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001330#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001331 {
1332 ch = *iter;
1333 iter++;
1334 }
1335 if (ch > *maxchar) {
1336 *maxchar = ch;
1337 if (*maxchar > MAX_UNICODE) {
1338 PyErr_Format(PyExc_ValueError,
1339 "character U+%x is not in range [U+0000; U+10ffff]",
1340 ch);
1341 return -1;
1342 }
1343 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001344 }
1345 return 0;
1346}
1347
1348#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001349static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350#endif
1351
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001352int
1353_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001354{
1355 wchar_t *end;
1356 Py_UCS4 maxchar = 0;
1357 Py_ssize_t num_surrogates;
1358#if SIZEOF_WCHAR_T == 2
1359 Py_ssize_t length_wo_surrogates;
1360#endif
1361
Georg Brandl7597add2011-10-05 16:36:47 +02001362 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001363 strings were created using _PyObject_New() and where no canonical
1364 representation (the str field) has been set yet aka strings
1365 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001366 assert(_PyUnicode_CHECK(unicode));
1367 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001368 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001369 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001370 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001371 /* Actually, it should neither be interned nor be anything else: */
1372 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001373
1374#ifdef Py_DEBUG
1375 ++unicode_ready_calls;
1376#endif
1377
1378 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001379 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001380 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001381 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001382
1383 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001384 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1385 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001386 PyErr_NoMemory();
1387 return -1;
1388 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001389 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001390 _PyUnicode_WSTR(unicode), end,
1391 PyUnicode_1BYTE_DATA(unicode));
1392 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1393 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1394 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1395 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001396 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001397 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001398 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001399 }
1400 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001401 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001402 _PyUnicode_UTF8(unicode) = NULL;
1403 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001404 }
1405 PyObject_FREE(_PyUnicode_WSTR(unicode));
1406 _PyUnicode_WSTR(unicode) = NULL;
1407 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1408 }
1409 /* In this case we might have to convert down from 4-byte native
1410 wchar_t to 2-byte unicode. */
1411 else if (maxchar < 65536) {
1412 assert(num_surrogates == 0 &&
1413 "FindMaxCharAndNumSurrogatePairs() messed up");
1414
Victor Stinner506f5922011-09-28 22:34:18 +02001415#if SIZEOF_WCHAR_T == 2
1416 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001417 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001418 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1419 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1420 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001421 _PyUnicode_UTF8(unicode) = NULL;
1422 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001423#else
1424 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001425 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001426 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001427 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001428 PyErr_NoMemory();
1429 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001430 }
Victor Stinner506f5922011-09-28 22:34:18 +02001431 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1432 _PyUnicode_WSTR(unicode), end,
1433 PyUnicode_2BYTE_DATA(unicode));
1434 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1435 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1436 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001437 _PyUnicode_UTF8(unicode) = NULL;
1438 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001439 PyObject_FREE(_PyUnicode_WSTR(unicode));
1440 _PyUnicode_WSTR(unicode) = NULL;
1441 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1442#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001443 }
1444 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1445 else {
1446#if SIZEOF_WCHAR_T == 2
1447 /* in case the native representation is 2-bytes, we need to allocate a
1448 new normalized 4-byte version. */
1449 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001450 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1451 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001452 PyErr_NoMemory();
1453 return -1;
1454 }
1455 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1456 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001457 _PyUnicode_UTF8(unicode) = NULL;
1458 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001459 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1460 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001461 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001462 PyObject_FREE(_PyUnicode_WSTR(unicode));
1463 _PyUnicode_WSTR(unicode) = NULL;
1464 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1465#else
1466 assert(num_surrogates == 0);
1467
Victor Stinnerc3c74152011-10-02 20:39:55 +02001468 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001469 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001470 _PyUnicode_UTF8(unicode) = NULL;
1471 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001472 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1473#endif
1474 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1475 }
1476 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001477 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001478 return 0;
1479}
1480
Alexander Belopolsky40018472011-02-26 01:02:56 +00001481static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001482unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001483{
Walter Dörwald16807132007-05-25 13:52:07 +00001484 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001485 case SSTATE_NOT_INTERNED:
1486 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001487
Benjamin Peterson29060642009-01-31 22:14:21 +00001488 case SSTATE_INTERNED_MORTAL:
1489 /* revive dead object temporarily for DelItem */
1490 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001491 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001492 Py_FatalError(
1493 "deletion of interned string failed");
1494 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001495
Benjamin Peterson29060642009-01-31 22:14:21 +00001496 case SSTATE_INTERNED_IMMORTAL:
1497 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001498
Benjamin Peterson29060642009-01-31 22:14:21 +00001499 default:
1500 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001501 }
1502
Victor Stinner03490912011-10-03 23:45:12 +02001503 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001504 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001505 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001506 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001507 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1508 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001509
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001510 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001511}
1512
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001513#ifdef Py_DEBUG
1514static int
1515unicode_is_singleton(PyObject *unicode)
1516{
1517 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1518 if (unicode == unicode_empty)
1519 return 1;
1520 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1521 {
1522 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1523 if (ch < 256 && unicode_latin1[ch] == unicode)
1524 return 1;
1525 }
1526 return 0;
1527}
1528#endif
1529
Alexander Belopolsky40018472011-02-26 01:02:56 +00001530static int
Victor Stinner488fa492011-12-12 00:01:39 +01001531unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001532{
Victor Stinner488fa492011-12-12 00:01:39 +01001533 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001534 if (Py_REFCNT(unicode) != 1)
1535 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001536 if (_PyUnicode_HASH(unicode) != -1)
1537 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001538 if (PyUnicode_CHECK_INTERNED(unicode))
1539 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001540 if (!PyUnicode_CheckExact(unicode))
1541 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001542#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001543 /* singleton refcount is greater than 1 */
1544 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001545#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001546 return 1;
1547}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001548
Victor Stinnerfe226c02011-10-03 03:52:20 +02001549static int
1550unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1551{
1552 PyObject *unicode;
1553 Py_ssize_t old_length;
1554
1555 assert(p_unicode != NULL);
1556 unicode = *p_unicode;
1557
1558 assert(unicode != NULL);
1559 assert(PyUnicode_Check(unicode));
1560 assert(0 <= length);
1561
Victor Stinner910337b2011-10-03 03:20:16 +02001562 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001563 old_length = PyUnicode_WSTR_LENGTH(unicode);
1564 else
1565 old_length = PyUnicode_GET_LENGTH(unicode);
1566 if (old_length == length)
1567 return 0;
1568
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001569 if (length == 0) {
1570 Py_DECREF(*p_unicode);
1571 *p_unicode = unicode_empty;
1572 Py_INCREF(*p_unicode);
1573 return 0;
1574 }
1575
Victor Stinner488fa492011-12-12 00:01:39 +01001576 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001577 PyObject *copy = resize_copy(unicode, length);
1578 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001579 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001580 Py_DECREF(*p_unicode);
1581 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001582 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001583 }
1584
Victor Stinnerfe226c02011-10-03 03:52:20 +02001585 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001586 PyObject *new_unicode = resize_compact(unicode, length);
1587 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001588 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001589 *p_unicode = new_unicode;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001590 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001591 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001592 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001593 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001594}
1595
Alexander Belopolsky40018472011-02-26 01:02:56 +00001596int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001597PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001598{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001599 PyObject *unicode;
1600 if (p_unicode == NULL) {
1601 PyErr_BadInternalCall();
1602 return -1;
1603 }
1604 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001605 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001606 {
1607 PyErr_BadInternalCall();
1608 return -1;
1609 }
1610 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001611}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001612
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001613static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001614unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001615{
1616 PyObject *result;
1617 assert(PyUnicode_IS_READY(*p_unicode));
1618 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1619 return 0;
1620 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1621 maxchar);
1622 if (result == NULL)
1623 return -1;
1624 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1625 PyUnicode_GET_LENGTH(*p_unicode));
1626 Py_DECREF(*p_unicode);
1627 *p_unicode = result;
1628 return 0;
1629}
1630
1631static int
1632unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1633 Py_UCS4 ch)
1634{
Victor Stinner15e9ed22012-02-22 13:36:20 +01001635 assert(ch <= MAX_UNICODE);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001636 if (unicode_widen(p_unicode, ch) < 0)
1637 return -1;
1638 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1639 PyUnicode_DATA(*p_unicode),
1640 (*pos)++, ch);
1641 return 0;
1642}
1643
Victor Stinnerc5166102012-02-22 13:55:02 +01001644/* Copy a ASCII or latin1 char* string into a Python Unicode string.
1645 Return the length of the input string.
1646
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001647 WARNING: The function doesn't copy the terminating null character and
1648 doesn't check the maximum character (may write a latin1 character in an
1649 ASCII string). */
Victor Stinnerc5166102012-02-22 13:55:02 +01001650static Py_ssize_t
1651unicode_write_cstr(PyObject *unicode, Py_ssize_t index, const char *str)
1652{
1653 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1654 void *data = PyUnicode_DATA(unicode);
1655
1656 switch (kind) {
1657 case PyUnicode_1BYTE_KIND: {
1658 Py_ssize_t len = strlen(str);
1659 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001660 memcpy((char *) data + index, str, len);
Victor Stinnerc5166102012-02-22 13:55:02 +01001661 return len;
1662 }
1663 case PyUnicode_2BYTE_KIND: {
1664 Py_UCS2 *start = (Py_UCS2 *)data + index;
1665 Py_UCS2 *ucs2 = start;
1666 assert(index <= PyUnicode_GET_LENGTH(unicode));
1667
1668 for (; *str; ++ucs2, ++str)
1669 *ucs2 = (Py_UCS2)*str;
1670
1671 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
1672 return ucs2 - start;
1673 }
1674 default: {
1675 Py_UCS4 *start = (Py_UCS4 *)data + index;
1676 Py_UCS4 *ucs4 = start;
1677 assert(kind == PyUnicode_4BYTE_KIND);
1678 assert(index <= PyUnicode_GET_LENGTH(unicode));
1679
1680 for (; *str; ++ucs4, ++str)
1681 *ucs4 = (Py_UCS4)*str;
1682
1683 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
1684 return ucs4 - start;
1685 }
1686 }
1687}
1688
1689
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001690static PyObject*
1691get_latin1_char(unsigned char ch)
1692{
Victor Stinnera464fc12011-10-02 20:39:30 +02001693 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001694 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001695 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001696 if (!unicode)
1697 return NULL;
1698 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001699 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001700 unicode_latin1[ch] = unicode;
1701 }
1702 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001703 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001704}
1705
Alexander Belopolsky40018472011-02-26 01:02:56 +00001706PyObject *
1707PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001708{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001709 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001710 Py_UCS4 maxchar = 0;
1711 Py_ssize_t num_surrogates;
1712
1713 if (u == NULL)
1714 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001715
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001716 /* If the Unicode data is known at construction time, we can apply
1717 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001718
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001719 /* Optimization for empty strings */
1720 if (size == 0 && unicode_empty != NULL) {
1721 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001722 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001723 }
Tim Petersced69f82003-09-16 20:30:58 +00001724
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001725 /* Single character Unicode objects in the Latin-1 range are
1726 shared when using this constructor */
1727 if (size == 1 && *u < 256)
1728 return get_latin1_char((unsigned char)*u);
1729
1730 /* If not empty and not single character, copy the Unicode data
1731 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001732 if (find_maxchar_surrogates(u, u + size,
1733 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001734 return NULL;
1735
Victor Stinner8faf8212011-12-08 22:14:11 +01001736 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001737 if (!unicode)
1738 return NULL;
1739
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001740 switch (PyUnicode_KIND(unicode)) {
1741 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001742 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001743 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1744 break;
1745 case PyUnicode_2BYTE_KIND:
1746#if Py_UNICODE_SIZE == 2
1747 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1748#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001749 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001750 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1751#endif
1752 break;
1753 case PyUnicode_4BYTE_KIND:
1754#if SIZEOF_WCHAR_T == 2
1755 /* This is the only case which has to process surrogates, thus
1756 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001757 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758#else
1759 assert(num_surrogates == 0);
1760 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1761#endif
1762 break;
1763 default:
1764 assert(0 && "Impossible state");
1765 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001766
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001767 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001768}
1769
Alexander Belopolsky40018472011-02-26 01:02:56 +00001770PyObject *
1771PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001772{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001773 if (size < 0) {
1774 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001775 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001776 return NULL;
1777 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001778 if (u != NULL)
1779 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1780 else
1781 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001782}
1783
Alexander Belopolsky40018472011-02-26 01:02:56 +00001784PyObject *
1785PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001786{
1787 size_t size = strlen(u);
1788 if (size > PY_SSIZE_T_MAX) {
1789 PyErr_SetString(PyExc_OverflowError, "input too long");
1790 return NULL;
1791 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001792 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001793}
1794
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001795PyObject *
1796_PyUnicode_FromId(_Py_Identifier *id)
1797{
1798 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001799 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1800 strlen(id->string),
1801 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001802 if (!id->object)
1803 return NULL;
1804 PyUnicode_InternInPlace(&id->object);
1805 assert(!id->next);
1806 id->next = static_strings;
1807 static_strings = id;
1808 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001809 return id->object;
1810}
1811
1812void
1813_PyUnicode_ClearStaticStrings()
1814{
1815 _Py_Identifier *i;
1816 for (i = static_strings; i; i = i->next) {
1817 Py_DECREF(i->object);
1818 i->object = NULL;
1819 i->next = NULL;
1820 }
1821}
1822
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001823/* Internal function, don't check maximum character */
1824
Victor Stinnere57b1c02011-09-28 22:20:48 +02001825static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001826unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001827{
Victor Stinner785938e2011-12-11 20:09:03 +01001828 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001829 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001830#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001831 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001832#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001833 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001834 }
Victor Stinner785938e2011-12-11 20:09:03 +01001835 unicode = PyUnicode_New(size, 127);
1836 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001837 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001838 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1839 assert(_PyUnicode_CheckConsistency(unicode, 1));
1840 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001841}
1842
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001843static Py_UCS4
1844kind_maxchar_limit(unsigned int kind)
1845{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001846 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001847 case PyUnicode_1BYTE_KIND:
1848 return 0x80;
1849 case PyUnicode_2BYTE_KIND:
1850 return 0x100;
1851 case PyUnicode_4BYTE_KIND:
1852 return 0x10000;
1853 default:
1854 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001855 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001856 }
1857}
1858
Victor Stinner702c7342011-10-05 13:50:52 +02001859static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001860_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001861{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001862 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001863 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001864
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001865 if (size == 0) {
1866 Py_INCREF(unicode_empty);
1867 return unicode_empty;
1868 }
1869 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001870 if (size == 1)
1871 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001872
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001873 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001874 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001875 if (!res)
1876 return NULL;
1877 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001878 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001879 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001880}
1881
Victor Stinnere57b1c02011-09-28 22:20:48 +02001882static PyObject*
1883_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001884{
1885 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001886 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001887
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001888 if (size == 0) {
1889 Py_INCREF(unicode_empty);
1890 return unicode_empty;
1891 }
1892 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001893 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001894 return get_latin1_char((unsigned char)u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001895
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001896 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001897 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001898 if (!res)
1899 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001900 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001901 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001902 else {
1903 _PyUnicode_CONVERT_BYTES(
1904 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1905 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001906 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001907 return res;
1908}
1909
Victor Stinnere57b1c02011-09-28 22:20:48 +02001910static PyObject*
1911_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001912{
1913 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001914 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001915
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001916 if (size == 0) {
1917 Py_INCREF(unicode_empty);
1918 return unicode_empty;
1919 }
1920 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001921 if (size == 1 && u[0] < 256)
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001922 return get_latin1_char((unsigned char)u[0]);
1923
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001924 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001925 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001926 if (!res)
1927 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001928 if (max_char < 256)
1929 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1930 PyUnicode_1BYTE_DATA(res));
1931 else if (max_char < 0x10000)
1932 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1933 PyUnicode_2BYTE_DATA(res));
1934 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001935 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001936 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001937 return res;
1938}
1939
1940PyObject*
1941PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1942{
Victor Stinnercfed46e2011-11-22 01:29:14 +01001943 if (size < 0) {
1944 PyErr_SetString(PyExc_ValueError, "size must be positive");
1945 return NULL;
1946 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06001947 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001948 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001949 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001950 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001951 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001952 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001953 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001954 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02001955 PyErr_SetString(PyExc_SystemError, "invalid kind");
1956 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001957 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001958}
1959
Victor Stinner25a4b292011-10-06 12:31:55 +02001960/* Ensure that a string uses the most efficient storage, if it is not the
1961 case: create a new string with of the right kind. Write NULL into *p_unicode
1962 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001963static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001964unicode_adjust_maxchar(PyObject **p_unicode)
1965{
1966 PyObject *unicode, *copy;
1967 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001968 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001969 unsigned int kind;
1970
1971 assert(p_unicode != NULL);
1972 unicode = *p_unicode;
1973 assert(PyUnicode_IS_READY(unicode));
1974 if (PyUnicode_IS_ASCII(unicode))
1975 return;
1976
1977 len = PyUnicode_GET_LENGTH(unicode);
1978 kind = PyUnicode_KIND(unicode);
1979 if (kind == PyUnicode_1BYTE_KIND) {
1980 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001981 max_char = ucs1lib_find_max_char(u, u + len);
1982 if (max_char >= 128)
1983 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001984 }
1985 else if (kind == PyUnicode_2BYTE_KIND) {
1986 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001987 max_char = ucs2lib_find_max_char(u, u + len);
1988 if (max_char >= 256)
1989 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001990 }
1991 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001992 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001993 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001994 max_char = ucs4lib_find_max_char(u, u + len);
1995 if (max_char >= 0x10000)
1996 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001997 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001998 copy = PyUnicode_New(len, max_char);
1999 copy_characters(copy, 0, unicode, 0, len);
2000 Py_DECREF(unicode);
2001 *p_unicode = copy;
2002}
2003
Victor Stinner034f6cf2011-09-30 02:26:44 +02002004PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002005_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002006{
Victor Stinner87af4f22011-11-21 23:03:47 +01002007 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002008 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002009
Victor Stinner034f6cf2011-09-30 02:26:44 +02002010 if (!PyUnicode_Check(unicode)) {
2011 PyErr_BadInternalCall();
2012 return NULL;
2013 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002014 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002015 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002016
Victor Stinner87af4f22011-11-21 23:03:47 +01002017 length = PyUnicode_GET_LENGTH(unicode);
2018 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002019 if (!copy)
2020 return NULL;
2021 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2022
Victor Stinner87af4f22011-11-21 23:03:47 +01002023 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2024 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002025 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002026 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002027}
2028
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002029
Victor Stinnerbc603d12011-10-02 01:00:40 +02002030/* Widen Unicode objects to larger buffers. Don't write terminating null
2031 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002032
2033void*
2034_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2035{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002036 Py_ssize_t len;
2037 void *result;
2038 unsigned int skind;
2039
Benjamin Petersonbac79492012-01-14 13:34:47 -05002040 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002041 return NULL;
2042
2043 len = PyUnicode_GET_LENGTH(s);
2044 skind = PyUnicode_KIND(s);
2045 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002046 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047 return NULL;
2048 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002049 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002050 case PyUnicode_2BYTE_KIND:
2051 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2052 if (!result)
2053 return PyErr_NoMemory();
2054 assert(skind == PyUnicode_1BYTE_KIND);
2055 _PyUnicode_CONVERT_BYTES(
2056 Py_UCS1, Py_UCS2,
2057 PyUnicode_1BYTE_DATA(s),
2058 PyUnicode_1BYTE_DATA(s) + len,
2059 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002060 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002061 case PyUnicode_4BYTE_KIND:
2062 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2063 if (!result)
2064 return PyErr_NoMemory();
2065 if (skind == PyUnicode_2BYTE_KIND) {
2066 _PyUnicode_CONVERT_BYTES(
2067 Py_UCS2, Py_UCS4,
2068 PyUnicode_2BYTE_DATA(s),
2069 PyUnicode_2BYTE_DATA(s) + len,
2070 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002071 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002072 else {
2073 assert(skind == PyUnicode_1BYTE_KIND);
2074 _PyUnicode_CONVERT_BYTES(
2075 Py_UCS1, Py_UCS4,
2076 PyUnicode_1BYTE_DATA(s),
2077 PyUnicode_1BYTE_DATA(s) + len,
2078 result);
2079 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002080 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002081 default:
2082 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002083 }
Victor Stinner01698042011-10-04 00:04:26 +02002084 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002085 return NULL;
2086}
2087
2088static Py_UCS4*
2089as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2090 int copy_null)
2091{
2092 int kind;
2093 void *data;
2094 Py_ssize_t len, targetlen;
2095 if (PyUnicode_READY(string) == -1)
2096 return NULL;
2097 kind = PyUnicode_KIND(string);
2098 data = PyUnicode_DATA(string);
2099 len = PyUnicode_GET_LENGTH(string);
2100 targetlen = len;
2101 if (copy_null)
2102 targetlen++;
2103 if (!target) {
2104 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2105 PyErr_NoMemory();
2106 return NULL;
2107 }
2108 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2109 if (!target) {
2110 PyErr_NoMemory();
2111 return NULL;
2112 }
2113 }
2114 else {
2115 if (targetsize < targetlen) {
2116 PyErr_Format(PyExc_SystemError,
2117 "string is longer than the buffer");
2118 if (copy_null && 0 < targetsize)
2119 target[0] = 0;
2120 return NULL;
2121 }
2122 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002123 if (kind == PyUnicode_1BYTE_KIND) {
2124 Py_UCS1 *start = (Py_UCS1 *) data;
2125 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002126 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002127 else if (kind == PyUnicode_2BYTE_KIND) {
2128 Py_UCS2 *start = (Py_UCS2 *) data;
2129 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2130 }
2131 else {
2132 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002133 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002134 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002135 if (copy_null)
2136 target[len] = 0;
2137 return target;
2138}
2139
2140Py_UCS4*
2141PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2142 int copy_null)
2143{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002144 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002145 PyErr_BadInternalCall();
2146 return NULL;
2147 }
2148 return as_ucs4(string, target, targetsize, copy_null);
2149}
2150
2151Py_UCS4*
2152PyUnicode_AsUCS4Copy(PyObject *string)
2153{
2154 return as_ucs4(string, NULL, 0, 1);
2155}
2156
2157#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002158
Alexander Belopolsky40018472011-02-26 01:02:56 +00002159PyObject *
2160PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002161{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002162 if (w == NULL) {
Victor Stinner382955f2011-12-11 21:44:00 +01002163 if (size == 0) {
2164 Py_INCREF(unicode_empty);
2165 return unicode_empty;
2166 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002167 PyErr_BadInternalCall();
2168 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002169 }
2170
Martin v. Löwis790465f2008-04-05 20:41:37 +00002171 if (size == -1) {
2172 size = wcslen(w);
2173 }
2174
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002175 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002176}
2177
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002178#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002179
Walter Dörwald346737f2007-05-31 10:44:43 +00002180static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002181makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2182 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002183{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002184 *fmt++ = '%';
2185 if (width) {
2186 if (zeropad)
2187 *fmt++ = '0';
2188 fmt += sprintf(fmt, "%d", width);
2189 }
2190 if (precision)
2191 fmt += sprintf(fmt, ".%d", precision);
2192 if (longflag)
2193 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002194 else if (longlongflag) {
2195 /* longlongflag should only ever be nonzero on machines with
2196 HAVE_LONG_LONG defined */
2197#ifdef HAVE_LONG_LONG
2198 char *f = PY_FORMAT_LONG_LONG;
2199 while (*f)
2200 *fmt++ = *f++;
2201#else
2202 /* we shouldn't ever get here */
2203 assert(0);
2204 *fmt++ = 'l';
2205#endif
2206 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002207 else if (size_tflag) {
2208 char *f = PY_FORMAT_SIZE_T;
2209 while (*f)
2210 *fmt++ = *f++;
2211 }
2212 *fmt++ = c;
2213 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002214}
2215
Victor Stinner96865452011-03-01 23:44:09 +00002216/* helper for PyUnicode_FromFormatV() */
2217
2218static const char*
2219parse_format_flags(const char *f,
2220 int *p_width, int *p_precision,
2221 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2222{
2223 int width, precision, longflag, longlongflag, size_tflag;
2224
2225 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2226 f++;
2227 width = 0;
2228 while (Py_ISDIGIT((unsigned)*f))
2229 width = (width*10) + *f++ - '0';
2230 precision = 0;
2231 if (*f == '.') {
2232 f++;
2233 while (Py_ISDIGIT((unsigned)*f))
2234 precision = (precision*10) + *f++ - '0';
2235 if (*f == '%') {
2236 /* "%.3%s" => f points to "3" */
2237 f--;
2238 }
2239 }
2240 if (*f == '\0') {
2241 /* bogus format "%.1" => go backward, f points to "1" */
2242 f--;
2243 }
2244 if (p_width != NULL)
2245 *p_width = width;
2246 if (p_precision != NULL)
2247 *p_precision = precision;
2248
2249 /* Handle %ld, %lu, %lld and %llu. */
2250 longflag = 0;
2251 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002252 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002253
2254 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002255 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002256 longflag = 1;
2257 ++f;
2258 }
2259#ifdef HAVE_LONG_LONG
2260 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002261 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002262 longlongflag = 1;
2263 f += 2;
2264 }
2265#endif
2266 }
2267 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002268 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002269 size_tflag = 1;
2270 ++f;
2271 }
2272 if (p_longflag != NULL)
2273 *p_longflag = longflag;
2274 if (p_longlongflag != NULL)
2275 *p_longlongflag = longlongflag;
2276 if (p_size_tflag != NULL)
2277 *p_size_tflag = size_tflag;
2278 return f;
2279}
2280
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002281/* maximum number of characters required for output of %ld. 21 characters
2282 allows for 64-bit integers (in decimal) and an optional sign. */
2283#define MAX_LONG_CHARS 21
2284/* maximum number of characters required for output of %lld.
2285 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2286 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2287#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2288
Walter Dörwaldd2034312007-05-18 16:29:38 +00002289PyObject *
2290PyUnicode_FromFormatV(const char *format, va_list vargs)
2291{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002292 va_list count;
2293 Py_ssize_t callcount = 0;
2294 PyObject **callresults = NULL;
2295 PyObject **callresult = NULL;
2296 Py_ssize_t n = 0;
2297 int width = 0;
2298 int precision = 0;
2299 int zeropad;
2300 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002301 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002302 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002303 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002304 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2305 Py_UCS4 argmaxchar;
2306 Py_ssize_t numbersize = 0;
2307 char *numberresults = NULL;
2308 char *numberresult = NULL;
2309 Py_ssize_t i;
2310 int kind;
2311 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002312
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002313 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002314 /* step 1: count the number of %S/%R/%A/%s format specifications
2315 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2316 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002317 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002318 * also estimate a upper bound for all the number formats in the string,
2319 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002320 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002321 for (f = format; *f; f++) {
2322 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002323 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002324 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2325 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2326 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2327 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002328
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002329 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002330#ifdef HAVE_LONG_LONG
2331 if (longlongflag) {
2332 if (width < MAX_LONG_LONG_CHARS)
2333 width = MAX_LONG_LONG_CHARS;
2334 }
2335 else
2336#endif
2337 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2338 including sign. Decimal takes the most space. This
2339 isn't enough for octal. If a width is specified we
2340 need more (which we allocate later). */
2341 if (width < MAX_LONG_CHARS)
2342 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002343
2344 /* account for the size + '\0' to separate numbers
2345 inside of the numberresults buffer */
2346 numbersize += (width + 1);
2347 }
2348 }
2349 else if ((unsigned char)*f > 127) {
2350 PyErr_Format(PyExc_ValueError,
2351 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2352 "string, got a non-ASCII byte: 0x%02x",
2353 (unsigned char)*f);
2354 return NULL;
2355 }
2356 }
2357 /* step 2: allocate memory for the results of
2358 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2359 if (callcount) {
2360 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2361 if (!callresults) {
2362 PyErr_NoMemory();
2363 return NULL;
2364 }
2365 callresult = callresults;
2366 }
2367 /* step 2.5: allocate memory for the results of formating numbers */
2368 if (numbersize) {
2369 numberresults = PyObject_Malloc(numbersize);
2370 if (!numberresults) {
2371 PyErr_NoMemory();
2372 goto fail;
2373 }
2374 numberresult = numberresults;
2375 }
2376
2377 /* step 3: format numbers and figure out how large a buffer we need */
2378 for (f = format; *f; f++) {
2379 if (*f == '%') {
2380 const char* p;
2381 int longflag;
2382 int longlongflag;
2383 int size_tflag;
2384 int numprinted;
2385
2386 p = f;
2387 zeropad = (f[1] == '0');
2388 f = parse_format_flags(f, &width, &precision,
2389 &longflag, &longlongflag, &size_tflag);
2390 switch (*f) {
2391 case 'c':
2392 {
2393 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002394 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002395 n++;
2396 break;
2397 }
2398 case '%':
2399 n++;
2400 break;
2401 case 'i':
2402 case 'd':
2403 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2404 width, precision, *f);
2405 if (longflag)
2406 numprinted = sprintf(numberresult, fmt,
2407 va_arg(count, long));
2408#ifdef HAVE_LONG_LONG
2409 else if (longlongflag)
2410 numprinted = sprintf(numberresult, fmt,
2411 va_arg(count, PY_LONG_LONG));
2412#endif
2413 else if (size_tflag)
2414 numprinted = sprintf(numberresult, fmt,
2415 va_arg(count, Py_ssize_t));
2416 else
2417 numprinted = sprintf(numberresult, fmt,
2418 va_arg(count, int));
2419 n += numprinted;
2420 /* advance by +1 to skip over the '\0' */
2421 numberresult += (numprinted + 1);
2422 assert(*(numberresult - 1) == '\0');
2423 assert(*(numberresult - 2) != '\0');
2424 assert(numprinted >= 0);
2425 assert(numberresult <= numberresults + numbersize);
2426 break;
2427 case 'u':
2428 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2429 width, precision, 'u');
2430 if (longflag)
2431 numprinted = sprintf(numberresult, fmt,
2432 va_arg(count, unsigned long));
2433#ifdef HAVE_LONG_LONG
2434 else if (longlongflag)
2435 numprinted = sprintf(numberresult, fmt,
2436 va_arg(count, unsigned PY_LONG_LONG));
2437#endif
2438 else if (size_tflag)
2439 numprinted = sprintf(numberresult, fmt,
2440 va_arg(count, size_t));
2441 else
2442 numprinted = sprintf(numberresult, fmt,
2443 va_arg(count, unsigned int));
2444 n += numprinted;
2445 numberresult += (numprinted + 1);
2446 assert(*(numberresult - 1) == '\0');
2447 assert(*(numberresult - 2) != '\0');
2448 assert(numprinted >= 0);
2449 assert(numberresult <= numberresults + numbersize);
2450 break;
2451 case 'x':
2452 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2453 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2454 n += numprinted;
2455 numberresult += (numprinted + 1);
2456 assert(*(numberresult - 1) == '\0');
2457 assert(*(numberresult - 2) != '\0');
2458 assert(numprinted >= 0);
2459 assert(numberresult <= numberresults + numbersize);
2460 break;
2461 case 'p':
2462 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2463 /* %p is ill-defined: ensure leading 0x. */
2464 if (numberresult[1] == 'X')
2465 numberresult[1] = 'x';
2466 else if (numberresult[1] != 'x') {
2467 memmove(numberresult + 2, numberresult,
2468 strlen(numberresult) + 1);
2469 numberresult[0] = '0';
2470 numberresult[1] = 'x';
2471 numprinted += 2;
2472 }
2473 n += numprinted;
2474 numberresult += (numprinted + 1);
2475 assert(*(numberresult - 1) == '\0');
2476 assert(*(numberresult - 2) != '\0');
2477 assert(numprinted >= 0);
2478 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002479 break;
2480 case 's':
2481 {
2482 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002483 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002484 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002485 if (!str)
2486 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 /* since PyUnicode_DecodeUTF8 returns already flexible
2488 unicode objects, there is no need to call ready on them */
2489 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002490 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002491 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002492 /* Remember the str and switch to the next slot */
2493 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002494 break;
2495 }
2496 case 'U':
2497 {
2498 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002499 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002500 if (PyUnicode_READY(obj) == -1)
2501 goto fail;
2502 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002503 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002504 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002505 break;
2506 }
2507 case 'V':
2508 {
2509 PyObject *obj = va_arg(count, PyObject *);
2510 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002511 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002512 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002513 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002514 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002515 if (PyUnicode_READY(obj) == -1)
2516 goto fail;
2517 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002518 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002519 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002520 *callresult++ = NULL;
2521 }
2522 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002523 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002524 if (!str_obj)
2525 goto fail;
Benjamin Petersonbac79492012-01-14 13:34:47 -05002526 if (PyUnicode_READY(str_obj) == -1) {
Victor Stinnere1335c72011-10-04 20:53:03 +02002527 Py_DECREF(str_obj);
2528 goto fail;
2529 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002530 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002531 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002532 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002533 *callresult++ = str_obj;
2534 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002535 break;
2536 }
2537 case 'S':
2538 {
2539 PyObject *obj = va_arg(count, PyObject *);
2540 PyObject *str;
2541 assert(obj);
2542 str = PyObject_Str(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002543 if (!str)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002544 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002545 if (PyUnicode_READY(str) == -1) {
2546 Py_DECREF(str);
2547 goto fail;
2548 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002549 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002550 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002551 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002552 /* Remember the str and switch to the next slot */
2553 *callresult++ = str;
2554 break;
2555 }
2556 case 'R':
2557 {
2558 PyObject *obj = va_arg(count, PyObject *);
2559 PyObject *repr;
2560 assert(obj);
2561 repr = PyObject_Repr(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002562 if (!repr)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002563 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002564 if (PyUnicode_READY(repr) == -1) {
2565 Py_DECREF(repr);
2566 goto fail;
2567 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002568 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002569 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002570 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002571 /* Remember the repr and switch to the next slot */
2572 *callresult++ = repr;
2573 break;
2574 }
2575 case 'A':
2576 {
2577 PyObject *obj = va_arg(count, PyObject *);
2578 PyObject *ascii;
2579 assert(obj);
2580 ascii = PyObject_ASCII(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002581 if (!ascii)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002582 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002583 if (PyUnicode_READY(ascii) == -1) {
2584 Py_DECREF(ascii);
2585 goto fail;
2586 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002587 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002588 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002589 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002590 /* Remember the repr and switch to the next slot */
2591 *callresult++ = ascii;
2592 break;
2593 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002594 default:
2595 /* if we stumble upon an unknown
2596 formatting code, copy the rest of
2597 the format string to the output
2598 string. (we cannot just skip the
2599 code, since there's no way to know
2600 what's in the argument list) */
2601 n += strlen(p);
2602 goto expand;
2603 }
2604 } else
2605 n++;
2606 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002607 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002608 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002609 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002610 we don't have to resize the string.
2611 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002612 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002613 if (!string)
2614 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002615 kind = PyUnicode_KIND(string);
2616 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002617 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002618 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002619
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002620 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002621 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002622 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002623
2624 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002625 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2626 /* checking for == because the last argument could be a empty
2627 string, which causes i to point to end, the assert at the end of
2628 the loop */
2629 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002630
Benjamin Peterson14339b62009-01-31 16:36:08 +00002631 switch (*f) {
2632 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002633 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002634 const int ordinal = va_arg(vargs, int);
2635 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002636 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002637 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002638 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002639 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002640 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002641 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002642 case 'p':
Victor Stinnerc5166102012-02-22 13:55:02 +01002643 {
2644 Py_ssize_t written;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002645 /* unused, since we already have the result */
2646 if (*f == 'p')
2647 (void) va_arg(vargs, void *);
2648 else
2649 (void) va_arg(vargs, int);
2650 /* extract the result from numberresults and append. */
Victor Stinnerc5166102012-02-22 13:55:02 +01002651 written = unicode_write_cstr(string, i, numberresult);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002652 /* skip over the separating '\0' */
Victor Stinnerc5166102012-02-22 13:55:02 +01002653 i += written;
2654 numberresult += written;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002655 assert(*numberresult == '\0');
2656 numberresult++;
2657 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002658 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002659 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002660 case 's':
2661 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002662 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002663 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002664 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002665 size = PyUnicode_GET_LENGTH(*callresult);
2666 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002667 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002668 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002669 /* We're done with the unicode()/repr() => forget it */
2670 Py_DECREF(*callresult);
2671 /* switch to next unicode()/repr() result */
2672 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002673 break;
2674 }
2675 case 'U':
2676 {
2677 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002678 Py_ssize_t size;
2679 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2680 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002681 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002682 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002683 break;
2684 }
2685 case 'V':
2686 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002687 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002688 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002689 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002690 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002691 size = PyUnicode_GET_LENGTH(obj);
2692 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002693 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002694 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002695 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002696 size = PyUnicode_GET_LENGTH(*callresult);
2697 assert(PyUnicode_KIND(*callresult) <=
2698 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002699 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002700 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002701 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002702 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002703 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002704 break;
2705 }
2706 case 'S':
2707 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002708 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002709 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002710 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002711 /* unused, since we already have the result */
2712 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002713 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002714 copy_characters(string, i, *callresult, 0, size);
2715 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002716 /* We're done with the unicode()/repr() => forget it */
2717 Py_DECREF(*callresult);
2718 /* switch to next unicode()/repr() result */
2719 ++callresult;
2720 break;
2721 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002722 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002723 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002724 break;
2725 default:
Victor Stinnerc5166102012-02-22 13:55:02 +01002726 i += unicode_write_cstr(string, i, p);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002727 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002728 goto end;
2729 }
Victor Stinner1205f272010-09-11 00:54:47 +00002730 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002731 else {
2732 assert(i < PyUnicode_GET_LENGTH(string));
2733 PyUnicode_WRITE(kind, data, i++, *f);
2734 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002735 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002736 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002737
Benjamin Peterson29060642009-01-31 22:14:21 +00002738 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002739 if (callresults)
2740 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002741 if (numberresults)
2742 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002743 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002744 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002745 if (callresults) {
2746 PyObject **callresult2 = callresults;
2747 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002748 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002749 ++callresult2;
2750 }
2751 PyObject_Free(callresults);
2752 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002753 if (numberresults)
2754 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002755 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002756}
2757
Walter Dörwaldd2034312007-05-18 16:29:38 +00002758PyObject *
2759PyUnicode_FromFormat(const char *format, ...)
2760{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002761 PyObject* ret;
2762 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002763
2764#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002765 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002766#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002767 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002768#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002769 ret = PyUnicode_FromFormatV(format, vargs);
2770 va_end(vargs);
2771 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002772}
2773
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002774#ifdef HAVE_WCHAR_H
2775
Victor Stinner5593d8a2010-10-02 11:11:27 +00002776/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2777 convert a Unicode object to a wide character string.
2778
Victor Stinnerd88d9832011-09-06 02:00:05 +02002779 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002780 character) required to convert the unicode object. Ignore size argument.
2781
Victor Stinnerd88d9832011-09-06 02:00:05 +02002782 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002783 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002784 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002785static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002786unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002787 wchar_t *w,
2788 Py_ssize_t size)
2789{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002790 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002791 const wchar_t *wstr;
2792
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002793 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002794 if (wstr == NULL)
2795 return -1;
2796
Victor Stinner5593d8a2010-10-02 11:11:27 +00002797 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002798 if (size > res)
2799 size = res + 1;
2800 else
2801 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002802 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002803 return res;
2804 }
2805 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002806 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002807}
2808
2809Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002810PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002811 wchar_t *w,
2812 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002813{
2814 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002815 PyErr_BadInternalCall();
2816 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002817 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002818 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002819}
2820
Victor Stinner137c34c2010-09-29 10:25:54 +00002821wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002822PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002823 Py_ssize_t *size)
2824{
2825 wchar_t* buffer;
2826 Py_ssize_t buflen;
2827
2828 if (unicode == NULL) {
2829 PyErr_BadInternalCall();
2830 return NULL;
2831 }
2832
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002833 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002834 if (buflen == -1)
2835 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002836 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002837 PyErr_NoMemory();
2838 return NULL;
2839 }
2840
Victor Stinner137c34c2010-09-29 10:25:54 +00002841 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2842 if (buffer == NULL) {
2843 PyErr_NoMemory();
2844 return NULL;
2845 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002846 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002847 if (buflen == -1)
2848 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002849 if (size != NULL)
2850 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002851 return buffer;
2852}
2853
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002854#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002855
Alexander Belopolsky40018472011-02-26 01:02:56 +00002856PyObject *
2857PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002858{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002859 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002860 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002861 PyErr_SetString(PyExc_ValueError,
2862 "chr() arg not in range(0x110000)");
2863 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002864 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002865
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002866 if (ordinal < 256)
2867 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002868
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002869 v = PyUnicode_New(1, ordinal);
2870 if (v == NULL)
2871 return NULL;
2872 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002873 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002874 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002875}
2876
Alexander Belopolsky40018472011-02-26 01:02:56 +00002877PyObject *
2878PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002879{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002880 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002881 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002882 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002883 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002884 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002885 Py_INCREF(obj);
2886 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002887 }
2888 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002889 /* For a Unicode subtype that's not a Unicode object,
2890 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002891 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002892 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002893 PyErr_Format(PyExc_TypeError,
2894 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002895 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002896 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002897}
2898
Alexander Belopolsky40018472011-02-26 01:02:56 +00002899PyObject *
2900PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002901 const char *encoding,
2902 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002903{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002904 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002905 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002906
Guido van Rossumd57fd912000-03-10 22:53:23 +00002907 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002908 PyErr_BadInternalCall();
2909 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002910 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002911
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002912 /* Decoding bytes objects is the most common case and should be fast */
2913 if (PyBytes_Check(obj)) {
2914 if (PyBytes_GET_SIZE(obj) == 0) {
2915 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002916 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002917 }
2918 else {
2919 v = PyUnicode_Decode(
2920 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2921 encoding, errors);
2922 }
2923 return v;
2924 }
2925
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002926 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002927 PyErr_SetString(PyExc_TypeError,
2928 "decoding str is not supported");
2929 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002930 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002931
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002932 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2933 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2934 PyErr_Format(PyExc_TypeError,
2935 "coercing to str: need bytes, bytearray "
2936 "or buffer-like object, %.80s found",
2937 Py_TYPE(obj)->tp_name);
2938 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002939 }
Tim Petersced69f82003-09-16 20:30:58 +00002940
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002941 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002942 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002943 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002944 }
Tim Petersced69f82003-09-16 20:30:58 +00002945 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002946 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002947
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002948 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002949 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002950}
2951
Victor Stinner600d3be2010-06-10 12:00:55 +00002952/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002953 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2954 1 on success. */
2955static int
2956normalize_encoding(const char *encoding,
2957 char *lower,
2958 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002959{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002960 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002961 char *l;
2962 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002963
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002964 if (encoding == NULL) {
2965 strcpy(lower, "utf-8");
2966 return 1;
2967 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002968 e = encoding;
2969 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002970 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002971 while (*e) {
2972 if (l == l_end)
2973 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002974 if (Py_ISUPPER(*e)) {
2975 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002976 }
2977 else if (*e == '_') {
2978 *l++ = '-';
2979 e++;
2980 }
2981 else {
2982 *l++ = *e++;
2983 }
2984 }
2985 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002986 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002987}
2988
Alexander Belopolsky40018472011-02-26 01:02:56 +00002989PyObject *
2990PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002991 Py_ssize_t size,
2992 const char *encoding,
2993 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002994{
2995 PyObject *buffer = NULL, *unicode;
2996 Py_buffer info;
2997 char lower[11]; /* Enough for any encoding shortcut */
2998
Fred Drakee4315f52000-05-09 19:53:39 +00002999 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003000 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003001 if ((strcmp(lower, "utf-8") == 0) ||
3002 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003003 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003004 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003005 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003006 (strcmp(lower, "iso-8859-1") == 0))
3007 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003008#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003009 else if (strcmp(lower, "mbcs") == 0)
3010 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003011#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003012 else if (strcmp(lower, "ascii") == 0)
3013 return PyUnicode_DecodeASCII(s, size, errors);
3014 else if (strcmp(lower, "utf-16") == 0)
3015 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3016 else if (strcmp(lower, "utf-32") == 0)
3017 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3018 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003019
3020 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003021 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003022 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003023 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003024 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003025 if (buffer == NULL)
3026 goto onError;
3027 unicode = PyCodec_Decode(buffer, encoding, errors);
3028 if (unicode == NULL)
3029 goto onError;
3030 if (!PyUnicode_Check(unicode)) {
3031 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003032 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003033 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003034 Py_DECREF(unicode);
3035 goto onError;
3036 }
3037 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003038 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003039
Benjamin Peterson29060642009-01-31 22:14:21 +00003040 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003041 Py_XDECREF(buffer);
3042 return NULL;
3043}
3044
Alexander Belopolsky40018472011-02-26 01:02:56 +00003045PyObject *
3046PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003047 const char *encoding,
3048 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003049{
3050 PyObject *v;
3051
3052 if (!PyUnicode_Check(unicode)) {
3053 PyErr_BadArgument();
3054 goto onError;
3055 }
3056
3057 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003058 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003059
3060 /* Decode via the codec registry */
3061 v = PyCodec_Decode(unicode, encoding, errors);
3062 if (v == NULL)
3063 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003064 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003065
Benjamin Peterson29060642009-01-31 22:14:21 +00003066 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003067 return NULL;
3068}
3069
Alexander Belopolsky40018472011-02-26 01:02:56 +00003070PyObject *
3071PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003072 const char *encoding,
3073 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003074{
3075 PyObject *v;
3076
3077 if (!PyUnicode_Check(unicode)) {
3078 PyErr_BadArgument();
3079 goto onError;
3080 }
3081
3082 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003083 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003084
3085 /* Decode via the codec registry */
3086 v = PyCodec_Decode(unicode, encoding, errors);
3087 if (v == NULL)
3088 goto onError;
3089 if (!PyUnicode_Check(v)) {
3090 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003091 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003092 Py_TYPE(v)->tp_name);
3093 Py_DECREF(v);
3094 goto onError;
3095 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003096 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003097
Benjamin Peterson29060642009-01-31 22:14:21 +00003098 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003099 return NULL;
3100}
3101
Alexander Belopolsky40018472011-02-26 01:02:56 +00003102PyObject *
3103PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003104 Py_ssize_t size,
3105 const char *encoding,
3106 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003107{
3108 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003109
Guido van Rossumd57fd912000-03-10 22:53:23 +00003110 unicode = PyUnicode_FromUnicode(s, size);
3111 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003112 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003113 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3114 Py_DECREF(unicode);
3115 return v;
3116}
3117
Alexander Belopolsky40018472011-02-26 01:02:56 +00003118PyObject *
3119PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003120 const char *encoding,
3121 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003122{
3123 PyObject *v;
3124
3125 if (!PyUnicode_Check(unicode)) {
3126 PyErr_BadArgument();
3127 goto onError;
3128 }
3129
3130 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003131 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003132
3133 /* Encode via the codec registry */
3134 v = PyCodec_Encode(unicode, encoding, errors);
3135 if (v == NULL)
3136 goto onError;
3137 return v;
3138
Benjamin Peterson29060642009-01-31 22:14:21 +00003139 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003140 return NULL;
3141}
3142
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003143static size_t
3144wcstombs_errorpos(const wchar_t *wstr)
3145{
3146 size_t len;
3147#if SIZEOF_WCHAR_T == 2
3148 wchar_t buf[3];
3149#else
3150 wchar_t buf[2];
3151#endif
3152 char outbuf[MB_LEN_MAX];
3153 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003154
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003155#if SIZEOF_WCHAR_T == 2
3156 buf[2] = 0;
3157#else
3158 buf[1] = 0;
3159#endif
3160 start = wstr;
3161 while (*wstr != L'\0')
3162 {
3163 previous = wstr;
3164#if SIZEOF_WCHAR_T == 2
3165 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3166 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3167 {
3168 buf[0] = wstr[0];
3169 buf[1] = wstr[1];
3170 wstr += 2;
3171 }
3172 else {
3173 buf[0] = *wstr;
3174 buf[1] = 0;
3175 wstr++;
3176 }
3177#else
3178 buf[0] = *wstr;
3179 wstr++;
3180#endif
3181 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003182 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003183 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003184 }
3185
3186 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003187 return 0;
3188}
3189
Victor Stinner1b579672011-12-17 05:47:23 +01003190static int
3191locale_error_handler(const char *errors, int *surrogateescape)
3192{
3193 if (errors == NULL) {
3194 *surrogateescape = 0;
3195 return 0;
3196 }
3197
3198 if (strcmp(errors, "strict") == 0) {
3199 *surrogateescape = 0;
3200 return 0;
3201 }
3202 if (strcmp(errors, "surrogateescape") == 0) {
3203 *surrogateescape = 1;
3204 return 0;
3205 }
3206 PyErr_Format(PyExc_ValueError,
3207 "only 'strict' and 'surrogateescape' error handlers "
3208 "are supported, not '%s'",
3209 errors);
3210 return -1;
3211}
3212
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003213PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003214PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003215{
3216 Py_ssize_t wlen, wlen2;
3217 wchar_t *wstr;
3218 PyObject *bytes = NULL;
3219 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003220 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003221 PyObject *exc;
3222 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003223 int surrogateescape;
3224
3225 if (locale_error_handler(errors, &surrogateescape) < 0)
3226 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003227
3228 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3229 if (wstr == NULL)
3230 return NULL;
3231
3232 wlen2 = wcslen(wstr);
3233 if (wlen2 != wlen) {
3234 PyMem_Free(wstr);
3235 PyErr_SetString(PyExc_TypeError, "embedded null character");
3236 return NULL;
3237 }
3238
3239 if (surrogateescape) {
3240 /* locale encoding with surrogateescape */
3241 char *str;
3242
3243 str = _Py_wchar2char(wstr, &error_pos);
3244 if (str == NULL) {
3245 if (error_pos == (size_t)-1) {
3246 PyErr_NoMemory();
3247 PyMem_Free(wstr);
3248 return NULL;
3249 }
3250 else {
3251 goto encode_error;
3252 }
3253 }
3254 PyMem_Free(wstr);
3255
3256 bytes = PyBytes_FromString(str);
3257 PyMem_Free(str);
3258 }
3259 else {
3260 size_t len, len2;
3261
3262 len = wcstombs(NULL, wstr, 0);
3263 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003264 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003265 goto encode_error;
3266 }
3267
3268 bytes = PyBytes_FromStringAndSize(NULL, len);
3269 if (bytes == NULL) {
3270 PyMem_Free(wstr);
3271 return NULL;
3272 }
3273
3274 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3275 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003276 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003277 goto encode_error;
3278 }
3279 PyMem_Free(wstr);
3280 }
3281 return bytes;
3282
3283encode_error:
3284 errmsg = strerror(errno);
3285 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003286
3287 if (error_pos == (size_t)-1)
3288 error_pos = wcstombs_errorpos(wstr);
3289
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003290 PyMem_Free(wstr);
3291 Py_XDECREF(bytes);
3292
Victor Stinner2f197072011-12-17 07:08:30 +01003293 if (errmsg != NULL) {
3294 size_t errlen;
3295 wstr = _Py_char2wchar(errmsg, &errlen);
3296 if (wstr != NULL) {
3297 reason = PyUnicode_FromWideChar(wstr, errlen);
3298 PyMem_Free(wstr);
3299 } else
3300 errmsg = NULL;
3301 }
3302 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003303 reason = PyUnicode_FromString(
3304 "wcstombs() encountered an unencodable "
3305 "wide character");
3306 if (reason == NULL)
3307 return NULL;
3308
3309 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3310 "locale", unicode,
3311 (Py_ssize_t)error_pos,
3312 (Py_ssize_t)(error_pos+1),
3313 reason);
3314 Py_DECREF(reason);
3315 if (exc != NULL) {
3316 PyCodec_StrictErrors(exc);
3317 Py_XDECREF(exc);
3318 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003319 return NULL;
3320}
3321
Victor Stinnerad158722010-10-27 00:25:46 +00003322PyObject *
3323PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003324{
Victor Stinner99b95382011-07-04 14:23:54 +02003325#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003326 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003327#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003328 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003329#else
Victor Stinner793b5312011-04-27 00:24:21 +02003330 PyInterpreterState *interp = PyThreadState_GET()->interp;
3331 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3332 cannot use it to encode and decode filenames before it is loaded. Load
3333 the Python codec requires to encode at least its own filename. Use the C
3334 version of the locale codec until the codec registry is initialized and
3335 the Python codec is loaded.
3336
3337 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3338 cannot only rely on it: check also interp->fscodec_initialized for
3339 subinterpreters. */
3340 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003341 return PyUnicode_AsEncodedString(unicode,
3342 Py_FileSystemDefaultEncoding,
3343 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003344 }
3345 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003346 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003347 }
Victor Stinnerad158722010-10-27 00:25:46 +00003348#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003349}
3350
Alexander Belopolsky40018472011-02-26 01:02:56 +00003351PyObject *
3352PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003353 const char *encoding,
3354 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003355{
3356 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003357 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003358
Guido van Rossumd57fd912000-03-10 22:53:23 +00003359 if (!PyUnicode_Check(unicode)) {
3360 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003361 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003362 }
Fred Drakee4315f52000-05-09 19:53:39 +00003363
Fred Drakee4315f52000-05-09 19:53:39 +00003364 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003365 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003366 if ((strcmp(lower, "utf-8") == 0) ||
3367 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003368 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003369 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003370 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003371 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003372 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003373 }
Victor Stinner37296e82010-06-10 13:36:23 +00003374 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003375 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003376 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003377 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003378#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003379 else if (strcmp(lower, "mbcs") == 0)
3380 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003381#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003382 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003383 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003384 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003385
3386 /* Encode via the codec registry */
3387 v = PyCodec_Encode(unicode, encoding, errors);
3388 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003389 return NULL;
3390
3391 /* The normal path */
3392 if (PyBytes_Check(v))
3393 return v;
3394
3395 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003396 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003397 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003398 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003399
3400 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3401 "encoder %s returned bytearray instead of bytes",
3402 encoding);
3403 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003404 Py_DECREF(v);
3405 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003406 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003407
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003408 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3409 Py_DECREF(v);
3410 return b;
3411 }
3412
3413 PyErr_Format(PyExc_TypeError,
3414 "encoder did not return a bytes object (type=%.400s)",
3415 Py_TYPE(v)->tp_name);
3416 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003417 return NULL;
3418}
3419
Alexander Belopolsky40018472011-02-26 01:02:56 +00003420PyObject *
3421PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003422 const char *encoding,
3423 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003424{
3425 PyObject *v;
3426
3427 if (!PyUnicode_Check(unicode)) {
3428 PyErr_BadArgument();
3429 goto onError;
3430 }
3431
3432 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003433 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003434
3435 /* Encode via the codec registry */
3436 v = PyCodec_Encode(unicode, encoding, errors);
3437 if (v == NULL)
3438 goto onError;
3439 if (!PyUnicode_Check(v)) {
3440 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003441 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003442 Py_TYPE(v)->tp_name);
3443 Py_DECREF(v);
3444 goto onError;
3445 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003446 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003447
Benjamin Peterson29060642009-01-31 22:14:21 +00003448 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003449 return NULL;
3450}
3451
Victor Stinner2f197072011-12-17 07:08:30 +01003452static size_t
3453mbstowcs_errorpos(const char *str, size_t len)
3454{
3455#ifdef HAVE_MBRTOWC
3456 const char *start = str;
3457 mbstate_t mbs;
3458 size_t converted;
3459 wchar_t ch;
3460
3461 memset(&mbs, 0, sizeof mbs);
3462 while (len)
3463 {
3464 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3465 if (converted == 0)
3466 /* Reached end of string */
3467 break;
3468 if (converted == (size_t)-1 || converted == (size_t)-2) {
3469 /* Conversion error or incomplete character */
3470 return str - start;
3471 }
3472 else {
3473 str += converted;
3474 len -= converted;
3475 }
3476 }
3477 /* failed to find the undecodable byte sequence */
3478 return 0;
3479#endif
3480 return 0;
3481}
3482
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003483PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003484PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003485 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003486{
3487 wchar_t smallbuf[256];
3488 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3489 wchar_t *wstr;
3490 size_t wlen, wlen2;
3491 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003492 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003493 size_t error_pos;
3494 char *errmsg;
3495 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003496
3497 if (locale_error_handler(errors, &surrogateescape) < 0)
3498 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003499
3500 if (str[len] != '\0' || len != strlen(str)) {
3501 PyErr_SetString(PyExc_TypeError, "embedded null character");
3502 return NULL;
3503 }
3504
3505 if (surrogateescape)
3506 {
3507 wstr = _Py_char2wchar(str, &wlen);
3508 if (wstr == NULL) {
3509 if (wlen == (size_t)-1)
3510 PyErr_NoMemory();
3511 else
3512 PyErr_SetFromErrno(PyExc_OSError);
3513 return NULL;
3514 }
3515
3516 unicode = PyUnicode_FromWideChar(wstr, wlen);
3517 PyMem_Free(wstr);
3518 }
3519 else {
3520#ifndef HAVE_BROKEN_MBSTOWCS
3521 wlen = mbstowcs(NULL, str, 0);
3522#else
3523 wlen = len;
3524#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003525 if (wlen == (size_t)-1)
3526 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003527 if (wlen+1 <= smallbuf_len) {
3528 wstr = smallbuf;
3529 }
3530 else {
3531 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3532 return PyErr_NoMemory();
3533
3534 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3535 if (!wstr)
3536 return PyErr_NoMemory();
3537 }
3538
3539 /* This shouldn't fail now */
3540 wlen2 = mbstowcs(wstr, str, wlen+1);
3541 if (wlen2 == (size_t)-1) {
3542 if (wstr != smallbuf)
3543 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003544 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003545 }
3546#ifdef HAVE_BROKEN_MBSTOWCS
3547 assert(wlen2 == wlen);
3548#endif
3549 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3550 if (wstr != smallbuf)
3551 PyMem_Free(wstr);
3552 }
3553 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003554
3555decode_error:
3556 errmsg = strerror(errno);
3557 assert(errmsg != NULL);
3558
3559 error_pos = mbstowcs_errorpos(str, len);
3560 if (errmsg != NULL) {
3561 size_t errlen;
3562 wstr = _Py_char2wchar(errmsg, &errlen);
3563 if (wstr != NULL) {
3564 reason = PyUnicode_FromWideChar(wstr, errlen);
3565 PyMem_Free(wstr);
3566 } else
3567 errmsg = NULL;
3568 }
3569 if (errmsg == NULL)
3570 reason = PyUnicode_FromString(
3571 "mbstowcs() encountered an invalid multibyte sequence");
3572 if (reason == NULL)
3573 return NULL;
3574
3575 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3576 "locale", str, len,
3577 (Py_ssize_t)error_pos,
3578 (Py_ssize_t)(error_pos+1),
3579 reason);
3580 Py_DECREF(reason);
3581 if (exc != NULL) {
3582 PyCodec_StrictErrors(exc);
3583 Py_XDECREF(exc);
3584 }
3585 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003586}
3587
3588PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003589PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003590{
3591 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003592 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003593}
3594
3595
3596PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003597PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003598 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003599 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3600}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003601
Christian Heimes5894ba72007-11-04 11:43:14 +00003602PyObject*
3603PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3604{
Victor Stinner99b95382011-07-04 14:23:54 +02003605#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003606 return PyUnicode_DecodeMBCS(s, size, NULL);
3607#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003608 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003609#else
Victor Stinner793b5312011-04-27 00:24:21 +02003610 PyInterpreterState *interp = PyThreadState_GET()->interp;
3611 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3612 cannot use it to encode and decode filenames before it is loaded. Load
3613 the Python codec requires to encode at least its own filename. Use the C
3614 version of the locale codec until the codec registry is initialized and
3615 the Python codec is loaded.
3616
3617 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3618 cannot only rely on it: check also interp->fscodec_initialized for
3619 subinterpreters. */
3620 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003621 return PyUnicode_Decode(s, size,
3622 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003623 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003624 }
3625 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003626 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003627 }
Victor Stinnerad158722010-10-27 00:25:46 +00003628#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003629}
3630
Martin v. Löwis011e8422009-05-05 04:43:17 +00003631
3632int
Antoine Pitrou13348842012-01-29 18:36:34 +01003633_PyUnicode_HasNULChars(PyObject* s)
3634{
3635 static PyObject *nul = NULL;
3636
3637 if (nul == NULL)
3638 nul = PyUnicode_FromStringAndSize("\0", 1);
3639 if (nul == NULL)
3640 return -1;
3641 return PyUnicode_Contains(s, nul);
3642}
3643
3644
3645int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003646PyUnicode_FSConverter(PyObject* arg, void* addr)
3647{
3648 PyObject *output = NULL;
3649 Py_ssize_t size;
3650 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003651 if (arg == NULL) {
3652 Py_DECREF(*(PyObject**)addr);
3653 return 1;
3654 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003655 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003656 output = arg;
3657 Py_INCREF(output);
3658 }
3659 else {
3660 arg = PyUnicode_FromObject(arg);
3661 if (!arg)
3662 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003663 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003664 Py_DECREF(arg);
3665 if (!output)
3666 return 0;
3667 if (!PyBytes_Check(output)) {
3668 Py_DECREF(output);
3669 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3670 return 0;
3671 }
3672 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003673 size = PyBytes_GET_SIZE(output);
3674 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003675 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003676 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003677 Py_DECREF(output);
3678 return 0;
3679 }
3680 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003681 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003682}
3683
3684
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003685int
3686PyUnicode_FSDecoder(PyObject* arg, void* addr)
3687{
3688 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003689 if (arg == NULL) {
3690 Py_DECREF(*(PyObject**)addr);
3691 return 1;
3692 }
3693 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003694 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003695 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003696 output = arg;
3697 Py_INCREF(output);
3698 }
3699 else {
3700 arg = PyBytes_FromObject(arg);
3701 if (!arg)
3702 return 0;
3703 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3704 PyBytes_GET_SIZE(arg));
3705 Py_DECREF(arg);
3706 if (!output)
3707 return 0;
3708 if (!PyUnicode_Check(output)) {
3709 Py_DECREF(output);
3710 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3711 return 0;
3712 }
3713 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003714 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003715 Py_DECREF(output);
3716 return 0;
3717 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003718 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003719 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003720 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3721 Py_DECREF(output);
3722 return 0;
3723 }
3724 *(PyObject**)addr = output;
3725 return Py_CLEANUP_SUPPORTED;
3726}
3727
3728
Martin v. Löwis5b222132007-06-10 09:51:05 +00003729char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003730PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003731{
Christian Heimesf3863112007-11-22 07:46:41 +00003732 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003733
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003734 if (!PyUnicode_Check(unicode)) {
3735 PyErr_BadArgument();
3736 return NULL;
3737 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003738 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003739 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003740
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003741 if (PyUnicode_UTF8(unicode) == NULL) {
3742 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003743 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3744 if (bytes == NULL)
3745 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003746 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3747 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003748 Py_DECREF(bytes);
3749 return NULL;
3750 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003751 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3752 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3753 PyBytes_AS_STRING(bytes),
3754 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003755 Py_DECREF(bytes);
3756 }
3757
3758 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003759 *psize = PyUnicode_UTF8_LENGTH(unicode);
3760 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003761}
3762
3763char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003764PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003765{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003766 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3767}
3768
3769#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003770static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003771#endif
3772
3773
3774Py_UNICODE *
3775PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3776{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003777 const unsigned char *one_byte;
3778#if SIZEOF_WCHAR_T == 4
3779 const Py_UCS2 *two_bytes;
3780#else
3781 const Py_UCS4 *four_bytes;
3782 const Py_UCS4 *ucs4_end;
3783 Py_ssize_t num_surrogates;
3784#endif
3785 wchar_t *w;
3786 wchar_t *wchar_end;
3787
3788 if (!PyUnicode_Check(unicode)) {
3789 PyErr_BadArgument();
3790 return NULL;
3791 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003792 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003793 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003794 assert(_PyUnicode_KIND(unicode) != 0);
3795 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003796
3797#ifdef Py_DEBUG
3798 ++unicode_as_unicode_calls;
3799#endif
3800
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003801 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003802#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003803 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3804 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003805 num_surrogates = 0;
3806
3807 for (; four_bytes < ucs4_end; ++four_bytes) {
3808 if (*four_bytes > 0xFFFF)
3809 ++num_surrogates;
3810 }
3811
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003812 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3813 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3814 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003815 PyErr_NoMemory();
3816 return NULL;
3817 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003818 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003819
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003820 w = _PyUnicode_WSTR(unicode);
3821 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3822 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003823 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3824 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003825 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003826 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003827 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3828 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003829 }
3830 else
3831 *w = *four_bytes;
3832
3833 if (w > wchar_end) {
3834 assert(0 && "Miscalculated string end");
3835 }
3836 }
3837 *w = 0;
3838#else
3839 /* sizeof(wchar_t) == 4 */
3840 Py_FatalError("Impossible unicode object state, wstr and str "
3841 "should share memory already.");
3842 return NULL;
3843#endif
3844 }
3845 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003846 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3847 (_PyUnicode_LENGTH(unicode) + 1));
3848 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003849 PyErr_NoMemory();
3850 return NULL;
3851 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003852 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3853 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3854 w = _PyUnicode_WSTR(unicode);
3855 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003856
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003857 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3858 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003859 for (; w < wchar_end; ++one_byte, ++w)
3860 *w = *one_byte;
3861 /* null-terminate the wstr */
3862 *w = 0;
3863 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003864 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003865#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003866 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003867 for (; w < wchar_end; ++two_bytes, ++w)
3868 *w = *two_bytes;
3869 /* null-terminate the wstr */
3870 *w = 0;
3871#else
3872 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003873 PyObject_FREE(_PyUnicode_WSTR(unicode));
3874 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003875 Py_FatalError("Impossible unicode object state, wstr "
3876 "and str should share memory already.");
3877 return NULL;
3878#endif
3879 }
3880 else {
3881 assert(0 && "This should never happen.");
3882 }
3883 }
3884 }
3885 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003886 *size = PyUnicode_WSTR_LENGTH(unicode);
3887 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003888}
3889
Alexander Belopolsky40018472011-02-26 01:02:56 +00003890Py_UNICODE *
3891PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003892{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003893 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003894}
3895
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003896
Alexander Belopolsky40018472011-02-26 01:02:56 +00003897Py_ssize_t
3898PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003899{
3900 if (!PyUnicode_Check(unicode)) {
3901 PyErr_BadArgument();
3902 goto onError;
3903 }
3904 return PyUnicode_GET_SIZE(unicode);
3905
Benjamin Peterson29060642009-01-31 22:14:21 +00003906 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003907 return -1;
3908}
3909
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003910Py_ssize_t
3911PyUnicode_GetLength(PyObject *unicode)
3912{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003913 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003914 PyErr_BadArgument();
3915 return -1;
3916 }
3917
3918 return PyUnicode_GET_LENGTH(unicode);
3919}
3920
3921Py_UCS4
3922PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3923{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003924 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3925 PyErr_BadArgument();
3926 return (Py_UCS4)-1;
3927 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003928 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003929 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003930 return (Py_UCS4)-1;
3931 }
3932 return PyUnicode_READ_CHAR(unicode, index);
3933}
3934
3935int
3936PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3937{
3938 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003939 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003940 return -1;
3941 }
Victor Stinner488fa492011-12-12 00:01:39 +01003942 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003943 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003944 PyErr_SetString(PyExc_IndexError, "string index out of range");
3945 return -1;
3946 }
Victor Stinner488fa492011-12-12 00:01:39 +01003947 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003948 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003949 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3950 PyErr_SetString(PyExc_ValueError, "character out of range");
3951 return -1;
3952 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003953 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3954 index, ch);
3955 return 0;
3956}
3957
Alexander Belopolsky40018472011-02-26 01:02:56 +00003958const char *
3959PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003960{
Victor Stinner42cb4622010-09-01 19:39:01 +00003961 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003962}
3963
Victor Stinner554f3f02010-06-16 23:33:54 +00003964/* create or adjust a UnicodeDecodeError */
3965static void
3966make_decode_exception(PyObject **exceptionObject,
3967 const char *encoding,
3968 const char *input, Py_ssize_t length,
3969 Py_ssize_t startpos, Py_ssize_t endpos,
3970 const char *reason)
3971{
3972 if (*exceptionObject == NULL) {
3973 *exceptionObject = PyUnicodeDecodeError_Create(
3974 encoding, input, length, startpos, endpos, reason);
3975 }
3976 else {
3977 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3978 goto onError;
3979 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3980 goto onError;
3981 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3982 goto onError;
3983 }
3984 return;
3985
3986onError:
3987 Py_DECREF(*exceptionObject);
3988 *exceptionObject = NULL;
3989}
3990
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003991/* error handling callback helper:
3992 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003993 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003994 and adjust various state variables.
3995 return 0 on success, -1 on error
3996*/
3997
Alexander Belopolsky40018472011-02-26 01:02:56 +00003998static int
3999unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004000 const char *encoding, const char *reason,
4001 const char **input, const char **inend, Py_ssize_t *startinpos,
4002 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004003 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004004{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004005 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004006
4007 PyObject *restuple = NULL;
4008 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004009 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004010 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004011 Py_ssize_t requiredsize;
4012 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004013 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004014 int res = -1;
4015
Victor Stinner596a6c42011-11-09 00:02:18 +01004016 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4017 outsize = PyUnicode_GET_LENGTH(*output);
4018 else
4019 outsize = _PyUnicode_WSTR_LENGTH(*output);
4020
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004021 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004022 *errorHandler = PyCodec_LookupError(errors);
4023 if (*errorHandler == NULL)
4024 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004025 }
4026
Victor Stinner554f3f02010-06-16 23:33:54 +00004027 make_decode_exception(exceptionObject,
4028 encoding,
4029 *input, *inend - *input,
4030 *startinpos, *endinpos,
4031 reason);
4032 if (*exceptionObject == NULL)
4033 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004034
4035 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4036 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004037 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004038 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004039 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004040 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004041 }
4042 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004043 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004044 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004045 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004046
4047 /* Copy back the bytes variables, which might have been modified by the
4048 callback */
4049 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4050 if (!inputobj)
4051 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004052 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004053 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004054 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004055 *input = PyBytes_AS_STRING(inputobj);
4056 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004057 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004058 /* we can DECREF safely, as the exception has another reference,
4059 so the object won't go away. */
4060 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004061
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004062 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004063 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004064 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004065 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4066 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004067 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004068
Victor Stinner596a6c42011-11-09 00:02:18 +01004069 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4070 /* need more space? (at least enough for what we
4071 have+the replacement+the rest of the string (starting
4072 at the new input position), so we won't have to check space
4073 when there are no errors in the rest of the string) */
4074 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4075 requiredsize = *outpos + replen + insize-newpos;
4076 if (requiredsize > outsize) {
4077 if (requiredsize<2*outsize)
4078 requiredsize = 2*outsize;
4079 if (unicode_resize(output, requiredsize) < 0)
4080 goto onError;
4081 }
4082 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004083 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01004084 copy_characters(*output, *outpos, repunicode, 0, replen);
4085 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004086 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004087 else {
4088 wchar_t *repwstr;
4089 Py_ssize_t repwlen;
4090 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4091 if (repwstr == NULL)
4092 goto onError;
4093 /* need more space? (at least enough for what we
4094 have+the replacement+the rest of the string (starting
4095 at the new input position), so we won't have to check space
4096 when there are no errors in the rest of the string) */
4097 requiredsize = *outpos + repwlen + insize-newpos;
4098 if (requiredsize > outsize) {
4099 if (requiredsize < 2*outsize)
4100 requiredsize = 2*outsize;
4101 if (unicode_resize(output, requiredsize) < 0)
4102 goto onError;
4103 }
4104 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4105 *outpos += repwlen;
4106 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004107 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004108 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004109
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004110 /* we made it! */
4111 res = 0;
4112
Benjamin Peterson29060642009-01-31 22:14:21 +00004113 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004114 Py_XDECREF(restuple);
4115 return res;
4116}
4117
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004118/* --- UTF-7 Codec -------------------------------------------------------- */
4119
Antoine Pitrou244651a2009-05-04 18:56:13 +00004120/* See RFC2152 for details. We encode conservatively and decode liberally. */
4121
4122/* Three simple macros defining base-64. */
4123
4124/* Is c a base-64 character? */
4125
4126#define IS_BASE64(c) \
4127 (((c) >= 'A' && (c) <= 'Z') || \
4128 ((c) >= 'a' && (c) <= 'z') || \
4129 ((c) >= '0' && (c) <= '9') || \
4130 (c) == '+' || (c) == '/')
4131
4132/* given that c is a base-64 character, what is its base-64 value? */
4133
4134#define FROM_BASE64(c) \
4135 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4136 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4137 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4138 (c) == '+' ? 62 : 63)
4139
4140/* What is the base-64 character of the bottom 6 bits of n? */
4141
4142#define TO_BASE64(n) \
4143 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4144
4145/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4146 * decoded as itself. We are permissive on decoding; the only ASCII
4147 * byte not decoding to itself is the + which begins a base64
4148 * string. */
4149
4150#define DECODE_DIRECT(c) \
4151 ((c) <= 127 && (c) != '+')
4152
4153/* The UTF-7 encoder treats ASCII characters differently according to
4154 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4155 * the above). See RFC2152. This array identifies these different
4156 * sets:
4157 * 0 : "Set D"
4158 * alphanumeric and '(),-./:?
4159 * 1 : "Set O"
4160 * !"#$%&*;<=>@[]^_`{|}
4161 * 2 : "whitespace"
4162 * ht nl cr sp
4163 * 3 : special (must be base64 encoded)
4164 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4165 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004166
Tim Petersced69f82003-09-16 20:30:58 +00004167static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004168char utf7_category[128] = {
4169/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4170 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4171/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4172 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4173/* sp ! " # $ % & ' ( ) * + , - . / */
4174 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4175/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4176 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4177/* @ A B C D E F G H I J K L M N O */
4178 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4179/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4180 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4181/* ` a b c d e f g h i j k l m n o */
4182 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4183/* p q r s t u v w x y z { | } ~ del */
4184 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004185};
4186
Antoine Pitrou244651a2009-05-04 18:56:13 +00004187/* ENCODE_DIRECT: this character should be encoded as itself. The
4188 * answer depends on whether we are encoding set O as itself, and also
4189 * on whether we are encoding whitespace as itself. RFC2152 makes it
4190 * clear that the answers to these questions vary between
4191 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004192
Antoine Pitrou244651a2009-05-04 18:56:13 +00004193#define ENCODE_DIRECT(c, directO, directWS) \
4194 ((c) < 128 && (c) > 0 && \
4195 ((utf7_category[(c)] == 0) || \
4196 (directWS && (utf7_category[(c)] == 2)) || \
4197 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004198
Alexander Belopolsky40018472011-02-26 01:02:56 +00004199PyObject *
4200PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004201 Py_ssize_t size,
4202 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004203{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004204 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4205}
4206
Antoine Pitrou244651a2009-05-04 18:56:13 +00004207/* The decoder. The only state we preserve is our read position,
4208 * i.e. how many characters we have consumed. So if we end in the
4209 * middle of a shift sequence we have to back off the read position
4210 * and the output to the beginning of the sequence, otherwise we lose
4211 * all the shift state (seen bits, number of bits seen, high
4212 * surrogate). */
4213
Alexander Belopolsky40018472011-02-26 01:02:56 +00004214PyObject *
4215PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004216 Py_ssize_t size,
4217 const char *errors,
4218 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004219{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004220 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004221 Py_ssize_t startinpos;
4222 Py_ssize_t endinpos;
4223 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004224 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004225 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004226 const char *errmsg = "";
4227 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004228 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004229 unsigned int base64bits = 0;
4230 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004231 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004232 PyObject *errorHandler = NULL;
4233 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004234
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004235 /* Start off assuming it's all ASCII. Widen later as necessary. */
4236 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004237 if (!unicode)
4238 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004239 if (size == 0) {
4240 if (consumed)
4241 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004242 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004243 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004244
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004245 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004246 e = s + size;
4247
4248 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004249 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004250 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004251 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004252
Antoine Pitrou244651a2009-05-04 18:56:13 +00004253 if (inShift) { /* in a base-64 section */
4254 if (IS_BASE64(ch)) { /* consume a base-64 character */
4255 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4256 base64bits += 6;
4257 s++;
4258 if (base64bits >= 16) {
4259 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004260 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004261 base64bits -= 16;
4262 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4263 if (surrogate) {
4264 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004265 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4266 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004267 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4268 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004269 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004270 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004271 }
4272 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004273 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4274 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004275 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004276 }
4277 }
Victor Stinner551ac952011-11-29 22:58:13 +01004278 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004279 /* first surrogate */
4280 surrogate = outCh;
4281 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004282 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004283 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4284 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004285 }
4286 }
4287 }
4288 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004289 inShift = 0;
4290 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004291 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004292 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4293 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004294 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004295 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004296 if (base64bits > 0) { /* left-over bits */
4297 if (base64bits >= 6) {
4298 /* We've seen at least one base-64 character */
4299 errmsg = "partial character in shift sequence";
4300 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004301 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004302 else {
4303 /* Some bits remain; they should be zero */
4304 if (base64buffer != 0) {
4305 errmsg = "non-zero padding bits in shift sequence";
4306 goto utf7Error;
4307 }
4308 }
4309 }
4310 if (ch != '-') {
4311 /* '-' is absorbed; other terminating
4312 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004313 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4314 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004315 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004316 }
4317 }
4318 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004319 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004320 s++; /* consume '+' */
4321 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004322 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004323 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4324 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004325 }
4326 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004327 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004328 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004329 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004330 }
4331 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004332 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004333 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4334 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004335 s++;
4336 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004337 else {
4338 startinpos = s-starts;
4339 s++;
4340 errmsg = "unexpected special character";
4341 goto utf7Error;
4342 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004343 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004344utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004345 endinpos = s-starts;
4346 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004347 errors, &errorHandler,
4348 "utf7", errmsg,
4349 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004350 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004351 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004352 }
4353
Antoine Pitrou244651a2009-05-04 18:56:13 +00004354 /* end of string */
4355
4356 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4357 /* if we're in an inconsistent state, that's an error */
4358 if (surrogate ||
4359 (base64bits >= 6) ||
4360 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004361 endinpos = size;
4362 if (unicode_decode_call_errorhandler(
4363 errors, &errorHandler,
4364 "utf7", "unterminated shift sequence",
4365 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004366 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004367 goto onError;
4368 if (s < e)
4369 goto restart;
4370 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004371 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004372
4373 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004374 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004375 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004376 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004377 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004378 }
4379 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004380 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004381 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004382 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004383
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004384 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004385 goto onError;
4386
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004387 Py_XDECREF(errorHandler);
4388 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004389 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004390
Benjamin Peterson29060642009-01-31 22:14:21 +00004391 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004392 Py_XDECREF(errorHandler);
4393 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004394 Py_DECREF(unicode);
4395 return NULL;
4396}
4397
4398
Alexander Belopolsky40018472011-02-26 01:02:56 +00004399PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004400_PyUnicode_EncodeUTF7(PyObject *str,
4401 int base64SetO,
4402 int base64WhiteSpace,
4403 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004404{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004405 int kind;
4406 void *data;
4407 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004408 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004409 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004410 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004411 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004412 unsigned int base64bits = 0;
4413 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004414 char * out;
4415 char * start;
4416
Benjamin Petersonbac79492012-01-14 13:34:47 -05004417 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004418 return NULL;
4419 kind = PyUnicode_KIND(str);
4420 data = PyUnicode_DATA(str);
4421 len = PyUnicode_GET_LENGTH(str);
4422
4423 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004424 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004425
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004426 /* It might be possible to tighten this worst case */
4427 allocated = 8 * len;
4428 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004429 return PyErr_NoMemory();
4430
Antoine Pitrou244651a2009-05-04 18:56:13 +00004431 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004432 if (v == NULL)
4433 return NULL;
4434
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004435 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004436 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004437 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004438
Antoine Pitrou244651a2009-05-04 18:56:13 +00004439 if (inShift) {
4440 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4441 /* shifting out */
4442 if (base64bits) { /* output remaining bits */
4443 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4444 base64buffer = 0;
4445 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004446 }
4447 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004448 /* Characters not in the BASE64 set implicitly unshift the sequence
4449 so no '-' is required, except if the character is itself a '-' */
4450 if (IS_BASE64(ch) || ch == '-') {
4451 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004452 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004453 *out++ = (char) ch;
4454 }
4455 else {
4456 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004457 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004458 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004459 else { /* not in a shift sequence */
4460 if (ch == '+') {
4461 *out++ = '+';
4462 *out++ = '-';
4463 }
4464 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4465 *out++ = (char) ch;
4466 }
4467 else {
4468 *out++ = '+';
4469 inShift = 1;
4470 goto encode_char;
4471 }
4472 }
4473 continue;
4474encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004475 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004476 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004477
Antoine Pitrou244651a2009-05-04 18:56:13 +00004478 /* code first surrogate */
4479 base64bits += 16;
4480 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4481 while (base64bits >= 6) {
4482 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4483 base64bits -= 6;
4484 }
4485 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004486 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004487 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004488 base64bits += 16;
4489 base64buffer = (base64buffer << 16) | ch;
4490 while (base64bits >= 6) {
4491 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4492 base64bits -= 6;
4493 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004494 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004495 if (base64bits)
4496 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4497 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004498 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004499 if (_PyBytes_Resize(&v, out - start) < 0)
4500 return NULL;
4501 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004502}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004503PyObject *
4504PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4505 Py_ssize_t size,
4506 int base64SetO,
4507 int base64WhiteSpace,
4508 const char *errors)
4509{
4510 PyObject *result;
4511 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4512 if (tmp == NULL)
4513 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004514 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004515 base64WhiteSpace, errors);
4516 Py_DECREF(tmp);
4517 return result;
4518}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004519
Antoine Pitrou244651a2009-05-04 18:56:13 +00004520#undef IS_BASE64
4521#undef FROM_BASE64
4522#undef TO_BASE64
4523#undef DECODE_DIRECT
4524#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004525
Guido van Rossumd57fd912000-03-10 22:53:23 +00004526/* --- UTF-8 Codec -------------------------------------------------------- */
4527
Tim Petersced69f82003-09-16 20:30:58 +00004528static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004529char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004530 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4531 illegal prefix. See RFC 3629 for details */
4532 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4533 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004534 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004535 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4536 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4537 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4538 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004539 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4540 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 +00004541 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4542 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004543 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4544 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4545 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4546 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4547 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 +00004548};
4549
Alexander Belopolsky40018472011-02-26 01:02:56 +00004550PyObject *
4551PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004552 Py_ssize_t size,
4553 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004554{
Walter Dörwald69652032004-09-07 20:24:22 +00004555 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4556}
4557
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004558#include "stringlib/ucs1lib.h"
4559#include "stringlib/codecs.h"
4560#include "stringlib/undef.h"
4561
4562#include "stringlib/ucs2lib.h"
4563#include "stringlib/codecs.h"
4564#include "stringlib/undef.h"
4565
4566#include "stringlib/ucs4lib.h"
4567#include "stringlib/codecs.h"
4568#include "stringlib/undef.h"
4569
Antoine Pitrouab868312009-01-10 15:40:25 +00004570/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4571#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4572
4573/* Mask to quickly check whether a C 'long' contains a
4574 non-ASCII, UTF8-encoded char. */
4575#if (SIZEOF_LONG == 8)
4576# define ASCII_CHAR_MASK 0x8080808080808080L
4577#elif (SIZEOF_LONG == 4)
4578# define ASCII_CHAR_MASK 0x80808080L
4579#else
4580# error C 'long' size should be either 4 or 8!
4581#endif
4582
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004583/* Scans a UTF-8 string and returns the maximum character to be expected
4584 and the size of the decoded unicode string.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004585
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004586 This function doesn't check for errors, these checks are performed in
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004587 PyUnicode_DecodeUTF8Stateful.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004588 */
4589static Py_UCS4
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004590utf8_scanner(const unsigned char *p, Py_ssize_t string_size, Py_ssize_t *unicode_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004591{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004592 Py_ssize_t char_count = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004593 const unsigned char *end = p + string_size;
4594 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004595
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004596 assert(unicode_size != NULL);
4597
4598 /* By having a cascade of independent loops which fallback onto each
4599 other, we minimize the amount of work done in the average loop
4600 iteration, and we also maximize the CPU's ability to predict
4601 branches correctly (because a given condition will have always the
4602 same boolean outcome except perhaps in the last iteration of the
4603 corresponding loop).
4604 In the general case this brings us rather close to decoding
4605 performance pre-PEP 393, despite the two-pass decoding.
4606
4607 Note that the pure ASCII loop is not duplicated once a non-ASCII
4608 character has been encountered. It is actually a pessimization (by
4609 a significant factor) to use this loop on text with many non-ASCII
4610 characters, and it is important to avoid bad performance on valid
4611 utf-8 data (invalid utf-8 being a different can of worms).
4612 */
4613
4614 /* ASCII */
4615 for (; p < end; ++p) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004616 /* Only check value if it's not a ASCII char... */
4617 if (*p < 0x80) {
4618 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4619 an explanation. */
4620 if (!((size_t) p & LONG_PTR_MASK)) {
4621 /* Help register allocation */
4622 register const unsigned char *_p = p;
4623 while (_p < aligned_end) {
4624 unsigned long value = *(unsigned long *) _p;
4625 if (value & ASCII_CHAR_MASK)
4626 break;
4627 _p += SIZEOF_LONG;
4628 char_count += SIZEOF_LONG;
4629 }
4630 p = _p;
4631 if (p == end)
4632 break;
4633 }
4634 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004635 if (*p < 0x80)
4636 ++char_count;
4637 else
4638 goto _ucs1loop;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004639 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004640 *unicode_size = char_count;
4641 return 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004642
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004643_ucs1loop:
4644 for (; p < end; ++p) {
4645 if (*p < 0xc4)
4646 char_count += ((*p & 0xc0) != 0x80);
4647 else
4648 goto _ucs2loop;
4649 }
4650 *unicode_size = char_count;
4651 return 255;
4652
4653_ucs2loop:
4654 for (; p < end; ++p) {
4655 if (*p < 0xf0)
4656 char_count += ((*p & 0xc0) != 0x80);
4657 else
4658 goto _ucs4loop;
4659 }
4660 *unicode_size = char_count;
4661 return 65535;
4662
4663_ucs4loop:
4664 for (; p < end; ++p) {
4665 char_count += ((*p & 0xc0) != 0x80);
4666 }
4667 *unicode_size = char_count;
4668 return 65537;
4669}
4670
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004671/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
Victor Stinner785938e2011-12-11 20:09:03 +01004672 in case of errors. Implicit parameters: unicode, kind, data, onError.
4673 Potential resizing overallocates, so the result needs to shrink at the end.
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004674*/
Victor Stinner785938e2011-12-11 20:09:03 +01004675#define WRITE_MAYBE_FAIL(index, value) \
4676 do { \
4677 Py_ssize_t pos = index; \
4678 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4679 unicode_resize(&unicode, pos + pos/8) < 0) \
4680 goto onError; \
4681 if (unicode_putchar(&unicode, &pos, value) < 0) \
4682 goto onError; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004683 } while (0)
4684
Victor Stinnerbf6e5602011-12-12 01:53:47 +01004685static PyObject *
Victor Stinner785938e2011-12-11 20:09:03 +01004686decode_utf8_errors(const char *starts,
4687 Py_ssize_t size,
4688 const char *errors,
4689 Py_ssize_t *consumed,
4690 const char *s,
4691 PyObject *unicode,
4692 Py_ssize_t i)
Walter Dörwald69652032004-09-07 20:24:22 +00004693{
Guido van Rossumd57fd912000-03-10 22:53:23 +00004694 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004695 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004696 Py_ssize_t startinpos;
4697 Py_ssize_t endinpos;
Victor Stinner785938e2011-12-11 20:09:03 +01004698 const char *e = starts + size;
4699 const char *aligned_end;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004700 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004701 PyObject *errorHandler = NULL;
4702 PyObject *exc = NULL;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004703
Antoine Pitrouab868312009-01-10 15:40:25 +00004704 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004705
4706 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004707 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004708
4709 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004710 /* Fast path for runs of ASCII characters. Given that common UTF-8
4711 input will consist of an overwhelming majority of ASCII
4712 characters, we try to optimize for this case by checking
4713 as many characters as a C 'long' can contain.
4714 First, check if we can do an aligned read, as most CPUs have
4715 a penalty for unaligned reads.
4716 */
4717 if (!((size_t) s & LONG_PTR_MASK)) {
4718 /* Help register allocation */
4719 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004720 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004721 while (_s < aligned_end) {
4722 /* Read a whole long at a time (either 4 or 8 bytes),
4723 and do a fast unrolled copy if it only contains ASCII
4724 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004725 unsigned long value = *(unsigned long *) _s;
4726 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004727 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004728 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4729 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4730 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4731 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004732#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004733 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4734 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4735 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4736 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004737#endif
4738 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004739 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004740 }
4741 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004742 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004743 if (s == e)
4744 break;
4745 ch = (unsigned char)*s;
4746 }
4747 }
4748
4749 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004750 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004751 s++;
4752 continue;
4753 }
4754
4755 n = utf8_code_length[ch];
4756
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004757 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004758 if (consumed)
4759 break;
4760 else {
4761 errmsg = "unexpected end of data";
4762 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004763 endinpos = startinpos+1;
4764 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4765 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004766 goto utf8Error;
4767 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004768 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004769
4770 switch (n) {
4771
4772 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004773 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004774 startinpos = s-starts;
4775 endinpos = startinpos+1;
4776 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004777
4778 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004779 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004780 startinpos = s-starts;
4781 endinpos = startinpos+1;
4782 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004783
4784 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004785 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004786 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004787 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004788 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004789 goto utf8Error;
4790 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004791 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004792 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004793 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004794 break;
4795
4796 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004797 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4798 will result in surrogates in range d800-dfff. Surrogates are
4799 not valid UTF-8 so they are rejected.
4800 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4801 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004802 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004803 (s[2] & 0xc0) != 0x80 ||
4804 ((unsigned char)s[0] == 0xE0 &&
4805 (unsigned char)s[1] < 0xA0) ||
4806 ((unsigned char)s[0] == 0xED &&
4807 (unsigned char)s[1] > 0x9F)) {
4808 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004809 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004810 endinpos = startinpos + 1;
4811
4812 /* if s[1] first two bits are 1 and 0, then the invalid
4813 continuation byte is s[2], so increment endinpos by 1,
4814 if not, s[1] is invalid and endinpos doesn't need to
4815 be incremented. */
4816 if ((s[1] & 0xC0) == 0x80)
4817 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004818 goto utf8Error;
4819 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004820 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004821 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004822 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004823 break;
4824
4825 case 4:
4826 if ((s[1] & 0xc0) != 0x80 ||
4827 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004828 (s[3] & 0xc0) != 0x80 ||
4829 ((unsigned char)s[0] == 0xF0 &&
4830 (unsigned char)s[1] < 0x90) ||
4831 ((unsigned char)s[0] == 0xF4 &&
4832 (unsigned char)s[1] > 0x8F)) {
4833 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004834 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004835 endinpos = startinpos + 1;
4836 if ((s[1] & 0xC0) == 0x80) {
4837 endinpos++;
4838 if ((s[2] & 0xC0) == 0x80)
4839 endinpos++;
4840 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004841 goto utf8Error;
4842 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004843 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004844 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01004845 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Ezio Melotti57221d02010-07-01 07:32:02 +00004846
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004847 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004848 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004849 }
4850 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004851 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004852
Benjamin Peterson29060642009-01-31 22:14:21 +00004853 utf8Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00004854 if (unicode_decode_call_errorhandler(
4855 errors, &errorHandler,
Victor Stinnercbe01342012-02-14 01:17:45 +01004856 "utf-8", errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00004857 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004858 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004859 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004860 /* Update data because unicode_decode_call_errorhandler might have
4861 re-created or resized the unicode object. */
Benjamin Peterson29060642009-01-31 22:14:21 +00004862 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004863 }
Walter Dörwald69652032004-09-07 20:24:22 +00004864 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004865 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004866
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004867 /* Adjust length and ready string when it contained errors and
4868 is of the old resizable kind. */
Victor Stinner785938e2011-12-11 20:09:03 +01004869 if (unicode_resize(&unicode, i) < 0)
4870 goto onError;
4871 unicode_adjust_maxchar(&unicode);
4872 if (unicode == NULL)
4873 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004874
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004875 Py_XDECREF(errorHandler);
4876 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004877 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004878 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004879
Benjamin Peterson29060642009-01-31 22:14:21 +00004880 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004881 Py_XDECREF(errorHandler);
4882 Py_XDECREF(exc);
Victor Stinner785938e2011-12-11 20:09:03 +01004883 Py_XDECREF(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004884 return NULL;
4885}
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004886#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004887
Victor Stinner785938e2011-12-11 20:09:03 +01004888PyObject *
4889PyUnicode_DecodeUTF8Stateful(const char *s,
4890 Py_ssize_t size,
4891 const char *errors,
4892 Py_ssize_t *consumed)
4893{
4894 Py_UCS4 maxchar = 0;
4895 Py_ssize_t unicode_size;
4896 int has_errors = 0;
4897 PyObject *unicode;
4898 int kind;
4899 void *data;
4900 const char *starts = s;
4901 const char *e;
4902 Py_ssize_t i;
4903
4904 if (size == 0) {
4905 if (consumed)
4906 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004907 Py_INCREF(unicode_empty);
4908 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004909 }
4910
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004911 maxchar = utf8_scanner((const unsigned char *)s, size, &unicode_size);
Victor Stinner785938e2011-12-11 20:09:03 +01004912
4913 /* When the string is ASCII only, just use memcpy and return.
4914 unicode_size may be != size if there is an incomplete UTF-8
4915 sequence at the end of the ASCII block. */
4916 if (maxchar < 128 && size == unicode_size) {
4917 if (consumed)
4918 *consumed = size;
Victor Stinnerab870212011-12-17 22:39:43 +01004919 return unicode_fromascii((const unsigned char *)s, size);
Victor Stinner785938e2011-12-11 20:09:03 +01004920 }
4921
4922 unicode = PyUnicode_New(unicode_size, maxchar);
4923 if (!unicode)
4924 return NULL;
4925 kind = PyUnicode_KIND(unicode);
4926 data = PyUnicode_DATA(unicode);
4927
4928 /* Unpack UTF-8 encoded data */
4929 i = 0;
4930 e = starts + size;
4931 switch (kind) {
4932 case PyUnicode_1BYTE_KIND:
4933 has_errors = ucs1lib_utf8_try_decode(s, e, (Py_UCS1 *) data, &s, &i);
4934 break;
4935 case PyUnicode_2BYTE_KIND:
4936 has_errors = ucs2lib_utf8_try_decode(s, e, (Py_UCS2 *) data, &s, &i);
4937 break;
4938 case PyUnicode_4BYTE_KIND:
4939 has_errors = ucs4lib_utf8_try_decode(s, e, (Py_UCS4 *) data, &s, &i);
4940 break;
4941 }
4942 if (!has_errors) {
4943 /* Ensure the unicode size calculation was correct */
4944 assert(i == unicode_size);
4945 assert(s == e);
4946 if (consumed)
4947 *consumed = size;
4948 return unicode;
4949 }
4950
4951 /* In case of errors, maxchar and size computation might be incorrect;
4952 code below refits and resizes as necessary. */
4953 return decode_utf8_errors(starts, size, errors, consumed, s, unicode, i);
4954}
4955
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004956#ifdef __APPLE__
4957
4958/* Simplified UTF-8 decoder using surrogateescape error handler,
4959 used to decode the command line arguments on Mac OS X. */
4960
4961wchar_t*
4962_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4963{
4964 int n;
4965 const char *e;
4966 wchar_t *unicode, *p;
4967
4968 /* Note: size will always be longer than the resulting Unicode
4969 character count */
4970 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4971 PyErr_NoMemory();
4972 return NULL;
4973 }
4974 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4975 if (!unicode)
4976 return NULL;
4977
4978 /* Unpack UTF-8 encoded data */
4979 p = unicode;
4980 e = s + size;
4981 while (s < e) {
4982 Py_UCS4 ch = (unsigned char)*s;
4983
4984 if (ch < 0x80) {
4985 *p++ = (wchar_t)ch;
4986 s++;
4987 continue;
4988 }
4989
4990 n = utf8_code_length[ch];
4991 if (s + n > e) {
4992 goto surrogateescape;
4993 }
4994
4995 switch (n) {
4996 case 0:
4997 case 1:
4998 goto surrogateescape;
4999
5000 case 2:
5001 if ((s[1] & 0xc0) != 0x80)
5002 goto surrogateescape;
5003 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
5004 assert ((ch > 0x007F) && (ch <= 0x07FF));
5005 *p++ = (wchar_t)ch;
5006 break;
5007
5008 case 3:
5009 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
5010 will result in surrogates in range d800-dfff. Surrogates are
5011 not valid UTF-8 so they are rejected.
5012 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
5013 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
5014 if ((s[1] & 0xc0) != 0x80 ||
5015 (s[2] & 0xc0) != 0x80 ||
5016 ((unsigned char)s[0] == 0xE0 &&
5017 (unsigned char)s[1] < 0xA0) ||
5018 ((unsigned char)s[0] == 0xED &&
5019 (unsigned char)s[1] > 0x9F)) {
5020
5021 goto surrogateescape;
5022 }
5023 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
5024 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005025 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005026 break;
5027
5028 case 4:
5029 if ((s[1] & 0xc0) != 0x80 ||
5030 (s[2] & 0xc0) != 0x80 ||
5031 (s[3] & 0xc0) != 0x80 ||
5032 ((unsigned char)s[0] == 0xF0 &&
5033 (unsigned char)s[1] < 0x90) ||
5034 ((unsigned char)s[0] == 0xF4 &&
5035 (unsigned char)s[1] > 0x8F)) {
5036 goto surrogateescape;
5037 }
5038 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
5039 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01005040 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005041
5042#if SIZEOF_WCHAR_T == 4
5043 *p++ = (wchar_t)ch;
5044#else
5045 /* compute and append the two surrogates: */
Victor Stinner551ac952011-11-29 22:58:13 +01005046 *p++ = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5047 *p++ = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005048#endif
5049 break;
5050 }
5051 s += n;
5052 continue;
5053
5054 surrogateescape:
5055 *p++ = 0xDC00 + ch;
5056 s++;
5057 }
5058 *p = L'\0';
5059 return unicode;
5060}
5061
5062#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005063
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005064/* Primary internal function which creates utf8 encoded bytes objects.
5065
5066 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005067 and allocate exactly as much space needed at the end. Else allocate the
5068 maximum possible needed (4 result bytes per Unicode character), and return
5069 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005070*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005071PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005072_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005073{
Victor Stinner6099a032011-12-18 14:22:26 +01005074 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005075 void *data;
5076 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005077
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005078 if (!PyUnicode_Check(unicode)) {
5079 PyErr_BadArgument();
5080 return NULL;
5081 }
5082
5083 if (PyUnicode_READY(unicode) == -1)
5084 return NULL;
5085
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005086 if (PyUnicode_UTF8(unicode))
5087 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5088 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005089
5090 kind = PyUnicode_KIND(unicode);
5091 data = PyUnicode_DATA(unicode);
5092 size = PyUnicode_GET_LENGTH(unicode);
5093
Benjamin Petersonead6b532011-12-20 17:23:42 -06005094 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005095 default:
5096 assert(0);
5097 case PyUnicode_1BYTE_KIND:
5098 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5099 assert(!PyUnicode_IS_ASCII(unicode));
5100 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5101 case PyUnicode_2BYTE_KIND:
5102 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5103 case PyUnicode_4BYTE_KIND:
5104 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005105 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005106}
5107
Alexander Belopolsky40018472011-02-26 01:02:56 +00005108PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005109PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5110 Py_ssize_t size,
5111 const char *errors)
5112{
5113 PyObject *v, *unicode;
5114
5115 unicode = PyUnicode_FromUnicode(s, size);
5116 if (unicode == NULL)
5117 return NULL;
5118 v = _PyUnicode_AsUTF8String(unicode, errors);
5119 Py_DECREF(unicode);
5120 return v;
5121}
5122
5123PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005124PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005125{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005126 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005127}
5128
Walter Dörwald41980ca2007-08-16 21:55:45 +00005129/* --- UTF-32 Codec ------------------------------------------------------- */
5130
5131PyObject *
5132PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005133 Py_ssize_t size,
5134 const char *errors,
5135 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005136{
5137 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5138}
5139
5140PyObject *
5141PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005142 Py_ssize_t size,
5143 const char *errors,
5144 int *byteorder,
5145 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005146{
5147 const char *starts = s;
5148 Py_ssize_t startinpos;
5149 Py_ssize_t endinpos;
5150 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005151 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005152 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005153 int bo = 0; /* assume native ordering by default */
5154 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005155 /* Offsets from q for retrieving bytes in the right order. */
5156#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5157 int iorder[] = {0, 1, 2, 3};
5158#else
5159 int iorder[] = {3, 2, 1, 0};
5160#endif
5161 PyObject *errorHandler = NULL;
5162 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005163
Walter Dörwald41980ca2007-08-16 21:55:45 +00005164 q = (unsigned char *)s;
5165 e = q + size;
5166
5167 if (byteorder)
5168 bo = *byteorder;
5169
5170 /* Check for BOM marks (U+FEFF) in the input and adjust current
5171 byte order setting accordingly. In native mode, the leading BOM
5172 mark is skipped, in all other modes, it is copied to the output
5173 stream as-is (giving a ZWNBSP character). */
5174 if (bo == 0) {
5175 if (size >= 4) {
5176 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00005177 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005178#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005179 if (bom == 0x0000FEFF) {
5180 q += 4;
5181 bo = -1;
5182 }
5183 else if (bom == 0xFFFE0000) {
5184 q += 4;
5185 bo = 1;
5186 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005187#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005188 if (bom == 0x0000FEFF) {
5189 q += 4;
5190 bo = 1;
5191 }
5192 else if (bom == 0xFFFE0000) {
5193 q += 4;
5194 bo = -1;
5195 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005196#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005197 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005198 }
5199
5200 if (bo == -1) {
5201 /* force LE */
5202 iorder[0] = 0;
5203 iorder[1] = 1;
5204 iorder[2] = 2;
5205 iorder[3] = 3;
5206 }
5207 else if (bo == 1) {
5208 /* force BE */
5209 iorder[0] = 3;
5210 iorder[1] = 2;
5211 iorder[2] = 1;
5212 iorder[3] = 0;
5213 }
5214
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005215 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005216 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005217 if (!unicode)
5218 return NULL;
5219 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005220 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005221 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005222
Walter Dörwald41980ca2007-08-16 21:55:45 +00005223 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005224 Py_UCS4 ch;
5225 /* remaining bytes at the end? (size should be divisible by 4) */
5226 if (e-q<4) {
5227 if (consumed)
5228 break;
5229 errmsg = "truncated data";
5230 startinpos = ((const char *)q)-starts;
5231 endinpos = ((const char *)e)-starts;
5232 goto utf32Error;
5233 /* The remaining input chars are ignored if the callback
5234 chooses to skip the input */
5235 }
5236 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5237 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005238
Benjamin Peterson29060642009-01-31 22:14:21 +00005239 if (ch >= 0x110000)
5240 {
5241 errmsg = "codepoint not in range(0x110000)";
5242 startinpos = ((const char *)q)-starts;
5243 endinpos = startinpos+4;
5244 goto utf32Error;
5245 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005246 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5247 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005248 q += 4;
5249 continue;
5250 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005251 if (unicode_decode_call_errorhandler(
5252 errors, &errorHandler,
5253 "utf32", errmsg,
5254 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005255 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005256 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005257 }
5258
5259 if (byteorder)
5260 *byteorder = bo;
5261
5262 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005263 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005264
5265 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005266 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005267 goto onError;
5268
5269 Py_XDECREF(errorHandler);
5270 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005271 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005272
Benjamin Peterson29060642009-01-31 22:14:21 +00005273 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005274 Py_DECREF(unicode);
5275 Py_XDECREF(errorHandler);
5276 Py_XDECREF(exc);
5277 return NULL;
5278}
5279
5280PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005281_PyUnicode_EncodeUTF32(PyObject *str,
5282 const char *errors,
5283 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005284{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005285 int kind;
5286 void *data;
5287 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005288 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005289 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005290 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005291 /* Offsets from p for storing byte pairs in the right order. */
5292#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5293 int iorder[] = {0, 1, 2, 3};
5294#else
5295 int iorder[] = {3, 2, 1, 0};
5296#endif
5297
Benjamin Peterson29060642009-01-31 22:14:21 +00005298#define STORECHAR(CH) \
5299 do { \
5300 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5301 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5302 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5303 p[iorder[0]] = (CH) & 0xff; \
5304 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005305 } while(0)
5306
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005307 if (!PyUnicode_Check(str)) {
5308 PyErr_BadArgument();
5309 return NULL;
5310 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005311 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005312 return NULL;
5313 kind = PyUnicode_KIND(str);
5314 data = PyUnicode_DATA(str);
5315 len = PyUnicode_GET_LENGTH(str);
5316
5317 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005318 bytesize = nsize * 4;
5319 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005320 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005321 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005322 if (v == NULL)
5323 return NULL;
5324
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005325 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005326 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005327 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005328 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005329 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005330
5331 if (byteorder == -1) {
5332 /* force LE */
5333 iorder[0] = 0;
5334 iorder[1] = 1;
5335 iorder[2] = 2;
5336 iorder[3] = 3;
5337 }
5338 else if (byteorder == 1) {
5339 /* force BE */
5340 iorder[0] = 3;
5341 iorder[1] = 2;
5342 iorder[2] = 1;
5343 iorder[3] = 0;
5344 }
5345
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005346 for (i = 0; i < len; i++)
5347 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005348
5349 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005350 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005351#undef STORECHAR
5352}
5353
Alexander Belopolsky40018472011-02-26 01:02:56 +00005354PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005355PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5356 Py_ssize_t size,
5357 const char *errors,
5358 int byteorder)
5359{
5360 PyObject *result;
5361 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5362 if (tmp == NULL)
5363 return NULL;
5364 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5365 Py_DECREF(tmp);
5366 return result;
5367}
5368
5369PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005370PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005371{
Victor Stinnerb960b342011-11-20 19:12:52 +01005372 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005373}
5374
Guido van Rossumd57fd912000-03-10 22:53:23 +00005375/* --- UTF-16 Codec ------------------------------------------------------- */
5376
Tim Peters772747b2001-08-09 22:21:55 +00005377PyObject *
5378PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005379 Py_ssize_t size,
5380 const char *errors,
5381 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005382{
Walter Dörwald69652032004-09-07 20:24:22 +00005383 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5384}
5385
Antoine Pitrouab868312009-01-10 15:40:25 +00005386/* Two masks for fast checking of whether a C 'long' may contain
5387 UTF16-encoded surrogate characters. This is an efficient heuristic,
5388 assuming that non-surrogate characters with a code point >= 0x8000 are
5389 rare in most input.
5390 FAST_CHAR_MASK is used when the input is in native byte ordering,
5391 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005392*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005393#if (SIZEOF_LONG == 8)
5394# define FAST_CHAR_MASK 0x8000800080008000L
5395# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5396#elif (SIZEOF_LONG == 4)
5397# define FAST_CHAR_MASK 0x80008000L
5398# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5399#else
5400# error C 'long' size should be either 4 or 8!
5401#endif
5402
Walter Dörwald69652032004-09-07 20:24:22 +00005403PyObject *
5404PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005405 Py_ssize_t size,
5406 const char *errors,
5407 int *byteorder,
5408 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005409{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005410 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005411 Py_ssize_t startinpos;
5412 Py_ssize_t endinpos;
5413 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005414 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005415 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005416 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005417 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005418 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005419 /* Offsets from q for retrieving byte pairs in the right order. */
5420#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5421 int ihi = 1, ilo = 0;
5422#else
5423 int ihi = 0, ilo = 1;
5424#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005425 PyObject *errorHandler = NULL;
5426 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005427
5428 /* Note: size will always be longer than the resulting Unicode
5429 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005430 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005431 if (!unicode)
5432 return NULL;
5433 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005434 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005435 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005436
Tim Peters772747b2001-08-09 22:21:55 +00005437 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005438 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005439
5440 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005441 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005442
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005443 /* Check for BOM marks (U+FEFF) in the input and adjust current
5444 byte order setting accordingly. In native mode, the leading BOM
5445 mark is skipped, in all other modes, it is copied to the output
5446 stream as-is (giving a ZWNBSP character). */
5447 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005448 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005449 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005450#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005451 if (bom == 0xFEFF) {
5452 q += 2;
5453 bo = -1;
5454 }
5455 else if (bom == 0xFFFE) {
5456 q += 2;
5457 bo = 1;
5458 }
Tim Petersced69f82003-09-16 20:30:58 +00005459#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005460 if (bom == 0xFEFF) {
5461 q += 2;
5462 bo = 1;
5463 }
5464 else if (bom == 0xFFFE) {
5465 q += 2;
5466 bo = -1;
5467 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005468#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005469 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005470 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005471
Tim Peters772747b2001-08-09 22:21:55 +00005472 if (bo == -1) {
5473 /* force LE */
5474 ihi = 1;
5475 ilo = 0;
5476 }
5477 else if (bo == 1) {
5478 /* force BE */
5479 ihi = 0;
5480 ilo = 1;
5481 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005482#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5483 native_ordering = ilo < ihi;
5484#else
5485 native_ordering = ilo > ihi;
5486#endif
Tim Peters772747b2001-08-09 22:21:55 +00005487
Antoine Pitrouab868312009-01-10 15:40:25 +00005488 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005489 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005490 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005491 /* First check for possible aligned read of a C 'long'. Unaligned
5492 reads are more expensive, better to defer to another iteration. */
5493 if (!((size_t) q & LONG_PTR_MASK)) {
5494 /* Fast path for runs of non-surrogate chars. */
5495 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005496 int kind = PyUnicode_KIND(unicode);
5497 void *data = PyUnicode_DATA(unicode);
5498 while (_q < aligned_end) {
5499 unsigned long block = * (unsigned long *) _q;
5500 unsigned short *pblock = (unsigned short*)&block;
5501 Py_UCS4 maxch;
5502 if (native_ordering) {
5503 /* Can use buffer directly */
5504 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005505 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005506 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005507 else {
5508 /* Need to byte-swap */
5509 unsigned char *_p = (unsigned char*)pblock;
5510 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005511 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005512 _p[0] = _q[1];
5513 _p[1] = _q[0];
5514 _p[2] = _q[3];
5515 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005516#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005517 _p[4] = _q[5];
5518 _p[5] = _q[4];
5519 _p[6] = _q[7];
5520 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005521#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005522 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005523 maxch = Py_MAX(pblock[0], pblock[1]);
5524#if SIZEOF_LONG == 8
5525 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5526#endif
5527 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5528 if (unicode_widen(&unicode, maxch) < 0)
5529 goto onError;
5530 kind = PyUnicode_KIND(unicode);
5531 data = PyUnicode_DATA(unicode);
5532 }
5533 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5534 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5535#if SIZEOF_LONG == 8
5536 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5537 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5538#endif
5539 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005540 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005541 q = _q;
5542 if (q >= e)
5543 break;
5544 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005545 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005546
Benjamin Peterson14339b62009-01-31 16:36:08 +00005547 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005548
Victor Stinner551ac952011-11-29 22:58:13 +01005549 if (!Py_UNICODE_IS_SURROGATE(ch)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005550 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5551 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005552 continue;
5553 }
5554
5555 /* UTF-16 code pair: */
5556 if (q > e) {
5557 errmsg = "unexpected end of data";
5558 startinpos = (((const char *)q) - 2) - starts;
5559 endinpos = ((const char *)e) + 1 - starts;
5560 goto utf16Error;
5561 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005562 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5563 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005564 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005565 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005566 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005567 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005568 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005569 continue;
5570 }
5571 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005572 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005573 startinpos = (((const char *)q)-4)-starts;
5574 endinpos = startinpos+2;
5575 goto utf16Error;
5576 }
5577
Benjamin Peterson14339b62009-01-31 16:36:08 +00005578 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005579 errmsg = "illegal encoding";
5580 startinpos = (((const char *)q)-2)-starts;
5581 endinpos = startinpos+2;
5582 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005583
Benjamin Peterson29060642009-01-31 22:14:21 +00005584 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005585 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005586 errors,
5587 &errorHandler,
5588 "utf16", errmsg,
5589 &starts,
5590 (const char **)&e,
5591 &startinpos,
5592 &endinpos,
5593 &exc,
5594 (const char **)&q,
5595 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005596 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005597 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005598 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005599 /* remaining byte at the end? (size should be even) */
5600 if (e == q) {
5601 if (!consumed) {
5602 errmsg = "truncated data";
5603 startinpos = ((const char *)q) - starts;
5604 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005605 if (unicode_decode_call_errorhandler(
5606 errors,
5607 &errorHandler,
5608 "utf16", errmsg,
5609 &starts,
5610 (const char **)&e,
5611 &startinpos,
5612 &endinpos,
5613 &exc,
5614 (const char **)&q,
5615 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005616 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005617 goto onError;
5618 /* The remaining input chars are ignored if the callback
5619 chooses to skip the input */
5620 }
5621 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005622
5623 if (byteorder)
5624 *byteorder = bo;
5625
Walter Dörwald69652032004-09-07 20:24:22 +00005626 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005627 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005628
Guido van Rossumd57fd912000-03-10 22:53:23 +00005629 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005630 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005631 goto onError;
5632
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005633 Py_XDECREF(errorHandler);
5634 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005635 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005636
Benjamin Peterson29060642009-01-31 22:14:21 +00005637 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005638 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005639 Py_XDECREF(errorHandler);
5640 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005641 return NULL;
5642}
5643
Antoine Pitrouab868312009-01-10 15:40:25 +00005644#undef FAST_CHAR_MASK
5645#undef SWAPPED_FAST_CHAR_MASK
5646
Tim Peters772747b2001-08-09 22:21:55 +00005647PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005648_PyUnicode_EncodeUTF16(PyObject *str,
5649 const char *errors,
5650 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005651{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005652 int kind;
5653 void *data;
5654 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005655 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005656 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005657 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005658 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005659 /* Offsets from p for storing byte pairs in the right order. */
5660#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5661 int ihi = 1, ilo = 0;
5662#else
5663 int ihi = 0, ilo = 1;
5664#endif
5665
Benjamin Peterson29060642009-01-31 22:14:21 +00005666#define STORECHAR(CH) \
5667 do { \
5668 p[ihi] = ((CH) >> 8) & 0xff; \
5669 p[ilo] = (CH) & 0xff; \
5670 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005671 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005672
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005673 if (!PyUnicode_Check(str)) {
5674 PyErr_BadArgument();
5675 return NULL;
5676 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005677 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005678 return NULL;
5679 kind = PyUnicode_KIND(str);
5680 data = PyUnicode_DATA(str);
5681 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005682
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005683 pairs = 0;
5684 if (kind == PyUnicode_4BYTE_KIND)
5685 for (i = 0; i < len; i++)
5686 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5687 pairs++;
5688 /* 2 * (len + pairs + (byteorder == 0)) */
5689 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005690 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005691 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005692 bytesize = nsize * 2;
5693 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005694 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005695 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005696 if (v == NULL)
5697 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005698
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005699 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005700 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005701 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005702 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005703 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005704
5705 if (byteorder == -1) {
5706 /* force LE */
5707 ihi = 1;
5708 ilo = 0;
5709 }
5710 else if (byteorder == 1) {
5711 /* force BE */
5712 ihi = 0;
5713 ilo = 1;
5714 }
5715
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005716 for (i = 0; i < len; i++) {
5717 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5718 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005719 if (ch >= 0x10000) {
Victor Stinner551ac952011-11-29 22:58:13 +01005720 ch2 = Py_UNICODE_LOW_SURROGATE(ch);
5721 ch = Py_UNICODE_HIGH_SURROGATE(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00005722 }
Tim Peters772747b2001-08-09 22:21:55 +00005723 STORECHAR(ch);
5724 if (ch2)
5725 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005726 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005727
5728 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005729 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005730#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005731}
5732
Alexander Belopolsky40018472011-02-26 01:02:56 +00005733PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005734PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5735 Py_ssize_t size,
5736 const char *errors,
5737 int byteorder)
5738{
5739 PyObject *result;
5740 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5741 if (tmp == NULL)
5742 return NULL;
5743 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5744 Py_DECREF(tmp);
5745 return result;
5746}
5747
5748PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005749PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005750{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005751 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005752}
5753
5754/* --- Unicode Escape Codec ----------------------------------------------- */
5755
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005756/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5757 if all the escapes in the string make it still a valid ASCII string.
5758 Returns -1 if any escapes were found which cause the string to
5759 pop out of ASCII range. Otherwise returns the length of the
5760 required buffer to hold the string.
5761 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005762static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005763length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5764{
5765 const unsigned char *p = (const unsigned char *)s;
5766 const unsigned char *end = p + size;
5767 Py_ssize_t length = 0;
5768
5769 if (size < 0)
5770 return -1;
5771
5772 for (; p < end; ++p) {
5773 if (*p > 127) {
5774 /* Non-ASCII */
5775 return -1;
5776 }
5777 else if (*p != '\\') {
5778 /* Normal character */
5779 ++length;
5780 }
5781 else {
5782 /* Backslash-escape, check next char */
5783 ++p;
5784 /* Escape sequence reaches till end of string or
5785 non-ASCII follow-up. */
5786 if (p >= end || *p > 127)
5787 return -1;
5788 switch (*p) {
5789 case '\n':
5790 /* backslash + \n result in zero characters */
5791 break;
5792 case '\\': case '\'': case '\"':
5793 case 'b': case 'f': case 't':
5794 case 'n': case 'r': case 'v': case 'a':
5795 ++length;
5796 break;
5797 case '0': case '1': case '2': case '3':
5798 case '4': case '5': case '6': case '7':
5799 case 'x': case 'u': case 'U': case 'N':
5800 /* these do not guarantee ASCII characters */
5801 return -1;
5802 default:
5803 /* count the backslash + the other character */
5804 length += 2;
5805 }
5806 }
5807 }
5808 return length;
5809}
5810
Fredrik Lundh06d12682001-01-24 07:59:11 +00005811static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005812
Alexander Belopolsky40018472011-02-26 01:02:56 +00005813PyObject *
5814PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005815 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005816 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005817{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005818 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005819 Py_ssize_t startinpos;
5820 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005821 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005822 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005823 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005824 char* message;
5825 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005826 PyObject *errorHandler = NULL;
5827 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005828 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005829 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005830
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005831 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005832
5833 /* After length_of_escaped_ascii_string() there are two alternatives,
5834 either the string is pure ASCII with named escapes like \n, etc.
5835 and we determined it's exact size (common case)
5836 or it contains \x, \u, ... escape sequences. then we create a
5837 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005838 if (len >= 0) {
5839 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005840 if (!v)
5841 goto onError;
5842 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005843 }
5844 else {
5845 /* Escaped strings will always be longer than the resulting
5846 Unicode string, so we start with size here and then reduce the
5847 length after conversion to the true value.
5848 (but if the error callback returns a long replacement string
5849 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005850 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005851 if (!v)
5852 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005853 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005854 }
5855
Guido van Rossumd57fd912000-03-10 22:53:23 +00005856 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005857 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005858 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005859 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005860
Guido van Rossumd57fd912000-03-10 22:53:23 +00005861 while (s < end) {
5862 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005863 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005864 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005865
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005866 /* The only case in which i == ascii_length is a backslash
5867 followed by a newline. */
5868 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005869
Guido van Rossumd57fd912000-03-10 22:53:23 +00005870 /* Non-escape characters are interpreted as Unicode ordinals */
5871 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005872 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5873 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005874 continue;
5875 }
5876
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005877 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005878 /* \ - Escapes */
5879 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005880 c = *s++;
5881 if (s > end)
5882 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005883
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005884 /* The only case in which i == ascii_length is a backslash
5885 followed by a newline. */
5886 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005887
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005888 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005889
Benjamin Peterson29060642009-01-31 22:14:21 +00005890 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005891#define WRITECHAR(ch) \
5892 do { \
5893 if (unicode_putchar(&v, &i, ch) < 0) \
5894 goto onError; \
5895 }while(0)
5896
Guido van Rossumd57fd912000-03-10 22:53:23 +00005897 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005898 case '\\': WRITECHAR('\\'); break;
5899 case '\'': WRITECHAR('\''); break;
5900 case '\"': WRITECHAR('\"'); break;
5901 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005902 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005903 case 'f': WRITECHAR('\014'); break;
5904 case 't': WRITECHAR('\t'); break;
5905 case 'n': WRITECHAR('\n'); break;
5906 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005907 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005908 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005909 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005910 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005911
Benjamin Peterson29060642009-01-31 22:14:21 +00005912 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005913 case '0': case '1': case '2': case '3':
5914 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005915 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005916 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005917 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005918 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005919 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005920 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005921 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005922 break;
5923
Benjamin Peterson29060642009-01-31 22:14:21 +00005924 /* hex escapes */
5925 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005926 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005927 digits = 2;
5928 message = "truncated \\xXX escape";
5929 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005930
Benjamin Peterson29060642009-01-31 22:14:21 +00005931 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005932 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005933 digits = 4;
5934 message = "truncated \\uXXXX escape";
5935 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005936
Benjamin Peterson29060642009-01-31 22:14:21 +00005937 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005938 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005939 digits = 8;
5940 message = "truncated \\UXXXXXXXX escape";
5941 hexescape:
5942 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005943 if (s+digits>end) {
5944 endinpos = size;
5945 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005946 errors, &errorHandler,
5947 "unicodeescape", "end of string in escape sequence",
5948 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005949 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005950 goto onError;
5951 goto nextByte;
5952 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005953 for (j = 0; j < digits; ++j) {
5954 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005955 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005956 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005957 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005958 errors, &errorHandler,
5959 "unicodeescape", message,
5960 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005961 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005962 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005963 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005964 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005965 }
5966 chr = (chr<<4) & ~0xF;
5967 if (c >= '0' && c <= '9')
5968 chr += c - '0';
5969 else if (c >= 'a' && c <= 'f')
5970 chr += 10 + c - 'a';
5971 else
5972 chr += 10 + c - 'A';
5973 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005974 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005975 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005976 /* _decoding_error will have already written into the
5977 target buffer. */
5978 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005979 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005980 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005981 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005982 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005983 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005984 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005985 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005986 errors, &errorHandler,
5987 "unicodeescape", "illegal Unicode character",
5988 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005989 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005990 goto onError;
5991 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005992 break;
5993
Benjamin Peterson29060642009-01-31 22:14:21 +00005994 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005995 case 'N':
5996 message = "malformed \\N character escape";
5997 if (ucnhash_CAPI == NULL) {
5998 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005999 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6000 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00006001 if (ucnhash_CAPI == NULL)
6002 goto ucnhashError;
6003 }
6004 if (*s == '{') {
6005 const char *start = s+1;
6006 /* look for the closing brace */
6007 while (*s != '}' && s < end)
6008 s++;
6009 if (s > start && s < end && *s == '}') {
6010 /* found a name. look it up in the unicode database */
6011 message = "unknown Unicode character name";
6012 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006013 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03006014 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00006015 goto store;
6016 }
6017 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006018 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006019 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006020 errors, &errorHandler,
6021 "unicodeescape", message,
6022 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006023 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00006024 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006025 break;
6026
6027 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00006028 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006029 message = "\\ at end of string";
6030 s--;
6031 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006032 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006033 errors, &errorHandler,
6034 "unicodeescape", message,
6035 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006036 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00006037 goto onError;
6038 }
6039 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006040 WRITECHAR('\\');
6041 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00006042 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006043 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006044 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006045 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006046 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006047 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006048#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006049
Victor Stinner16e6a802011-12-12 13:24:15 +01006050 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006051 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006052 Py_XDECREF(errorHandler);
6053 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006054 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00006055
Benjamin Peterson29060642009-01-31 22:14:21 +00006056 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00006057 PyErr_SetString(
6058 PyExc_UnicodeError,
6059 "\\N escapes not supported (can't load unicodedata module)"
6060 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00006061 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006062 Py_XDECREF(errorHandler);
6063 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00006064 return NULL;
6065
Benjamin Peterson29060642009-01-31 22:14:21 +00006066 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006067 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006068 Py_XDECREF(errorHandler);
6069 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006070 return NULL;
6071}
6072
6073/* Return a Unicode-Escape string version of the Unicode object.
6074
6075 If quotes is true, the string is enclosed in u"" or u'' quotes as
6076 appropriate.
6077
6078*/
6079
Alexander Belopolsky40018472011-02-26 01:02:56 +00006080PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006081PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006082{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006083 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006084 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006085 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006086 int kind;
6087 void *data;
6088 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006089
Thomas Wouters89f507f2006-12-13 04:49:30 +00006090 /* Initial allocation is based on the longest-possible unichr
6091 escape.
6092
6093 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
6094 unichr, so in this case it's the longest unichr escape. In
6095 narrow (UTF-16) builds this is five chars per source unichr
6096 since there are two unichrs in the surrogate pair, so in narrow
6097 (UTF-16) builds it's not the longest unichr escape.
6098
6099 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
6100 so in the narrow (UTF-16) build case it's the longest unichr
6101 escape.
6102 */
6103
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006104 if (!PyUnicode_Check(unicode)) {
6105 PyErr_BadArgument();
6106 return NULL;
6107 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006108 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006109 return NULL;
6110 len = PyUnicode_GET_LENGTH(unicode);
6111 kind = PyUnicode_KIND(unicode);
6112 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06006113 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006114 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6115 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6116 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6117 }
6118
6119 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006120 return PyBytes_FromStringAndSize(NULL, 0);
6121
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006122 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006123 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006124
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006125 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00006126 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006127 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00006128 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006129 if (repr == NULL)
6130 return NULL;
6131
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006132 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006133
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006134 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006135 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006136
Walter Dörwald79e913e2007-05-12 11:08:06 +00006137 /* Escape backslashes */
6138 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006139 *p++ = '\\';
6140 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00006141 continue;
Tim Petersced69f82003-09-16 20:30:58 +00006142 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006143
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006144 /* Map 21-bit characters to '\U00xxxxxx' */
6145 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006146 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006147 *p++ = '\\';
6148 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006149 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
6150 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
6151 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6152 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6153 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6154 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6155 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6156 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006157 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006158 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006159
Guido van Rossumd57fd912000-03-10 22:53:23 +00006160 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006161 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006162 *p++ = '\\';
6163 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006164 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6165 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6166 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6167 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006168 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006169
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006170 /* Map special whitespace to '\t', \n', '\r' */
6171 else if (ch == '\t') {
6172 *p++ = '\\';
6173 *p++ = 't';
6174 }
6175 else if (ch == '\n') {
6176 *p++ = '\\';
6177 *p++ = 'n';
6178 }
6179 else if (ch == '\r') {
6180 *p++ = '\\';
6181 *p++ = 'r';
6182 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006183
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006184 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006185 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006186 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006187 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006188 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6189 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006190 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006191
Guido van Rossumd57fd912000-03-10 22:53:23 +00006192 /* Copy everything else as-is */
6193 else
6194 *p++ = (char) ch;
6195 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006196
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006197 assert(p - PyBytes_AS_STRING(repr) > 0);
6198 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6199 return NULL;
6200 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006201}
6202
Alexander Belopolsky40018472011-02-26 01:02:56 +00006203PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006204PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6205 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006206{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006207 PyObject *result;
6208 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6209 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006210 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006211 result = PyUnicode_AsUnicodeEscapeString(tmp);
6212 Py_DECREF(tmp);
6213 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006214}
6215
6216/* --- Raw Unicode Escape Codec ------------------------------------------- */
6217
Alexander Belopolsky40018472011-02-26 01:02:56 +00006218PyObject *
6219PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006220 Py_ssize_t size,
6221 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006222{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006223 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006224 Py_ssize_t startinpos;
6225 Py_ssize_t endinpos;
6226 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006227 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006228 const char *end;
6229 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006230 PyObject *errorHandler = NULL;
6231 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006232
Guido van Rossumd57fd912000-03-10 22:53:23 +00006233 /* Escaped strings will always be longer than the resulting
6234 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006235 length after conversion to the true value. (But decoding error
6236 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006237 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006238 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006239 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006240 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006241 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006242 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006243 end = s + size;
6244 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006245 unsigned char c;
6246 Py_UCS4 x;
6247 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006248 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006249
Benjamin Peterson29060642009-01-31 22:14:21 +00006250 /* Non-escape characters are interpreted as Unicode ordinals */
6251 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006252 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6253 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006254 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006255 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006256 startinpos = s-starts;
6257
6258 /* \u-escapes are only interpreted iff the number of leading
6259 backslashes if odd */
6260 bs = s;
6261 for (;s < end;) {
6262 if (*s != '\\')
6263 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006264 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6265 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006266 }
6267 if (((s - bs) & 1) == 0 ||
6268 s >= end ||
6269 (*s != 'u' && *s != 'U')) {
6270 continue;
6271 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006272 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006273 count = *s=='u' ? 4 : 8;
6274 s++;
6275
6276 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006277 for (x = 0, i = 0; i < count; ++i, ++s) {
6278 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006279 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006280 endinpos = s-starts;
6281 if (unicode_decode_call_errorhandler(
6282 errors, &errorHandler,
6283 "rawunicodeescape", "truncated \\uXXXX",
6284 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006285 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006286 goto onError;
6287 goto nextByte;
6288 }
6289 x = (x<<4) & ~0xF;
6290 if (c >= '0' && c <= '9')
6291 x += c - '0';
6292 else if (c >= 'a' && c <= 'f')
6293 x += 10 + c - 'a';
6294 else
6295 x += 10 + c - 'A';
6296 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006297 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006298 if (unicode_putchar(&v, &outpos, x) < 0)
6299 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006300 } else {
6301 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006302 if (unicode_decode_call_errorhandler(
6303 errors, &errorHandler,
6304 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006305 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006306 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006307 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006308 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006309 nextByte:
6310 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006311 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006312 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006313 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006314 Py_XDECREF(errorHandler);
6315 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006316 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006317
Benjamin Peterson29060642009-01-31 22:14:21 +00006318 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006319 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006320 Py_XDECREF(errorHandler);
6321 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006322 return NULL;
6323}
6324
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006325
Alexander Belopolsky40018472011-02-26 01:02:56 +00006326PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006327PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006328{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006329 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006330 char *p;
6331 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006332 Py_ssize_t expandsize, pos;
6333 int kind;
6334 void *data;
6335 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006336
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006337 if (!PyUnicode_Check(unicode)) {
6338 PyErr_BadArgument();
6339 return NULL;
6340 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006341 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006342 return NULL;
6343 kind = PyUnicode_KIND(unicode);
6344 data = PyUnicode_DATA(unicode);
6345 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006346 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6347 bytes, and 1 byte characters 4. */
6348 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006349
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006350 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006351 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006352
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006353 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006354 if (repr == NULL)
6355 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006356 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006357 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006358
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006359 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006360 for (pos = 0; pos < len; pos++) {
6361 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006362 /* Map 32-bit characters to '\Uxxxxxxxx' */
6363 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006364 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006365 *p++ = '\\';
6366 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006367 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6368 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6369 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6370 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6371 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6372 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6373 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6374 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006375 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006376 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006377 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006378 *p++ = '\\';
6379 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006380 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6381 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6382 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6383 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006384 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006385 /* Copy everything else as-is */
6386 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006387 *p++ = (char) ch;
6388 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006389
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006390 assert(p > q);
6391 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006392 return NULL;
6393 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006394}
6395
Alexander Belopolsky40018472011-02-26 01:02:56 +00006396PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006397PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6398 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006399{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006400 PyObject *result;
6401 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6402 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006403 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006404 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6405 Py_DECREF(tmp);
6406 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006407}
6408
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006409/* --- Unicode Internal Codec ------------------------------------------- */
6410
Alexander Belopolsky40018472011-02-26 01:02:56 +00006411PyObject *
6412_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006413 Py_ssize_t size,
6414 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006415{
6416 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006417 Py_ssize_t startinpos;
6418 Py_ssize_t endinpos;
6419 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006420 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006421 const char *end;
6422 const char *reason;
6423 PyObject *errorHandler = NULL;
6424 PyObject *exc = NULL;
6425
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006426 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006427 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006428 1))
6429 return NULL;
6430
Thomas Wouters89f507f2006-12-13 04:49:30 +00006431 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006432 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006433 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006434 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006435 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006436 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006437 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006438 end = s + size;
6439
6440 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006441 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006442 Py_UCS4 ch;
6443 /* We copy the raw representation one byte at a time because the
6444 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006445 ((char *) &uch)[0] = s[0];
6446 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006447#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006448 ((char *) &uch)[2] = s[2];
6449 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006450#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006451 ch = uch;
6452
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006453 /* We have to sanity check the raw data, otherwise doom looms for
6454 some malformed UCS-4 data. */
6455 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006456#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006457 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006458#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006459 end-s < Py_UNICODE_SIZE
6460 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006461 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006462 startinpos = s - starts;
6463 if (end-s < Py_UNICODE_SIZE) {
6464 endinpos = end-starts;
6465 reason = "truncated input";
6466 }
6467 else {
6468 endinpos = s - starts + Py_UNICODE_SIZE;
6469 reason = "illegal code point (> 0x10FFFF)";
6470 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006471 if (unicode_decode_call_errorhandler(
6472 errors, &errorHandler,
6473 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006474 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006475 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006476 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006477 continue;
6478 }
6479
6480 s += Py_UNICODE_SIZE;
6481#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006482 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006483 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006484 Py_UNICODE uch2;
6485 ((char *) &uch2)[0] = s[0];
6486 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006487 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006488 {
Victor Stinner551ac952011-11-29 22:58:13 +01006489 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006490 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006491 }
6492 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006493#endif
6494
6495 if (unicode_putchar(&v, &outpos, ch) < 0)
6496 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006497 }
6498
Victor Stinner16e6a802011-12-12 13:24:15 +01006499 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006500 goto onError;
6501 Py_XDECREF(errorHandler);
6502 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006503 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006504
Benjamin Peterson29060642009-01-31 22:14:21 +00006505 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006506 Py_XDECREF(v);
6507 Py_XDECREF(errorHandler);
6508 Py_XDECREF(exc);
6509 return NULL;
6510}
6511
Guido van Rossumd57fd912000-03-10 22:53:23 +00006512/* --- Latin-1 Codec ------------------------------------------------------ */
6513
Alexander Belopolsky40018472011-02-26 01:02:56 +00006514PyObject *
6515PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006516 Py_ssize_t size,
6517 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006518{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006519 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006520 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006521}
6522
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006523/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006524static void
6525make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006526 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006527 PyObject *unicode,
6528 Py_ssize_t startpos, Py_ssize_t endpos,
6529 const char *reason)
6530{
6531 if (*exceptionObject == NULL) {
6532 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006533 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006534 encoding, unicode, startpos, endpos, reason);
6535 }
6536 else {
6537 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6538 goto onError;
6539 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6540 goto onError;
6541 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6542 goto onError;
6543 return;
6544 onError:
6545 Py_DECREF(*exceptionObject);
6546 *exceptionObject = NULL;
6547 }
6548}
6549
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006550/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006551static void
6552raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006553 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006554 PyObject *unicode,
6555 Py_ssize_t startpos, Py_ssize_t endpos,
6556 const char *reason)
6557{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006558 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006559 encoding, unicode, startpos, endpos, reason);
6560 if (*exceptionObject != NULL)
6561 PyCodec_StrictErrors(*exceptionObject);
6562}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006563
6564/* error handling callback helper:
6565 build arguments, call the callback and check the arguments,
6566 put the result into newpos and return the replacement string, which
6567 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006568static PyObject *
6569unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006570 PyObject **errorHandler,
6571 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006572 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006573 Py_ssize_t startpos, Py_ssize_t endpos,
6574 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006575{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006576 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006577 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006578 PyObject *restuple;
6579 PyObject *resunicode;
6580
6581 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006582 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006583 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006584 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006585 }
6586
Benjamin Petersonbac79492012-01-14 13:34:47 -05006587 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006588 return NULL;
6589 len = PyUnicode_GET_LENGTH(unicode);
6590
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006591 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006592 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006593 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006594 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006595
6596 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006597 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006598 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006599 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006600 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006601 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006602 Py_DECREF(restuple);
6603 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006604 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006605 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006606 &resunicode, newpos)) {
6607 Py_DECREF(restuple);
6608 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006609 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006610 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6611 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6612 Py_DECREF(restuple);
6613 return NULL;
6614 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006615 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006616 *newpos = len + *newpos;
6617 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006618 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6619 Py_DECREF(restuple);
6620 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006621 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006622 Py_INCREF(resunicode);
6623 Py_DECREF(restuple);
6624 return resunicode;
6625}
6626
Alexander Belopolsky40018472011-02-26 01:02:56 +00006627static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006628unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006629 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006630 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006631{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006632 /* input state */
6633 Py_ssize_t pos=0, size;
6634 int kind;
6635 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006636 /* output object */
6637 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006638 /* pointer into the output */
6639 char *str;
6640 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006641 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006642 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6643 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006644 PyObject *errorHandler = NULL;
6645 PyObject *exc = NULL;
6646 /* the following variable is used for caching string comparisons
6647 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6648 int known_errorHandler = -1;
6649
Benjamin Petersonbac79492012-01-14 13:34:47 -05006650 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006651 return NULL;
6652 size = PyUnicode_GET_LENGTH(unicode);
6653 kind = PyUnicode_KIND(unicode);
6654 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006655 /* allocate enough for a simple encoding without
6656 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006657 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006658 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006659 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006660 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006661 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006662 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006663 ressize = size;
6664
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006665 while (pos < size) {
6666 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006667
Benjamin Peterson29060642009-01-31 22:14:21 +00006668 /* can we encode this? */
6669 if (c<limit) {
6670 /* no overflow check, because we know that the space is enough */
6671 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006672 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006673 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006674 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006675 Py_ssize_t requiredsize;
6676 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006677 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006678 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006679 Py_ssize_t collstart = pos;
6680 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006681 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006682 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006683 ++collend;
6684 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6685 if (known_errorHandler==-1) {
6686 if ((errors==NULL) || (!strcmp(errors, "strict")))
6687 known_errorHandler = 1;
6688 else if (!strcmp(errors, "replace"))
6689 known_errorHandler = 2;
6690 else if (!strcmp(errors, "ignore"))
6691 known_errorHandler = 3;
6692 else if (!strcmp(errors, "xmlcharrefreplace"))
6693 known_errorHandler = 4;
6694 else
6695 known_errorHandler = 0;
6696 }
6697 switch (known_errorHandler) {
6698 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006699 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006700 goto onError;
6701 case 2: /* replace */
6702 while (collstart++<collend)
6703 *str++ = '?'; /* fall through */
6704 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006705 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006706 break;
6707 case 4: /* xmlcharrefreplace */
6708 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006709 /* determine replacement size */
6710 for (i = collstart, repsize = 0; i < collend; ++i) {
6711 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6712 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006713 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006714 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006715 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006716 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006717 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006718 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006719 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006720 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006721 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006722 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006723 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006724 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006725 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006726 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006727 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006728 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006729 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006730 if (requiredsize > ressize) {
6731 if (requiredsize<2*ressize)
6732 requiredsize = 2*ressize;
6733 if (_PyBytes_Resize(&res, requiredsize))
6734 goto onError;
6735 str = PyBytes_AS_STRING(res) + respos;
6736 ressize = requiredsize;
6737 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006738 /* generate replacement */
6739 for (i = collstart; i < collend; ++i) {
6740 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006741 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006742 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006743 break;
6744 default:
6745 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006746 encoding, reason, unicode, &exc,
6747 collstart, collend, &newpos);
6748 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006749 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006750 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006751 if (PyBytes_Check(repunicode)) {
6752 /* Directly copy bytes result to output. */
6753 repsize = PyBytes_Size(repunicode);
6754 if (repsize > 1) {
6755 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006756 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006757 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6758 Py_DECREF(repunicode);
6759 goto onError;
6760 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006761 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006762 ressize += repsize-1;
6763 }
6764 memcpy(str, PyBytes_AsString(repunicode), repsize);
6765 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006766 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006767 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006768 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006769 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006770 /* need more space? (at least enough for what we
6771 have+the replacement+the rest of the string, so
6772 we won't have to check space for encodable characters) */
6773 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006774 repsize = PyUnicode_GET_LENGTH(repunicode);
6775 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006776 if (requiredsize > ressize) {
6777 if (requiredsize<2*ressize)
6778 requiredsize = 2*ressize;
6779 if (_PyBytes_Resize(&res, requiredsize)) {
6780 Py_DECREF(repunicode);
6781 goto onError;
6782 }
6783 str = PyBytes_AS_STRING(res) + respos;
6784 ressize = requiredsize;
6785 }
6786 /* check if there is anything unencodable in the replacement
6787 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006788 for (i = 0; repsize-->0; ++i, ++str) {
6789 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006790 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006791 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006792 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006793 Py_DECREF(repunicode);
6794 goto onError;
6795 }
6796 *str = (char)c;
6797 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006798 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006799 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006800 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006801 }
6802 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006803 /* Resize if we allocated to much */
6804 size = str - PyBytes_AS_STRING(res);
6805 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006806 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006807 if (_PyBytes_Resize(&res, size) < 0)
6808 goto onError;
6809 }
6810
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006811 Py_XDECREF(errorHandler);
6812 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006813 return res;
6814
6815 onError:
6816 Py_XDECREF(res);
6817 Py_XDECREF(errorHandler);
6818 Py_XDECREF(exc);
6819 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006820}
6821
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006822/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006823PyObject *
6824PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006825 Py_ssize_t size,
6826 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006827{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006828 PyObject *result;
6829 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6830 if (unicode == NULL)
6831 return NULL;
6832 result = unicode_encode_ucs1(unicode, errors, 256);
6833 Py_DECREF(unicode);
6834 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006835}
6836
Alexander Belopolsky40018472011-02-26 01:02:56 +00006837PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006838_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006839{
6840 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006841 PyErr_BadArgument();
6842 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006843 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006844 if (PyUnicode_READY(unicode) == -1)
6845 return NULL;
6846 /* Fast path: if it is a one-byte string, construct
6847 bytes object directly. */
6848 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6849 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6850 PyUnicode_GET_LENGTH(unicode));
6851 /* Non-Latin-1 characters present. Defer to above function to
6852 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006853 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006854}
6855
6856PyObject*
6857PyUnicode_AsLatin1String(PyObject *unicode)
6858{
6859 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006860}
6861
6862/* --- 7-bit ASCII Codec -------------------------------------------------- */
6863
Alexander Belopolsky40018472011-02-26 01:02:56 +00006864PyObject *
6865PyUnicode_DecodeASCII(const char *s,
6866 Py_ssize_t size,
6867 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006868{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006869 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006870 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006871 int kind;
6872 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006873 Py_ssize_t startinpos;
6874 Py_ssize_t endinpos;
6875 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006876 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006877 int has_error;
6878 const unsigned char *p = (const unsigned char *)s;
6879 const unsigned char *end = p + size;
6880 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006881 PyObject *errorHandler = NULL;
6882 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006883
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006884 if (size == 0) {
6885 Py_INCREF(unicode_empty);
6886 return unicode_empty;
6887 }
6888
Guido van Rossumd57fd912000-03-10 22:53:23 +00006889 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006890 if (size == 1 && (unsigned char)s[0] < 128)
6891 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006892
Victor Stinner702c7342011-10-05 13:50:52 +02006893 has_error = 0;
6894 while (p < end && !has_error) {
6895 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6896 an explanation. */
6897 if (!((size_t) p & LONG_PTR_MASK)) {
6898 /* Help register allocation */
6899 register const unsigned char *_p = p;
6900 while (_p < aligned_end) {
6901 unsigned long value = *(unsigned long *) _p;
6902 if (value & ASCII_CHAR_MASK) {
6903 has_error = 1;
6904 break;
6905 }
6906 _p += SIZEOF_LONG;
6907 }
6908 if (_p == end)
6909 break;
6910 if (has_error)
6911 break;
6912 p = _p;
6913 }
6914 if (*p & 0x80) {
6915 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006916 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006917 }
6918 else {
6919 ++p;
6920 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006921 }
Victor Stinner702c7342011-10-05 13:50:52 +02006922 if (!has_error)
6923 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006924
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006925 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006926 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006927 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006928 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006929 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006930 kind = PyUnicode_KIND(v);
6931 data = PyUnicode_DATA(v);
6932 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006933 e = s + size;
6934 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006935 register unsigned char c = (unsigned char)*s;
6936 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006937 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006938 ++s;
6939 }
6940 else {
6941 startinpos = s-starts;
6942 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006943 if (unicode_decode_call_errorhandler(
6944 errors, &errorHandler,
6945 "ascii", "ordinal not in range(128)",
6946 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006947 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006948 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006949 kind = PyUnicode_KIND(v);
6950 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006951 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006952 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006953 if (unicode_resize(&v, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006954 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006955 Py_XDECREF(errorHandler);
6956 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006957 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006958 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006959
Benjamin Peterson29060642009-01-31 22:14:21 +00006960 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006961 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006962 Py_XDECREF(errorHandler);
6963 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006964 return NULL;
6965}
6966
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006967/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006968PyObject *
6969PyUnicode_EncodeASCII(const Py_UNICODE *p,
6970 Py_ssize_t size,
6971 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006972{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006973 PyObject *result;
6974 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6975 if (unicode == NULL)
6976 return NULL;
6977 result = unicode_encode_ucs1(unicode, errors, 128);
6978 Py_DECREF(unicode);
6979 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006980}
6981
Alexander Belopolsky40018472011-02-26 01:02:56 +00006982PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006983_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006984{
6985 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006986 PyErr_BadArgument();
6987 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006988 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006989 if (PyUnicode_READY(unicode) == -1)
6990 return NULL;
6991 /* Fast path: if it is an ASCII-only string, construct bytes object
6992 directly. Else defer to above function to raise the exception. */
6993 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6994 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6995 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006996 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006997}
6998
6999PyObject *
7000PyUnicode_AsASCIIString(PyObject *unicode)
7001{
7002 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007003}
7004
Victor Stinner99b95382011-07-04 14:23:54 +02007005#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007006
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007007/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007008
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007009#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007010#define NEED_RETRY
7011#endif
7012
Victor Stinner3a50e702011-10-18 21:21:00 +02007013#ifndef WC_ERR_INVALID_CHARS
7014# define WC_ERR_INVALID_CHARS 0x0080
7015#endif
7016
7017static char*
7018code_page_name(UINT code_page, PyObject **obj)
7019{
7020 *obj = NULL;
7021 if (code_page == CP_ACP)
7022 return "mbcs";
7023 if (code_page == CP_UTF7)
7024 return "CP_UTF7";
7025 if (code_page == CP_UTF8)
7026 return "CP_UTF8";
7027
7028 *obj = PyBytes_FromFormat("cp%u", code_page);
7029 if (*obj == NULL)
7030 return NULL;
7031 return PyBytes_AS_STRING(*obj);
7032}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007033
Alexander Belopolsky40018472011-02-26 01:02:56 +00007034static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007035is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007036{
7037 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02007038 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007039
Victor Stinner3a50e702011-10-18 21:21:00 +02007040 if (!IsDBCSLeadByteEx(code_page, *curr))
7041 return 0;
7042
7043 prev = CharPrevExA(code_page, s, curr, 0);
7044 if (prev == curr)
7045 return 1;
7046 /* FIXME: This code is limited to "true" double-byte encodings,
7047 as it assumes an incomplete character consists of a single
7048 byte. */
7049 if (curr - prev == 2)
7050 return 1;
7051 if (!IsDBCSLeadByteEx(code_page, *prev))
7052 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007053 return 0;
7054}
7055
Victor Stinner3a50e702011-10-18 21:21:00 +02007056static DWORD
7057decode_code_page_flags(UINT code_page)
7058{
7059 if (code_page == CP_UTF7) {
7060 /* The CP_UTF7 decoder only supports flags=0 */
7061 return 0;
7062 }
7063 else
7064 return MB_ERR_INVALID_CHARS;
7065}
7066
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007067/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007068 * Decode a byte string from a Windows code page into unicode object in strict
7069 * mode.
7070 *
7071 * Returns consumed size if succeed, returns -2 on decode error, or raise a
7072 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007073 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007074static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007075decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007076 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007077 const char *in,
7078 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007079{
Victor Stinner3a50e702011-10-18 21:21:00 +02007080 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007081 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007082 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007083
7084 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007085 assert(insize > 0);
7086 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7087 if (outsize <= 0)
7088 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007089
7090 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007091 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007092 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007093 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007094 if (*v == NULL)
7095 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007096 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007097 }
7098 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007099 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007100 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007101 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007102 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007103 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007104 }
7105
7106 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007107 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7108 if (outsize <= 0)
7109 goto error;
7110 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007111
Victor Stinner3a50e702011-10-18 21:21:00 +02007112error:
7113 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7114 return -2;
7115 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007116 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007117}
7118
Victor Stinner3a50e702011-10-18 21:21:00 +02007119/*
7120 * Decode a byte string from a code page into unicode object with an error
7121 * handler.
7122 *
7123 * Returns consumed size if succeed, or raise a WindowsError or
7124 * UnicodeDecodeError exception and returns -1 on error.
7125 */
7126static int
7127decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007128 PyObject **v,
7129 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007130 const char *errors)
7131{
7132 const char *startin = in;
7133 const char *endin = in + size;
7134 const DWORD flags = decode_code_page_flags(code_page);
7135 /* Ideally, we should get reason from FormatMessage. This is the Windows
7136 2000 English version of the message. */
7137 const char *reason = "No mapping for the Unicode character exists "
7138 "in the target code page.";
7139 /* each step cannot decode more than 1 character, but a character can be
7140 represented as a surrogate pair */
7141 wchar_t buffer[2], *startout, *out;
7142 int insize, outsize;
7143 PyObject *errorHandler = NULL;
7144 PyObject *exc = NULL;
7145 PyObject *encoding_obj = NULL;
7146 char *encoding;
7147 DWORD err;
7148 int ret = -1;
7149
7150 assert(size > 0);
7151
7152 encoding = code_page_name(code_page, &encoding_obj);
7153 if (encoding == NULL)
7154 return -1;
7155
7156 if (errors == NULL || strcmp(errors, "strict") == 0) {
7157 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7158 UnicodeDecodeError. */
7159 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7160 if (exc != NULL) {
7161 PyCodec_StrictErrors(exc);
7162 Py_CLEAR(exc);
7163 }
7164 goto error;
7165 }
7166
7167 if (*v == NULL) {
7168 /* Create unicode object */
7169 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7170 PyErr_NoMemory();
7171 goto error;
7172 }
Victor Stinnerab595942011-12-17 04:59:06 +01007173 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007174 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007175 if (*v == NULL)
7176 goto error;
7177 startout = PyUnicode_AS_UNICODE(*v);
7178 }
7179 else {
7180 /* Extend unicode object */
7181 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7182 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7183 PyErr_NoMemory();
7184 goto error;
7185 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007186 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007187 goto error;
7188 startout = PyUnicode_AS_UNICODE(*v) + n;
7189 }
7190
7191 /* Decode the byte string character per character */
7192 out = startout;
7193 while (in < endin)
7194 {
7195 /* Decode a character */
7196 insize = 1;
7197 do
7198 {
7199 outsize = MultiByteToWideChar(code_page, flags,
7200 in, insize,
7201 buffer, Py_ARRAY_LENGTH(buffer));
7202 if (outsize > 0)
7203 break;
7204 err = GetLastError();
7205 if (err != ERROR_NO_UNICODE_TRANSLATION
7206 && err != ERROR_INSUFFICIENT_BUFFER)
7207 {
7208 PyErr_SetFromWindowsErr(0);
7209 goto error;
7210 }
7211 insize++;
7212 }
7213 /* 4=maximum length of a UTF-8 sequence */
7214 while (insize <= 4 && (in + insize) <= endin);
7215
7216 if (outsize <= 0) {
7217 Py_ssize_t startinpos, endinpos, outpos;
7218
7219 startinpos = in - startin;
7220 endinpos = startinpos + 1;
7221 outpos = out - PyUnicode_AS_UNICODE(*v);
7222 if (unicode_decode_call_errorhandler(
7223 errors, &errorHandler,
7224 encoding, reason,
7225 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007226 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007227 {
7228 goto error;
7229 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007230 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007231 }
7232 else {
7233 in += insize;
7234 memcpy(out, buffer, outsize * sizeof(wchar_t));
7235 out += outsize;
7236 }
7237 }
7238
7239 /* write a NUL character at the end */
7240 *out = 0;
7241
7242 /* Extend unicode object */
7243 outsize = out - startout;
7244 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007245 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007246 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007247 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007248
7249error:
7250 Py_XDECREF(encoding_obj);
7251 Py_XDECREF(errorHandler);
7252 Py_XDECREF(exc);
7253 return ret;
7254}
7255
Victor Stinner3a50e702011-10-18 21:21:00 +02007256static PyObject *
7257decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007258 const char *s, Py_ssize_t size,
7259 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007260{
Victor Stinner76a31a62011-11-04 00:05:13 +01007261 PyObject *v = NULL;
7262 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007263
Victor Stinner3a50e702011-10-18 21:21:00 +02007264 if (code_page < 0) {
7265 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7266 return NULL;
7267 }
7268
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007269 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007270 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007271
Victor Stinner76a31a62011-11-04 00:05:13 +01007272 do
7273 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007274#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007275 if (size > INT_MAX) {
7276 chunk_size = INT_MAX;
7277 final = 0;
7278 done = 0;
7279 }
7280 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007281#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007282 {
7283 chunk_size = (int)size;
7284 final = (consumed == NULL);
7285 done = 1;
7286 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007287
Victor Stinner76a31a62011-11-04 00:05:13 +01007288 /* Skip trailing lead-byte unless 'final' is set */
7289 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7290 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007291
Victor Stinner76a31a62011-11-04 00:05:13 +01007292 if (chunk_size == 0 && done) {
7293 if (v != NULL)
7294 break;
7295 Py_INCREF(unicode_empty);
7296 return unicode_empty;
7297 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007298
Victor Stinner76a31a62011-11-04 00:05:13 +01007299
7300 converted = decode_code_page_strict(code_page, &v,
7301 s, chunk_size);
7302 if (converted == -2)
7303 converted = decode_code_page_errors(code_page, &v,
7304 s, chunk_size,
7305 errors);
7306 assert(converted != 0);
7307
7308 if (converted < 0) {
7309 Py_XDECREF(v);
7310 return NULL;
7311 }
7312
7313 if (consumed)
7314 *consumed += converted;
7315
7316 s += converted;
7317 size -= converted;
7318 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007319
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007320 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007321}
7322
Alexander Belopolsky40018472011-02-26 01:02:56 +00007323PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007324PyUnicode_DecodeCodePageStateful(int code_page,
7325 const char *s,
7326 Py_ssize_t size,
7327 const char *errors,
7328 Py_ssize_t *consumed)
7329{
7330 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7331}
7332
7333PyObject *
7334PyUnicode_DecodeMBCSStateful(const char *s,
7335 Py_ssize_t size,
7336 const char *errors,
7337 Py_ssize_t *consumed)
7338{
7339 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7340}
7341
7342PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007343PyUnicode_DecodeMBCS(const char *s,
7344 Py_ssize_t size,
7345 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007346{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007347 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7348}
7349
Victor Stinner3a50e702011-10-18 21:21:00 +02007350static DWORD
7351encode_code_page_flags(UINT code_page, const char *errors)
7352{
7353 if (code_page == CP_UTF8) {
7354 if (winver.dwMajorVersion >= 6)
7355 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7356 and later */
7357 return WC_ERR_INVALID_CHARS;
7358 else
7359 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7360 return 0;
7361 }
7362 else if (code_page == CP_UTF7) {
7363 /* CP_UTF7 only supports flags=0 */
7364 return 0;
7365 }
7366 else {
7367 if (errors != NULL && strcmp(errors, "replace") == 0)
7368 return 0;
7369 else
7370 return WC_NO_BEST_FIT_CHARS;
7371 }
7372}
7373
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007374/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007375 * Encode a Unicode string to a Windows code page into a byte string in strict
7376 * mode.
7377 *
7378 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7379 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007380 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007381static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007382encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007383 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007384 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007385{
Victor Stinner554f3f02010-06-16 23:33:54 +00007386 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007387 BOOL *pusedDefaultChar = &usedDefaultChar;
7388 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007389 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007390 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007391 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 const DWORD flags = encode_code_page_flags(code_page, NULL);
7393 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007394 /* Create a substring so that we can get the UTF-16 representation
7395 of just the slice under consideration. */
7396 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007397
Martin v. Löwis3d325192011-11-04 18:23:06 +01007398 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007399
Victor Stinner3a50e702011-10-18 21:21:00 +02007400 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007401 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007402 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007403 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007404
Victor Stinner2fc507f2011-11-04 20:06:39 +01007405 substring = PyUnicode_Substring(unicode, offset, offset+len);
7406 if (substring == NULL)
7407 return -1;
7408 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7409 if (p == NULL) {
7410 Py_DECREF(substring);
7411 return -1;
7412 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007413
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007414 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007415 outsize = WideCharToMultiByte(code_page, flags,
7416 p, size,
7417 NULL, 0,
7418 NULL, pusedDefaultChar);
7419 if (outsize <= 0)
7420 goto error;
7421 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007422 if (pusedDefaultChar && *pusedDefaultChar) {
7423 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007424 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007425 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007426
Victor Stinner3a50e702011-10-18 21:21:00 +02007427 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007428 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007429 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007430 if (*outbytes == NULL) {
7431 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007432 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007433 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007434 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007435 }
7436 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007437 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007438 const Py_ssize_t n = PyBytes_Size(*outbytes);
7439 if (outsize > PY_SSIZE_T_MAX - n) {
7440 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007441 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007442 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007443 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007444 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7445 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007446 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007447 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007448 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007449 }
7450
7451 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007452 outsize = WideCharToMultiByte(code_page, flags,
7453 p, size,
7454 out, outsize,
7455 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007456 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007457 if (outsize <= 0)
7458 goto error;
7459 if (pusedDefaultChar && *pusedDefaultChar)
7460 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007461 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007462
Victor Stinner3a50e702011-10-18 21:21:00 +02007463error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007464 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007465 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7466 return -2;
7467 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007468 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007469}
7470
Victor Stinner3a50e702011-10-18 21:21:00 +02007471/*
7472 * Encode a Unicode string to a Windows code page into a byte string using a
7473 * error handler.
7474 *
7475 * Returns consumed characters if succeed, or raise a WindowsError and returns
7476 * -1 on other error.
7477 */
7478static int
7479encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007480 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007481 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007482{
Victor Stinner3a50e702011-10-18 21:21:00 +02007483 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007484 Py_ssize_t pos = unicode_offset;
7485 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007486 /* Ideally, we should get reason from FormatMessage. This is the Windows
7487 2000 English version of the message. */
7488 const char *reason = "invalid character";
7489 /* 4=maximum length of a UTF-8 sequence */
7490 char buffer[4];
7491 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7492 Py_ssize_t outsize;
7493 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007494 PyObject *errorHandler = NULL;
7495 PyObject *exc = NULL;
7496 PyObject *encoding_obj = NULL;
7497 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007498 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007499 PyObject *rep;
7500 int ret = -1;
7501
7502 assert(insize > 0);
7503
7504 encoding = code_page_name(code_page, &encoding_obj);
7505 if (encoding == NULL)
7506 return -1;
7507
7508 if (errors == NULL || strcmp(errors, "strict") == 0) {
7509 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7510 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007511 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007512 if (exc != NULL) {
7513 PyCodec_StrictErrors(exc);
7514 Py_DECREF(exc);
7515 }
7516 Py_XDECREF(encoding_obj);
7517 return -1;
7518 }
7519
7520 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7521 pusedDefaultChar = &usedDefaultChar;
7522 else
7523 pusedDefaultChar = NULL;
7524
7525 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7526 PyErr_NoMemory();
7527 goto error;
7528 }
7529 outsize = insize * Py_ARRAY_LENGTH(buffer);
7530
7531 if (*outbytes == NULL) {
7532 /* Create string object */
7533 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7534 if (*outbytes == NULL)
7535 goto error;
7536 out = PyBytes_AS_STRING(*outbytes);
7537 }
7538 else {
7539 /* Extend string object */
7540 Py_ssize_t n = PyBytes_Size(*outbytes);
7541 if (n > PY_SSIZE_T_MAX - outsize) {
7542 PyErr_NoMemory();
7543 goto error;
7544 }
7545 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7546 goto error;
7547 out = PyBytes_AS_STRING(*outbytes) + n;
7548 }
7549
7550 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007551 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007552 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007553 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7554 wchar_t chars[2];
7555 int charsize;
7556 if (ch < 0x10000) {
7557 chars[0] = (wchar_t)ch;
7558 charsize = 1;
7559 }
7560 else {
7561 ch -= 0x10000;
7562 chars[0] = 0xd800 + (ch >> 10);
7563 chars[1] = 0xdc00 + (ch & 0x3ff);
7564 charsize = 2;
7565 }
7566
Victor Stinner3a50e702011-10-18 21:21:00 +02007567 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007568 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007569 buffer, Py_ARRAY_LENGTH(buffer),
7570 NULL, pusedDefaultChar);
7571 if (outsize > 0) {
7572 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7573 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007574 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007575 memcpy(out, buffer, outsize);
7576 out += outsize;
7577 continue;
7578 }
7579 }
7580 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7581 PyErr_SetFromWindowsErr(0);
7582 goto error;
7583 }
7584
Victor Stinner3a50e702011-10-18 21:21:00 +02007585 rep = unicode_encode_call_errorhandler(
7586 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007587 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007588 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007589 if (rep == NULL)
7590 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007591 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007592
7593 if (PyBytes_Check(rep)) {
7594 outsize = PyBytes_GET_SIZE(rep);
7595 if (outsize != 1) {
7596 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7597 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7598 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7599 Py_DECREF(rep);
7600 goto error;
7601 }
7602 out = PyBytes_AS_STRING(*outbytes) + offset;
7603 }
7604 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7605 out += outsize;
7606 }
7607 else {
7608 Py_ssize_t i;
7609 enum PyUnicode_Kind kind;
7610 void *data;
7611
Benjamin Petersonbac79492012-01-14 13:34:47 -05007612 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007613 Py_DECREF(rep);
7614 goto error;
7615 }
7616
7617 outsize = PyUnicode_GET_LENGTH(rep);
7618 if (outsize != 1) {
7619 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7620 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7621 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7622 Py_DECREF(rep);
7623 goto error;
7624 }
7625 out = PyBytes_AS_STRING(*outbytes) + offset;
7626 }
7627 kind = PyUnicode_KIND(rep);
7628 data = PyUnicode_DATA(rep);
7629 for (i=0; i < outsize; i++) {
7630 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7631 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007632 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007633 encoding, unicode,
7634 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007635 "unable to encode error handler result to ASCII");
7636 Py_DECREF(rep);
7637 goto error;
7638 }
7639 *out = (unsigned char)ch;
7640 out++;
7641 }
7642 }
7643 Py_DECREF(rep);
7644 }
7645 /* write a NUL byte */
7646 *out = 0;
7647 outsize = out - PyBytes_AS_STRING(*outbytes);
7648 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7649 if (_PyBytes_Resize(outbytes, outsize) < 0)
7650 goto error;
7651 ret = 0;
7652
7653error:
7654 Py_XDECREF(encoding_obj);
7655 Py_XDECREF(errorHandler);
7656 Py_XDECREF(exc);
7657 return ret;
7658}
7659
Victor Stinner3a50e702011-10-18 21:21:00 +02007660static PyObject *
7661encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007662 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007663 const char *errors)
7664{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007665 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007666 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007667 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007668 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007669
Benjamin Petersonbac79492012-01-14 13:34:47 -05007670 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007671 return NULL;
7672 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007673
Victor Stinner3a50e702011-10-18 21:21:00 +02007674 if (code_page < 0) {
7675 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7676 return NULL;
7677 }
7678
Martin v. Löwis3d325192011-11-04 18:23:06 +01007679 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007680 return PyBytes_FromStringAndSize(NULL, 0);
7681
Victor Stinner7581cef2011-11-03 22:32:33 +01007682 offset = 0;
7683 do
7684 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007685#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007686 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007687 chunks. */
7688 if (len > INT_MAX/2) {
7689 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007690 done = 0;
7691 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007692 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007693#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007694 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007695 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007696 done = 1;
7697 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007698
Victor Stinner76a31a62011-11-04 00:05:13 +01007699 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007700 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007701 errors);
7702 if (ret == -2)
7703 ret = encode_code_page_errors(code_page, &outbytes,
7704 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007705 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007706 if (ret < 0) {
7707 Py_XDECREF(outbytes);
7708 return NULL;
7709 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007710
Victor Stinner7581cef2011-11-03 22:32:33 +01007711 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007712 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007713 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007714
Victor Stinner3a50e702011-10-18 21:21:00 +02007715 return outbytes;
7716}
7717
7718PyObject *
7719PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7720 Py_ssize_t size,
7721 const char *errors)
7722{
Victor Stinner7581cef2011-11-03 22:32:33 +01007723 PyObject *unicode, *res;
7724 unicode = PyUnicode_FromUnicode(p, size);
7725 if (unicode == NULL)
7726 return NULL;
7727 res = encode_code_page(CP_ACP, unicode, errors);
7728 Py_DECREF(unicode);
7729 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007730}
7731
7732PyObject *
7733PyUnicode_EncodeCodePage(int code_page,
7734 PyObject *unicode,
7735 const char *errors)
7736{
Victor Stinner7581cef2011-11-03 22:32:33 +01007737 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007738}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007739
Alexander Belopolsky40018472011-02-26 01:02:56 +00007740PyObject *
7741PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007742{
7743 if (!PyUnicode_Check(unicode)) {
7744 PyErr_BadArgument();
7745 return NULL;
7746 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007747 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007748}
7749
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007750#undef NEED_RETRY
7751
Victor Stinner99b95382011-07-04 14:23:54 +02007752#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007753
Guido van Rossumd57fd912000-03-10 22:53:23 +00007754/* --- Character Mapping Codec -------------------------------------------- */
7755
Alexander Belopolsky40018472011-02-26 01:02:56 +00007756PyObject *
7757PyUnicode_DecodeCharmap(const char *s,
7758 Py_ssize_t size,
7759 PyObject *mapping,
7760 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007761{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007762 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007763 Py_ssize_t startinpos;
7764 Py_ssize_t endinpos;
7765 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007766 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007767 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007768 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007769 PyObject *errorHandler = NULL;
7770 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007771
Guido van Rossumd57fd912000-03-10 22:53:23 +00007772 /* Default to Latin-1 */
7773 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007774 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007775
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007776 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007777 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007778 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007779 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007780 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007781 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007782 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007783 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007784 Py_ssize_t maplen;
7785 enum PyUnicode_Kind kind;
7786 void *data;
7787 Py_UCS4 x;
7788
Benjamin Petersonbac79492012-01-14 13:34:47 -05007789 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007790 return NULL;
7791
7792 maplen = PyUnicode_GET_LENGTH(mapping);
7793 data = PyUnicode_DATA(mapping);
7794 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007795 while (s < e) {
7796 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007797
Benjamin Peterson29060642009-01-31 22:14:21 +00007798 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007799 x = PyUnicode_READ(kind, data, ch);
7800 else
7801 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007802
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007803 if (x == 0xfffe)
7804 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007805 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007806 startinpos = s-starts;
7807 endinpos = startinpos+1;
7808 if (unicode_decode_call_errorhandler(
7809 errors, &errorHandler,
7810 "charmap", "character maps to <undefined>",
7811 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007812 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007813 goto onError;
7814 }
7815 continue;
7816 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007817
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007818 if (unicode_putchar(&v, &outpos, x) < 0)
7819 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007820 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007821 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007822 }
7823 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007824 while (s < e) {
7825 unsigned char ch = *s;
7826 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007827
Benjamin Peterson29060642009-01-31 22:14:21 +00007828 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7829 w = PyLong_FromLong((long)ch);
7830 if (w == NULL)
7831 goto onError;
7832 x = PyObject_GetItem(mapping, w);
7833 Py_DECREF(w);
7834 if (x == NULL) {
7835 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7836 /* No mapping found means: mapping is undefined. */
7837 PyErr_Clear();
7838 x = Py_None;
7839 Py_INCREF(x);
7840 } else
7841 goto onError;
7842 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007843
Benjamin Peterson29060642009-01-31 22:14:21 +00007844 /* Apply mapping */
7845 if (PyLong_Check(x)) {
7846 long value = PyLong_AS_LONG(x);
7847 if (value < 0 || value > 65535) {
7848 PyErr_SetString(PyExc_TypeError,
7849 "character mapping must be in range(65536)");
7850 Py_DECREF(x);
7851 goto onError;
7852 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007853 if (unicode_putchar(&v, &outpos, value) < 0)
7854 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007855 }
7856 else if (x == Py_None) {
7857 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007858 startinpos = s-starts;
7859 endinpos = startinpos+1;
7860 if (unicode_decode_call_errorhandler(
7861 errors, &errorHandler,
7862 "charmap", "character maps to <undefined>",
7863 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007864 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007865 Py_DECREF(x);
7866 goto onError;
7867 }
7868 Py_DECREF(x);
7869 continue;
7870 }
7871 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007872 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007873
Benjamin Petersonbac79492012-01-14 13:34:47 -05007874 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007875 goto onError;
7876 targetsize = PyUnicode_GET_LENGTH(x);
7877
7878 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007879 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007880 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007881 PyUnicode_READ_CHAR(x, 0)) < 0)
7882 goto onError;
7883 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007884 else if (targetsize > 1) {
7885 /* 1-n mapping */
7886 if (targetsize > extrachars) {
7887 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007888 Py_ssize_t needed = (targetsize - extrachars) + \
7889 (targetsize << 2);
7890 extrachars += needed;
7891 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007892 if (unicode_resize(&v,
7893 PyUnicode_GET_LENGTH(v) + needed) < 0)
7894 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007895 Py_DECREF(x);
7896 goto onError;
7897 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007898 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007899 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7900 goto onError;
7901 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7902 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007903 extrachars -= targetsize;
7904 }
7905 /* 1-0 mapping: skip the character */
7906 }
7907 else {
7908 /* wrong return value */
7909 PyErr_SetString(PyExc_TypeError,
7910 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007911 Py_DECREF(x);
7912 goto onError;
7913 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007914 Py_DECREF(x);
7915 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007916 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007917 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007918 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007919 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007920 Py_XDECREF(errorHandler);
7921 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007922 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007923
Benjamin Peterson29060642009-01-31 22:14:21 +00007924 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007925 Py_XDECREF(errorHandler);
7926 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007927 Py_XDECREF(v);
7928 return NULL;
7929}
7930
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007931/* Charmap encoding: the lookup table */
7932
Alexander Belopolsky40018472011-02-26 01:02:56 +00007933struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007934 PyObject_HEAD
7935 unsigned char level1[32];
7936 int count2, count3;
7937 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007938};
7939
7940static PyObject*
7941encoding_map_size(PyObject *obj, PyObject* args)
7942{
7943 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007944 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007945 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007946}
7947
7948static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007949 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007950 PyDoc_STR("Return the size (in bytes) of this object") },
7951 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007952};
7953
7954static void
7955encoding_map_dealloc(PyObject* o)
7956{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007957 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007958}
7959
7960static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007961 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007962 "EncodingMap", /*tp_name*/
7963 sizeof(struct encoding_map), /*tp_basicsize*/
7964 0, /*tp_itemsize*/
7965 /* methods */
7966 encoding_map_dealloc, /*tp_dealloc*/
7967 0, /*tp_print*/
7968 0, /*tp_getattr*/
7969 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007970 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007971 0, /*tp_repr*/
7972 0, /*tp_as_number*/
7973 0, /*tp_as_sequence*/
7974 0, /*tp_as_mapping*/
7975 0, /*tp_hash*/
7976 0, /*tp_call*/
7977 0, /*tp_str*/
7978 0, /*tp_getattro*/
7979 0, /*tp_setattro*/
7980 0, /*tp_as_buffer*/
7981 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7982 0, /*tp_doc*/
7983 0, /*tp_traverse*/
7984 0, /*tp_clear*/
7985 0, /*tp_richcompare*/
7986 0, /*tp_weaklistoffset*/
7987 0, /*tp_iter*/
7988 0, /*tp_iternext*/
7989 encoding_map_methods, /*tp_methods*/
7990 0, /*tp_members*/
7991 0, /*tp_getset*/
7992 0, /*tp_base*/
7993 0, /*tp_dict*/
7994 0, /*tp_descr_get*/
7995 0, /*tp_descr_set*/
7996 0, /*tp_dictoffset*/
7997 0, /*tp_init*/
7998 0, /*tp_alloc*/
7999 0, /*tp_new*/
8000 0, /*tp_free*/
8001 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008002};
8003
8004PyObject*
8005PyUnicode_BuildEncodingMap(PyObject* string)
8006{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008007 PyObject *result;
8008 struct encoding_map *mresult;
8009 int i;
8010 int need_dict = 0;
8011 unsigned char level1[32];
8012 unsigned char level2[512];
8013 unsigned char *mlevel1, *mlevel2, *mlevel3;
8014 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008015 int kind;
8016 void *data;
8017 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008018
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008019 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008020 PyErr_BadArgument();
8021 return NULL;
8022 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008023 kind = PyUnicode_KIND(string);
8024 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008025 memset(level1, 0xFF, sizeof level1);
8026 memset(level2, 0xFF, sizeof level2);
8027
8028 /* If there isn't a one-to-one mapping of NULL to \0,
8029 or if there are non-BMP characters, we need to use
8030 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008031 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008032 need_dict = 1;
8033 for (i = 1; i < 256; i++) {
8034 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008035 ch = PyUnicode_READ(kind, data, i);
8036 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008037 need_dict = 1;
8038 break;
8039 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008040 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008041 /* unmapped character */
8042 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008043 l1 = ch >> 11;
8044 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008045 if (level1[l1] == 0xFF)
8046 level1[l1] = count2++;
8047 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008048 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008049 }
8050
8051 if (count2 >= 0xFF || count3 >= 0xFF)
8052 need_dict = 1;
8053
8054 if (need_dict) {
8055 PyObject *result = PyDict_New();
8056 PyObject *key, *value;
8057 if (!result)
8058 return NULL;
8059 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008060 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008061 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008062 if (!key || !value)
8063 goto failed1;
8064 if (PyDict_SetItem(result, key, value) == -1)
8065 goto failed1;
8066 Py_DECREF(key);
8067 Py_DECREF(value);
8068 }
8069 return result;
8070 failed1:
8071 Py_XDECREF(key);
8072 Py_XDECREF(value);
8073 Py_DECREF(result);
8074 return NULL;
8075 }
8076
8077 /* Create a three-level trie */
8078 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8079 16*count2 + 128*count3 - 1);
8080 if (!result)
8081 return PyErr_NoMemory();
8082 PyObject_Init(result, &EncodingMapType);
8083 mresult = (struct encoding_map*)result;
8084 mresult->count2 = count2;
8085 mresult->count3 = count3;
8086 mlevel1 = mresult->level1;
8087 mlevel2 = mresult->level23;
8088 mlevel3 = mresult->level23 + 16*count2;
8089 memcpy(mlevel1, level1, 32);
8090 memset(mlevel2, 0xFF, 16*count2);
8091 memset(mlevel3, 0, 128*count3);
8092 count3 = 0;
8093 for (i = 1; i < 256; i++) {
8094 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008095 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008096 /* unmapped character */
8097 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008098 o1 = PyUnicode_READ(kind, data, i)>>11;
8099 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008100 i2 = 16*mlevel1[o1] + o2;
8101 if (mlevel2[i2] == 0xFF)
8102 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008103 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008104 i3 = 128*mlevel2[i2] + o3;
8105 mlevel3[i3] = i;
8106 }
8107 return result;
8108}
8109
8110static int
Victor Stinner22168992011-11-20 17:09:18 +01008111encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008112{
8113 struct encoding_map *map = (struct encoding_map*)mapping;
8114 int l1 = c>>11;
8115 int l2 = (c>>7) & 0xF;
8116 int l3 = c & 0x7F;
8117 int i;
8118
Victor Stinner22168992011-11-20 17:09:18 +01008119 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008120 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008121 if (c == 0)
8122 return 0;
8123 /* level 1*/
8124 i = map->level1[l1];
8125 if (i == 0xFF) {
8126 return -1;
8127 }
8128 /* level 2*/
8129 i = map->level23[16*i+l2];
8130 if (i == 0xFF) {
8131 return -1;
8132 }
8133 /* level 3 */
8134 i = map->level23[16*map->count2 + 128*i + l3];
8135 if (i == 0) {
8136 return -1;
8137 }
8138 return i;
8139}
8140
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008141/* Lookup the character ch in the mapping. If the character
8142 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008143 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008144static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008145charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008146{
Christian Heimes217cfd12007-12-02 14:31:20 +00008147 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008148 PyObject *x;
8149
8150 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008151 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008152 x = PyObject_GetItem(mapping, w);
8153 Py_DECREF(w);
8154 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008155 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8156 /* No mapping found means: mapping is undefined. */
8157 PyErr_Clear();
8158 x = Py_None;
8159 Py_INCREF(x);
8160 return x;
8161 } else
8162 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008163 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008164 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008165 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008166 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008167 long value = PyLong_AS_LONG(x);
8168 if (value < 0 || value > 255) {
8169 PyErr_SetString(PyExc_TypeError,
8170 "character mapping must be in range(256)");
8171 Py_DECREF(x);
8172 return NULL;
8173 }
8174 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008175 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008176 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008177 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008178 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008179 /* wrong return value */
8180 PyErr_Format(PyExc_TypeError,
8181 "character mapping must return integer, bytes or None, not %.400s",
8182 x->ob_type->tp_name);
8183 Py_DECREF(x);
8184 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008185 }
8186}
8187
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008188static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008189charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008190{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008191 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8192 /* exponentially overallocate to minimize reallocations */
8193 if (requiredsize < 2*outsize)
8194 requiredsize = 2*outsize;
8195 if (_PyBytes_Resize(outobj, requiredsize))
8196 return -1;
8197 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008198}
8199
Benjamin Peterson14339b62009-01-31 16:36:08 +00008200typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008201 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008202} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008203/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008204 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008205 space is available. Return a new reference to the object that
8206 was put in the output buffer, or Py_None, if the mapping was undefined
8207 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008208 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008209static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008210charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008211 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008212{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008213 PyObject *rep;
8214 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008215 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008216
Christian Heimes90aa7642007-12-19 02:45:37 +00008217 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008218 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008219 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008220 if (res == -1)
8221 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008222 if (outsize<requiredsize)
8223 if (charmapencode_resize(outobj, outpos, requiredsize))
8224 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008225 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008226 outstart[(*outpos)++] = (char)res;
8227 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008228 }
8229
8230 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008231 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008232 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008233 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008234 Py_DECREF(rep);
8235 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008236 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008237 if (PyLong_Check(rep)) {
8238 Py_ssize_t requiredsize = *outpos+1;
8239 if (outsize<requiredsize)
8240 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8241 Py_DECREF(rep);
8242 return enc_EXCEPTION;
8243 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008244 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008245 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008246 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008247 else {
8248 const char *repchars = PyBytes_AS_STRING(rep);
8249 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8250 Py_ssize_t requiredsize = *outpos+repsize;
8251 if (outsize<requiredsize)
8252 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8253 Py_DECREF(rep);
8254 return enc_EXCEPTION;
8255 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008256 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008257 memcpy(outstart + *outpos, repchars, repsize);
8258 *outpos += repsize;
8259 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008260 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008261 Py_DECREF(rep);
8262 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008263}
8264
8265/* handle an error in PyUnicode_EncodeCharmap
8266 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008267static int
8268charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008269 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008270 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008271 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008272 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008273{
8274 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008275 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008276 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008277 enum PyUnicode_Kind kind;
8278 void *data;
8279 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008280 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008281 Py_ssize_t collstartpos = *inpos;
8282 Py_ssize_t collendpos = *inpos+1;
8283 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008284 char *encoding = "charmap";
8285 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008286 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008287 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008288 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008289
Benjamin Petersonbac79492012-01-14 13:34:47 -05008290 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008291 return -1;
8292 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008293 /* find all unencodable characters */
8294 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008295 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008296 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008297 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008298 val = encoding_map_lookup(ch, mapping);
8299 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008300 break;
8301 ++collendpos;
8302 continue;
8303 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008304
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008305 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8306 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008307 if (rep==NULL)
8308 return -1;
8309 else if (rep!=Py_None) {
8310 Py_DECREF(rep);
8311 break;
8312 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008313 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008314 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008315 }
8316 /* cache callback name lookup
8317 * (if not done yet, i.e. it's the first error) */
8318 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008319 if ((errors==NULL) || (!strcmp(errors, "strict")))
8320 *known_errorHandler = 1;
8321 else if (!strcmp(errors, "replace"))
8322 *known_errorHandler = 2;
8323 else if (!strcmp(errors, "ignore"))
8324 *known_errorHandler = 3;
8325 else if (!strcmp(errors, "xmlcharrefreplace"))
8326 *known_errorHandler = 4;
8327 else
8328 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008329 }
8330 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008331 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008332 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008333 return -1;
8334 case 2: /* replace */
8335 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008336 x = charmapencode_output('?', mapping, res, respos);
8337 if (x==enc_EXCEPTION) {
8338 return -1;
8339 }
8340 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008341 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008342 return -1;
8343 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008344 }
8345 /* fall through */
8346 case 3: /* ignore */
8347 *inpos = collendpos;
8348 break;
8349 case 4: /* xmlcharrefreplace */
8350 /* generate replacement (temporarily (mis)uses p) */
8351 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008352 char buffer[2+29+1+1];
8353 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008354 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008355 for (cp = buffer; *cp; ++cp) {
8356 x = charmapencode_output(*cp, mapping, res, respos);
8357 if (x==enc_EXCEPTION)
8358 return -1;
8359 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008360 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008361 return -1;
8362 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008363 }
8364 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008365 *inpos = collendpos;
8366 break;
8367 default:
8368 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008369 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008370 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008371 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008372 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008373 if (PyBytes_Check(repunicode)) {
8374 /* Directly copy bytes result to output. */
8375 Py_ssize_t outsize = PyBytes_Size(*res);
8376 Py_ssize_t requiredsize;
8377 repsize = PyBytes_Size(repunicode);
8378 requiredsize = *respos + repsize;
8379 if (requiredsize > outsize)
8380 /* Make room for all additional bytes. */
8381 if (charmapencode_resize(res, respos, requiredsize)) {
8382 Py_DECREF(repunicode);
8383 return -1;
8384 }
8385 memcpy(PyBytes_AsString(*res) + *respos,
8386 PyBytes_AsString(repunicode), repsize);
8387 *respos += repsize;
8388 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008389 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008390 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008391 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008392 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008393 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008394 Py_DECREF(repunicode);
8395 return -1;
8396 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008397 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008398 data = PyUnicode_DATA(repunicode);
8399 kind = PyUnicode_KIND(repunicode);
8400 for (index = 0; index < repsize; index++) {
8401 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8402 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008403 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008404 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008405 return -1;
8406 }
8407 else if (x==enc_FAILED) {
8408 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008409 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008410 return -1;
8411 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008412 }
8413 *inpos = newpos;
8414 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008415 }
8416 return 0;
8417}
8418
Alexander Belopolsky40018472011-02-26 01:02:56 +00008419PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008420_PyUnicode_EncodeCharmap(PyObject *unicode,
8421 PyObject *mapping,
8422 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008423{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008424 /* output object */
8425 PyObject *res = NULL;
8426 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008427 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008428 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008429 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008430 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008431 PyObject *errorHandler = NULL;
8432 PyObject *exc = NULL;
8433 /* the following variable is used for caching string comparisons
8434 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8435 * 3=ignore, 4=xmlcharrefreplace */
8436 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008437
Benjamin Petersonbac79492012-01-14 13:34:47 -05008438 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008439 return NULL;
8440 size = PyUnicode_GET_LENGTH(unicode);
8441
Guido van Rossumd57fd912000-03-10 22:53:23 +00008442 /* Default to Latin-1 */
8443 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008444 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008445
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008446 /* allocate enough for a simple encoding without
8447 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008448 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008449 if (res == NULL)
8450 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008451 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008452 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008453
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008454 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008455 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008456 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008457 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008458 if (x==enc_EXCEPTION) /* error */
8459 goto onError;
8460 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008461 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008462 &exc,
8463 &known_errorHandler, &errorHandler, errors,
8464 &res, &respos)) {
8465 goto onError;
8466 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008467 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 else
8469 /* done with this character => adjust input position */
8470 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008471 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008472
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008473 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008474 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008475 if (_PyBytes_Resize(&res, respos) < 0)
8476 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008477
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008478 Py_XDECREF(exc);
8479 Py_XDECREF(errorHandler);
8480 return res;
8481
Benjamin Peterson29060642009-01-31 22:14:21 +00008482 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008483 Py_XDECREF(res);
8484 Py_XDECREF(exc);
8485 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008486 return NULL;
8487}
8488
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008489/* Deprecated */
8490PyObject *
8491PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8492 Py_ssize_t size,
8493 PyObject *mapping,
8494 const char *errors)
8495{
8496 PyObject *result;
8497 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8498 if (unicode == NULL)
8499 return NULL;
8500 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8501 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008502 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008503}
8504
Alexander Belopolsky40018472011-02-26 01:02:56 +00008505PyObject *
8506PyUnicode_AsCharmapString(PyObject *unicode,
8507 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008508{
8509 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008510 PyErr_BadArgument();
8511 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008512 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008513 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008514}
8515
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008516/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008517static void
8518make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008519 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008520 Py_ssize_t startpos, Py_ssize_t endpos,
8521 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008522{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008523 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008524 *exceptionObject = _PyUnicodeTranslateError_Create(
8525 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008526 }
8527 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008528 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8529 goto onError;
8530 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8531 goto onError;
8532 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8533 goto onError;
8534 return;
8535 onError:
8536 Py_DECREF(*exceptionObject);
8537 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008538 }
8539}
8540
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008541/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008542static void
8543raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008544 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008545 Py_ssize_t startpos, Py_ssize_t endpos,
8546 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008547{
8548 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008549 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008550 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008551 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008552}
8553
8554/* error handling callback helper:
8555 build arguments, call the callback and check the arguments,
8556 put the result into newpos and return the replacement string, which
8557 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008558static PyObject *
8559unicode_translate_call_errorhandler(const char *errors,
8560 PyObject **errorHandler,
8561 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008562 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008563 Py_ssize_t startpos, Py_ssize_t endpos,
8564 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008565{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008566 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008567
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008568 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008569 PyObject *restuple;
8570 PyObject *resunicode;
8571
8572 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008573 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008574 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008575 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008576 }
8577
8578 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008579 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008580 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008581 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008582
8583 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008584 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008585 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008586 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008587 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008588 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008589 Py_DECREF(restuple);
8590 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008591 }
8592 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008593 &resunicode, &i_newpos)) {
8594 Py_DECREF(restuple);
8595 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008596 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008597 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008598 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008599 else
8600 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008601 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008602 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8603 Py_DECREF(restuple);
8604 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008605 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008606 Py_INCREF(resunicode);
8607 Py_DECREF(restuple);
8608 return resunicode;
8609}
8610
8611/* Lookup the character ch in the mapping and put the result in result,
8612 which must be decrefed by the caller.
8613 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008614static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008615charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008616{
Christian Heimes217cfd12007-12-02 14:31:20 +00008617 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008618 PyObject *x;
8619
8620 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008621 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008622 x = PyObject_GetItem(mapping, w);
8623 Py_DECREF(w);
8624 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008625 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8626 /* No mapping found means: use 1:1 mapping. */
8627 PyErr_Clear();
8628 *result = NULL;
8629 return 0;
8630 } else
8631 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008632 }
8633 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008634 *result = x;
8635 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008636 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008637 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008638 long value = PyLong_AS_LONG(x);
8639 long max = PyUnicode_GetMax();
8640 if (value < 0 || value > max) {
8641 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008642 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008643 Py_DECREF(x);
8644 return -1;
8645 }
8646 *result = x;
8647 return 0;
8648 }
8649 else if (PyUnicode_Check(x)) {
8650 *result = x;
8651 return 0;
8652 }
8653 else {
8654 /* wrong return value */
8655 PyErr_SetString(PyExc_TypeError,
8656 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008657 Py_DECREF(x);
8658 return -1;
8659 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008660}
8661/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008662 if not reallocate and adjust various state variables.
8663 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008664static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008665charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008666 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008667{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008668 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008669 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008670 /* exponentially overallocate to minimize reallocations */
8671 if (requiredsize < 2 * oldsize)
8672 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008673 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8674 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008675 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008676 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008677 }
8678 return 0;
8679}
8680/* lookup the character, put the result in the output string and adjust
8681 various state variables. Return a new reference to the object that
8682 was put in the output buffer in *result, or Py_None, if the mapping was
8683 undefined (in which case no character was written).
8684 The called must decref result.
8685 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008686static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008687charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8688 PyObject *mapping, Py_UCS4 **output,
8689 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008690 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008691{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008692 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8693 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008694 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008695 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008696 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008697 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008698 }
8699 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008700 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008701 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008703 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008704 }
8705 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008706 Py_ssize_t repsize;
8707 if (PyUnicode_READY(*res) == -1)
8708 return -1;
8709 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008710 if (repsize==1) {
8711 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008712 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008713 }
8714 else if (repsize!=0) {
8715 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008716 Py_ssize_t requiredsize = *opos +
8717 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008718 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008719 Py_ssize_t i;
8720 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008721 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008722 for(i = 0; i < repsize; i++)
8723 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008724 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008725 }
8726 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008727 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008728 return 0;
8729}
8730
Alexander Belopolsky40018472011-02-26 01:02:56 +00008731PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008732_PyUnicode_TranslateCharmap(PyObject *input,
8733 PyObject *mapping,
8734 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008735{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008736 /* input object */
8737 char *idata;
8738 Py_ssize_t size, i;
8739 int kind;
8740 /* output buffer */
8741 Py_UCS4 *output = NULL;
8742 Py_ssize_t osize;
8743 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008744 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008745 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008746 char *reason = "character maps to <undefined>";
8747 PyObject *errorHandler = NULL;
8748 PyObject *exc = NULL;
8749 /* the following variable is used for caching string comparisons
8750 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8751 * 3=ignore, 4=xmlcharrefreplace */
8752 int known_errorHandler = -1;
8753
Guido van Rossumd57fd912000-03-10 22:53:23 +00008754 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008755 PyErr_BadArgument();
8756 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008757 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008758
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008759 if (PyUnicode_READY(input) == -1)
8760 return NULL;
8761 idata = (char*)PyUnicode_DATA(input);
8762 kind = PyUnicode_KIND(input);
8763 size = PyUnicode_GET_LENGTH(input);
8764 i = 0;
8765
8766 if (size == 0) {
8767 Py_INCREF(input);
8768 return input;
8769 }
8770
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008771 /* allocate enough for a simple 1:1 translation without
8772 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008773 osize = size;
8774 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8775 opos = 0;
8776 if (output == NULL) {
8777 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008778 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008779 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008780
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008781 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008782 /* try to encode it */
8783 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008784 if (charmaptranslate_output(input, i, mapping,
8785 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008786 Py_XDECREF(x);
8787 goto onError;
8788 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008789 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008790 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008791 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008792 else { /* untranslatable character */
8793 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8794 Py_ssize_t repsize;
8795 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008796 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008797 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008798 Py_ssize_t collstart = i;
8799 Py_ssize_t collend = i+1;
8800 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008801
Benjamin Peterson29060642009-01-31 22:14:21 +00008802 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008803 while (collend < size) {
8804 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008805 goto onError;
8806 Py_XDECREF(x);
8807 if (x!=Py_None)
8808 break;
8809 ++collend;
8810 }
8811 /* cache callback name lookup
8812 * (if not done yet, i.e. it's the first error) */
8813 if (known_errorHandler==-1) {
8814 if ((errors==NULL) || (!strcmp(errors, "strict")))
8815 known_errorHandler = 1;
8816 else if (!strcmp(errors, "replace"))
8817 known_errorHandler = 2;
8818 else if (!strcmp(errors, "ignore"))
8819 known_errorHandler = 3;
8820 else if (!strcmp(errors, "xmlcharrefreplace"))
8821 known_errorHandler = 4;
8822 else
8823 known_errorHandler = 0;
8824 }
8825 switch (known_errorHandler) {
8826 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008827 raise_translate_exception(&exc, input, collstart,
8828 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008829 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008830 case 2: /* replace */
8831 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008832 for (coll = collstart; coll<collend; coll++)
8833 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008834 /* fall through */
8835 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008836 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008837 break;
8838 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008839 /* generate replacement (temporarily (mis)uses i) */
8840 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008841 char buffer[2+29+1+1];
8842 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008843 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8844 if (charmaptranslate_makespace(&output, &osize,
8845 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008846 goto onError;
8847 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008848 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008849 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008850 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008851 break;
8852 default:
8853 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008854 reason, input, &exc,
8855 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008856 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008857 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008858 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008859 Py_DECREF(repunicode);
8860 goto onError;
8861 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008862 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008863 repsize = PyUnicode_GET_LENGTH(repunicode);
8864 if (charmaptranslate_makespace(&output, &osize,
8865 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008866 Py_DECREF(repunicode);
8867 goto onError;
8868 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008869 for (uni2 = 0; repsize-->0; ++uni2)
8870 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8871 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008872 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008873 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008874 }
8875 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008876 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8877 if (!res)
8878 goto onError;
8879 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008880 Py_XDECREF(exc);
8881 Py_XDECREF(errorHandler);
8882 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008883
Benjamin Peterson29060642009-01-31 22:14:21 +00008884 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008885 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008886 Py_XDECREF(exc);
8887 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008888 return NULL;
8889}
8890
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008891/* Deprecated. Use PyUnicode_Translate instead. */
8892PyObject *
8893PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8894 Py_ssize_t size,
8895 PyObject *mapping,
8896 const char *errors)
8897{
8898 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8899 if (!unicode)
8900 return NULL;
8901 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8902}
8903
Alexander Belopolsky40018472011-02-26 01:02:56 +00008904PyObject *
8905PyUnicode_Translate(PyObject *str,
8906 PyObject *mapping,
8907 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008908{
8909 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008910
Guido van Rossumd57fd912000-03-10 22:53:23 +00008911 str = PyUnicode_FromObject(str);
8912 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008913 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008914 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008915 Py_DECREF(str);
8916 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008917
Benjamin Peterson29060642009-01-31 22:14:21 +00008918 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008919 Py_XDECREF(str);
8920 return NULL;
8921}
Tim Petersced69f82003-09-16 20:30:58 +00008922
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008923static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008924fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008925{
8926 /* No need to call PyUnicode_READY(self) because this function is only
8927 called as a callback from fixup() which does it already. */
8928 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8929 const int kind = PyUnicode_KIND(self);
8930 void *data = PyUnicode_DATA(self);
8931 Py_UCS4 maxchar = 0, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008932 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008933 Py_ssize_t i;
8934
8935 for (i = 0; i < len; ++i) {
8936 ch = PyUnicode_READ(kind, data, i);
8937 fixed = 0;
8938 if (ch > 127) {
8939 if (Py_UNICODE_ISSPACE(ch))
8940 fixed = ' ';
8941 else {
8942 const int decimal = Py_UNICODE_TODECIMAL(ch);
8943 if (decimal >= 0)
8944 fixed = '0' + decimal;
8945 }
8946 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008947 modified = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008948 if (fixed > maxchar)
8949 maxchar = fixed;
8950 PyUnicode_WRITE(kind, data, i, fixed);
8951 }
8952 else if (ch > maxchar)
8953 maxchar = ch;
8954 }
8955 else if (ch > maxchar)
8956 maxchar = ch;
8957 }
8958
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008959 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008960}
8961
8962PyObject *
8963_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8964{
8965 if (!PyUnicode_Check(unicode)) {
8966 PyErr_BadInternalCall();
8967 return NULL;
8968 }
8969 if (PyUnicode_READY(unicode) == -1)
8970 return NULL;
8971 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8972 /* If the string is already ASCII, just return the same string */
8973 Py_INCREF(unicode);
8974 return unicode;
8975 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008976 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008977}
8978
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008979PyObject *
8980PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8981 Py_ssize_t length)
8982{
Victor Stinnerf0124502011-11-21 23:12:56 +01008983 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008984 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008985 Py_UCS4 maxchar;
8986 enum PyUnicode_Kind kind;
8987 void *data;
8988
Victor Stinner99d7ad02012-02-22 13:37:39 +01008989 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008990 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008991 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008992 if (ch > 127) {
8993 int decimal = Py_UNICODE_TODECIMAL(ch);
8994 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008995 ch = '0' + decimal;
Victor Stinner99d7ad02012-02-22 13:37:39 +01008996 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008997 }
8998 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008999
9000 /* Copy to a new string */
9001 decimal = PyUnicode_New(length, maxchar);
9002 if (decimal == NULL)
9003 return decimal;
9004 kind = PyUnicode_KIND(decimal);
9005 data = PyUnicode_DATA(decimal);
9006 /* Iterate over code points */
9007 for (i = 0; i < length; i++) {
9008 Py_UNICODE ch = s[i];
9009 if (ch > 127) {
9010 int decimal = Py_UNICODE_TODECIMAL(ch);
9011 if (decimal >= 0)
9012 ch = '0' + decimal;
9013 }
9014 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009015 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009016 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009017}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009018/* --- Decimal Encoder ---------------------------------------------------- */
9019
Alexander Belopolsky40018472011-02-26 01:02:56 +00009020int
9021PyUnicode_EncodeDecimal(Py_UNICODE *s,
9022 Py_ssize_t length,
9023 char *output,
9024 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009025{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009026 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009027 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009028 enum PyUnicode_Kind kind;
9029 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009030
9031 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009032 PyErr_BadArgument();
9033 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009034 }
9035
Victor Stinner42bf7752011-11-21 22:52:58 +01009036 unicode = PyUnicode_FromUnicode(s, length);
9037 if (unicode == NULL)
9038 return -1;
9039
Benjamin Petersonbac79492012-01-14 13:34:47 -05009040 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009041 Py_DECREF(unicode);
9042 return -1;
9043 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009044 kind = PyUnicode_KIND(unicode);
9045 data = PyUnicode_DATA(unicode);
9046
Victor Stinnerb84d7232011-11-22 01:50:07 +01009047 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009048 PyObject *exc;
9049 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009050 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009051 Py_ssize_t startpos;
9052
9053 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009054
Benjamin Peterson29060642009-01-31 22:14:21 +00009055 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009056 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009057 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009058 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009059 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009060 decimal = Py_UNICODE_TODECIMAL(ch);
9061 if (decimal >= 0) {
9062 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009063 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009064 continue;
9065 }
9066 if (0 < ch && ch < 256) {
9067 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009068 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009069 continue;
9070 }
Victor Stinner6345be92011-11-25 20:09:01 +01009071
Victor Stinner42bf7752011-11-21 22:52:58 +01009072 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009073 exc = NULL;
9074 raise_encode_exception(&exc, "decimal", unicode,
9075 startpos, startpos+1,
9076 "invalid decimal Unicode string");
9077 Py_XDECREF(exc);
9078 Py_DECREF(unicode);
9079 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009080 }
9081 /* 0-terminate the output string */
9082 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009083 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009084 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009085}
9086
Guido van Rossumd57fd912000-03-10 22:53:23 +00009087/* --- Helpers ------------------------------------------------------------ */
9088
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009089static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009090any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009091 Py_ssize_t start,
9092 Py_ssize_t end)
9093{
9094 int kind1, kind2, kind;
9095 void *buf1, *buf2;
9096 Py_ssize_t len1, len2, result;
9097
9098 kind1 = PyUnicode_KIND(s1);
9099 kind2 = PyUnicode_KIND(s2);
9100 kind = kind1 > kind2 ? kind1 : kind2;
9101 buf1 = PyUnicode_DATA(s1);
9102 buf2 = PyUnicode_DATA(s2);
9103 if (kind1 != kind)
9104 buf1 = _PyUnicode_AsKind(s1, kind);
9105 if (!buf1)
9106 return -2;
9107 if (kind2 != kind)
9108 buf2 = _PyUnicode_AsKind(s2, kind);
9109 if (!buf2) {
9110 if (kind1 != kind) PyMem_Free(buf1);
9111 return -2;
9112 }
9113 len1 = PyUnicode_GET_LENGTH(s1);
9114 len2 = PyUnicode_GET_LENGTH(s2);
9115
Victor Stinner794d5672011-10-10 03:21:36 +02009116 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009117 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009118 case PyUnicode_1BYTE_KIND:
9119 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9120 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9121 else
9122 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9123 break;
9124 case PyUnicode_2BYTE_KIND:
9125 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9126 break;
9127 case PyUnicode_4BYTE_KIND:
9128 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9129 break;
9130 default:
9131 assert(0); result = -2;
9132 }
9133 }
9134 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009135 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009136 case PyUnicode_1BYTE_KIND:
9137 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9138 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9139 else
9140 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9141 break;
9142 case PyUnicode_2BYTE_KIND:
9143 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9144 break;
9145 case PyUnicode_4BYTE_KIND:
9146 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9147 break;
9148 default:
9149 assert(0); result = -2;
9150 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009151 }
9152
9153 if (kind1 != kind)
9154 PyMem_Free(buf1);
9155 if (kind2 != kind)
9156 PyMem_Free(buf2);
9157
9158 return result;
9159}
9160
9161Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009162_PyUnicode_InsertThousandsGrouping(
9163 PyObject *unicode, Py_ssize_t index,
9164 Py_ssize_t n_buffer,
9165 void *digits, Py_ssize_t n_digits,
9166 Py_ssize_t min_width,
9167 const char *grouping, PyObject *thousands_sep,
9168 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009169{
Victor Stinner41a863c2012-02-24 00:37:51 +01009170 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009171 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009172 Py_ssize_t thousands_sep_len;
9173 Py_ssize_t len;
9174
9175 if (unicode != NULL) {
9176 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009177 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009178 }
9179 else {
9180 kind = PyUnicode_1BYTE_KIND;
9181 data = NULL;
9182 }
9183 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9184 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9185 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9186 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009187 if (thousands_sep_kind < kind) {
9188 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9189 if (!thousands_sep_data)
9190 return -1;
9191 }
9192 else {
9193 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9194 if (!data)
9195 return -1;
9196 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009197 }
9198
Benjamin Petersonead6b532011-12-20 17:23:42 -06009199 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009200 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009201 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009202 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009203 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009204 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009205 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009206 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009207 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009208 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009209 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009210 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009211 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009212 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009213 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009214 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009215 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009216 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009217 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009218 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009219 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009220 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009221 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009222 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009223 break;
9224 default:
9225 assert(0);
9226 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009227 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009228 if (unicode != NULL && thousands_sep_kind != kind) {
9229 if (thousands_sep_kind < kind)
9230 PyMem_Free(thousands_sep_data);
9231 else
9232 PyMem_Free(data);
9233 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009234 if (unicode == NULL) {
9235 *maxchar = 127;
9236 if (len != n_digits) {
9237 *maxchar = Py_MAX(*maxchar,
9238 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
9239 }
9240 }
9241 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009242}
9243
9244
Thomas Wouters477c8d52006-05-27 19:21:47 +00009245/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009246#define ADJUST_INDICES(start, end, len) \
9247 if (end > len) \
9248 end = len; \
9249 else if (end < 0) { \
9250 end += len; \
9251 if (end < 0) \
9252 end = 0; \
9253 } \
9254 if (start < 0) { \
9255 start += len; \
9256 if (start < 0) \
9257 start = 0; \
9258 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009259
Alexander Belopolsky40018472011-02-26 01:02:56 +00009260Py_ssize_t
9261PyUnicode_Count(PyObject *str,
9262 PyObject *substr,
9263 Py_ssize_t start,
9264 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009265{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009266 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009267 PyObject* str_obj;
9268 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009269 int kind1, kind2, kind;
9270 void *buf1 = NULL, *buf2 = NULL;
9271 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009272
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009273 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009274 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009275 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009276 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009277 if (!sub_obj) {
9278 Py_DECREF(str_obj);
9279 return -1;
9280 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009281 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009282 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009283 Py_DECREF(str_obj);
9284 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009285 }
Tim Petersced69f82003-09-16 20:30:58 +00009286
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009287 kind1 = PyUnicode_KIND(str_obj);
9288 kind2 = PyUnicode_KIND(sub_obj);
9289 kind = kind1 > kind2 ? kind1 : kind2;
9290 buf1 = PyUnicode_DATA(str_obj);
9291 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009292 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009293 if (!buf1)
9294 goto onError;
9295 buf2 = PyUnicode_DATA(sub_obj);
9296 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009297 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009298 if (!buf2)
9299 goto onError;
9300 len1 = PyUnicode_GET_LENGTH(str_obj);
9301 len2 = PyUnicode_GET_LENGTH(sub_obj);
9302
9303 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009304 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009305 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009306 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9307 result = asciilib_count(
9308 ((Py_UCS1*)buf1) + start, end - start,
9309 buf2, len2, PY_SSIZE_T_MAX
9310 );
9311 else
9312 result = ucs1lib_count(
9313 ((Py_UCS1*)buf1) + start, end - start,
9314 buf2, len2, PY_SSIZE_T_MAX
9315 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009316 break;
9317 case PyUnicode_2BYTE_KIND:
9318 result = ucs2lib_count(
9319 ((Py_UCS2*)buf1) + start, end - start,
9320 buf2, len2, PY_SSIZE_T_MAX
9321 );
9322 break;
9323 case PyUnicode_4BYTE_KIND:
9324 result = ucs4lib_count(
9325 ((Py_UCS4*)buf1) + start, end - start,
9326 buf2, len2, PY_SSIZE_T_MAX
9327 );
9328 break;
9329 default:
9330 assert(0); result = 0;
9331 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009332
9333 Py_DECREF(sub_obj);
9334 Py_DECREF(str_obj);
9335
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009336 if (kind1 != kind)
9337 PyMem_Free(buf1);
9338 if (kind2 != kind)
9339 PyMem_Free(buf2);
9340
Guido van Rossumd57fd912000-03-10 22:53:23 +00009341 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009342 onError:
9343 Py_DECREF(sub_obj);
9344 Py_DECREF(str_obj);
9345 if (kind1 != kind && buf1)
9346 PyMem_Free(buf1);
9347 if (kind2 != kind && buf2)
9348 PyMem_Free(buf2);
9349 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009350}
9351
Alexander Belopolsky40018472011-02-26 01:02:56 +00009352Py_ssize_t
9353PyUnicode_Find(PyObject *str,
9354 PyObject *sub,
9355 Py_ssize_t start,
9356 Py_ssize_t end,
9357 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009358{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009359 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009360
Guido van Rossumd57fd912000-03-10 22:53:23 +00009361 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009362 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009363 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009364 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009365 if (!sub) {
9366 Py_DECREF(str);
9367 return -2;
9368 }
9369 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9370 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009371 Py_DECREF(str);
9372 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009373 }
Tim Petersced69f82003-09-16 20:30:58 +00009374
Victor Stinner794d5672011-10-10 03:21:36 +02009375 result = any_find_slice(direction,
9376 str, sub, start, end
9377 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009378
Guido van Rossumd57fd912000-03-10 22:53:23 +00009379 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009380 Py_DECREF(sub);
9381
Guido van Rossumd57fd912000-03-10 22:53:23 +00009382 return result;
9383}
9384
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009385Py_ssize_t
9386PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9387 Py_ssize_t start, Py_ssize_t end,
9388 int direction)
9389{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009390 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009391 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009392 if (PyUnicode_READY(str) == -1)
9393 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009394 if (start < 0 || end < 0) {
9395 PyErr_SetString(PyExc_IndexError, "string index out of range");
9396 return -2;
9397 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009398 if (end > PyUnicode_GET_LENGTH(str))
9399 end = PyUnicode_GET_LENGTH(str);
9400 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009401 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9402 kind, end-start, ch, direction);
9403 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009404 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009405 else
9406 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009407}
9408
Alexander Belopolsky40018472011-02-26 01:02:56 +00009409static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009410tailmatch(PyObject *self,
9411 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009412 Py_ssize_t start,
9413 Py_ssize_t end,
9414 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009415{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009416 int kind_self;
9417 int kind_sub;
9418 void *data_self;
9419 void *data_sub;
9420 Py_ssize_t offset;
9421 Py_ssize_t i;
9422 Py_ssize_t end_sub;
9423
9424 if (PyUnicode_READY(self) == -1 ||
9425 PyUnicode_READY(substring) == -1)
9426 return 0;
9427
9428 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009429 return 1;
9430
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009431 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9432 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009433 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009434 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009435
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009436 kind_self = PyUnicode_KIND(self);
9437 data_self = PyUnicode_DATA(self);
9438 kind_sub = PyUnicode_KIND(substring);
9439 data_sub = PyUnicode_DATA(substring);
9440 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9441
9442 if (direction > 0)
9443 offset = end;
9444 else
9445 offset = start;
9446
9447 if (PyUnicode_READ(kind_self, data_self, offset) ==
9448 PyUnicode_READ(kind_sub, data_sub, 0) &&
9449 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9450 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9451 /* If both are of the same kind, memcmp is sufficient */
9452 if (kind_self == kind_sub) {
9453 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009454 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009455 data_sub,
9456 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009457 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009458 }
9459 /* otherwise we have to compare each character by first accesing it */
9460 else {
9461 /* We do not need to compare 0 and len(substring)-1 because
9462 the if statement above ensured already that they are equal
9463 when we end up here. */
9464 // TODO: honor direction and do a forward or backwards search
9465 for (i = 1; i < end_sub; ++i) {
9466 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9467 PyUnicode_READ(kind_sub, data_sub, i))
9468 return 0;
9469 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009470 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009471 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009472 }
9473
9474 return 0;
9475}
9476
Alexander Belopolsky40018472011-02-26 01:02:56 +00009477Py_ssize_t
9478PyUnicode_Tailmatch(PyObject *str,
9479 PyObject *substr,
9480 Py_ssize_t start,
9481 Py_ssize_t end,
9482 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009483{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009484 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009485
Guido van Rossumd57fd912000-03-10 22:53:23 +00009486 str = PyUnicode_FromObject(str);
9487 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009488 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009489 substr = PyUnicode_FromObject(substr);
9490 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009491 Py_DECREF(str);
9492 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009493 }
Tim Petersced69f82003-09-16 20:30:58 +00009494
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009495 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009496 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009497 Py_DECREF(str);
9498 Py_DECREF(substr);
9499 return result;
9500}
9501
Guido van Rossumd57fd912000-03-10 22:53:23 +00009502/* Apply fixfct filter to the Unicode object self and return a
9503 reference to the modified object */
9504
Alexander Belopolsky40018472011-02-26 01:02:56 +00009505static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009506fixup(PyObject *self,
9507 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009508{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009509 PyObject *u;
9510 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009511 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009512
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009513 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009514 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009515 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009516 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009518 /* fix functions return the new maximum character in a string,
9519 if the kind of the resulting unicode object does not change,
9520 everything is fine. Otherwise we need to change the string kind
9521 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009522 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009523
9524 if (maxchar_new == 0) {
9525 /* no changes */;
9526 if (PyUnicode_CheckExact(self)) {
9527 Py_DECREF(u);
9528 Py_INCREF(self);
9529 return self;
9530 }
9531 else
9532 return u;
9533 }
9534
9535 if (maxchar_new <= 127)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009536 maxchar_new = 127;
9537 else if (maxchar_new <= 255)
9538 maxchar_new = 255;
9539 else if (maxchar_new <= 65535)
9540 maxchar_new = 65535;
9541 else
Victor Stinner8faf8212011-12-08 22:14:11 +01009542 maxchar_new = MAX_UNICODE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009543
Victor Stinnereaab6042011-12-11 22:22:39 +01009544 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009545 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009546
9547 /* In case the maximum character changed, we need to
9548 convert the string to the new category. */
9549 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9550 if (v == NULL) {
9551 Py_DECREF(u);
9552 return NULL;
9553 }
9554 if (maxchar_new > maxchar_old) {
9555 /* If the maxchar increased so that the kind changed, not all
9556 characters are representable anymore and we need to fix the
9557 string again. This only happens in very few cases. */
9558 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
9559 maxchar_old = fixfct(v);
9560 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009561 }
9562 else {
Victor Stinnereaab6042011-12-11 22:22:39 +01009563 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009564 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009565 Py_DECREF(u);
9566 assert(_PyUnicode_CheckConsistency(v, 1));
9567 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009568}
9569
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009570static PyObject *
9571ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009572{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009573 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9574 char *resdata, *data = PyUnicode_DATA(self);
9575 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009576
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009577 res = PyUnicode_New(len, 127);
9578 if (res == NULL)
9579 return NULL;
9580 resdata = PyUnicode_DATA(res);
9581 if (lower)
9582 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009583 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009584 _Py_bytes_upper(resdata, data, len);
9585 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009586}
9587
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009588static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009589handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009590{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009591 Py_ssize_t j;
9592 int final_sigma;
9593 Py_UCS4 c;
9594 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009595
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009596 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9597
9598 where ! is a negation and \p{xxx} is a character with property xxx.
9599 */
9600 for (j = i - 1; j >= 0; j--) {
9601 c = PyUnicode_READ(kind, data, j);
9602 if (!_PyUnicode_IsCaseIgnorable(c))
9603 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009604 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009605 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9606 if (final_sigma) {
9607 for (j = i + 1; j < length; j++) {
9608 c = PyUnicode_READ(kind, data, j);
9609 if (!_PyUnicode_IsCaseIgnorable(c))
9610 break;
9611 }
9612 final_sigma = j == length || !_PyUnicode_IsCased(c);
9613 }
9614 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009615}
9616
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009617static int
9618lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9619 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009620{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009621 /* Obscure special case. */
9622 if (c == 0x3A3) {
9623 mapped[0] = handle_capital_sigma(kind, data, length, i);
9624 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009625 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009626 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009627}
9628
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009629static Py_ssize_t
9630do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009631{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009632 Py_ssize_t i, k = 0;
9633 int n_res, j;
9634 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009635
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009636 c = PyUnicode_READ(kind, data, 0);
9637 n_res = _PyUnicode_ToUpperFull(c, mapped);
9638 for (j = 0; j < n_res; j++) {
9639 if (mapped[j] > *maxchar)
9640 *maxchar = mapped[j];
9641 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009642 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009643 for (i = 1; i < length; i++) {
9644 c = PyUnicode_READ(kind, data, i);
9645 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9646 for (j = 0; j < n_res; j++) {
9647 if (mapped[j] > *maxchar)
9648 *maxchar = mapped[j];
9649 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009650 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009651 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009652 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009653}
9654
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009655static Py_ssize_t
9656do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9657 Py_ssize_t i, k = 0;
9658
9659 for (i = 0; i < length; i++) {
9660 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9661 int n_res, j;
9662 if (Py_UNICODE_ISUPPER(c)) {
9663 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9664 }
9665 else if (Py_UNICODE_ISLOWER(c)) {
9666 n_res = _PyUnicode_ToUpperFull(c, mapped);
9667 }
9668 else {
9669 n_res = 1;
9670 mapped[0] = c;
9671 }
9672 for (j = 0; j < n_res; j++) {
9673 if (mapped[j] > *maxchar)
9674 *maxchar = mapped[j];
9675 res[k++] = mapped[j];
9676 }
9677 }
9678 return k;
9679}
9680
9681static Py_ssize_t
9682do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9683 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009684{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009685 Py_ssize_t i, k = 0;
9686
9687 for (i = 0; i < length; i++) {
9688 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9689 int n_res, j;
9690 if (lower)
9691 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9692 else
9693 n_res = _PyUnicode_ToUpperFull(c, mapped);
9694 for (j = 0; j < n_res; j++) {
9695 if (mapped[j] > *maxchar)
9696 *maxchar = mapped[j];
9697 res[k++] = mapped[j];
9698 }
9699 }
9700 return k;
9701}
9702
9703static Py_ssize_t
9704do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9705{
9706 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9707}
9708
9709static Py_ssize_t
9710do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9711{
9712 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9713}
9714
Benjamin Petersone51757f2012-01-12 21:10:29 -05009715static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009716do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9717{
9718 Py_ssize_t i, k = 0;
9719
9720 for (i = 0; i < length; i++) {
9721 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9722 Py_UCS4 mapped[3];
9723 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9724 for (j = 0; j < n_res; j++) {
9725 if (mapped[j] > *maxchar)
9726 *maxchar = mapped[j];
9727 res[k++] = mapped[j];
9728 }
9729 }
9730 return k;
9731}
9732
9733static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009734do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9735{
9736 Py_ssize_t i, k = 0;
9737 int previous_is_cased;
9738
9739 previous_is_cased = 0;
9740 for (i = 0; i < length; i++) {
9741 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9742 Py_UCS4 mapped[3];
9743 int n_res, j;
9744
9745 if (previous_is_cased)
9746 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9747 else
9748 n_res = _PyUnicode_ToTitleFull(c, mapped);
9749
9750 for (j = 0; j < n_res; j++) {
9751 if (mapped[j] > *maxchar)
9752 *maxchar = mapped[j];
9753 res[k++] = mapped[j];
9754 }
9755
9756 previous_is_cased = _PyUnicode_IsCased(c);
9757 }
9758 return k;
9759}
9760
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009761static PyObject *
9762case_operation(PyObject *self,
9763 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9764{
9765 PyObject *res = NULL;
9766 Py_ssize_t length, newlength = 0;
9767 int kind, outkind;
9768 void *data, *outdata;
9769 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9770
Benjamin Petersoneea48462012-01-16 14:28:50 -05009771 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009772
9773 kind = PyUnicode_KIND(self);
9774 data = PyUnicode_DATA(self);
9775 length = PyUnicode_GET_LENGTH(self);
9776 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9777 if (tmp == NULL)
9778 return PyErr_NoMemory();
9779 newlength = perform(kind, data, length, tmp, &maxchar);
9780 res = PyUnicode_New(newlength, maxchar);
9781 if (res == NULL)
9782 goto leave;
9783 tmpend = tmp + newlength;
9784 outdata = PyUnicode_DATA(res);
9785 outkind = PyUnicode_KIND(res);
9786 switch (outkind) {
9787 case PyUnicode_1BYTE_KIND:
9788 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9789 break;
9790 case PyUnicode_2BYTE_KIND:
9791 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9792 break;
9793 case PyUnicode_4BYTE_KIND:
9794 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9795 break;
9796 default:
9797 assert(0);
9798 break;
9799 }
9800 leave:
9801 PyMem_FREE(tmp);
9802 return res;
9803}
9804
Tim Peters8ce9f162004-08-27 01:49:32 +00009805PyObject *
9806PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009807{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009808 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009809 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009810 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009811 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009812 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9813 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009814 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009815 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009816 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009817 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009818 int use_memcpy;
9819 unsigned char *res_data = NULL, *sep_data = NULL;
9820 PyObject *last_obj;
9821 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009822
Tim Peters05eba1f2004-08-27 21:32:02 +00009823 fseq = PySequence_Fast(seq, "");
9824 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009825 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009826 }
9827
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009828 /* NOTE: the following code can't call back into Python code,
9829 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009830 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009831
Tim Peters05eba1f2004-08-27 21:32:02 +00009832 seqlen = PySequence_Fast_GET_SIZE(fseq);
9833 /* If empty sequence, return u"". */
9834 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009835 Py_DECREF(fseq);
9836 Py_INCREF(unicode_empty);
9837 res = unicode_empty;
9838 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009839 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009840
Tim Peters05eba1f2004-08-27 21:32:02 +00009841 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009842 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009843 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009844 if (seqlen == 1) {
9845 if (PyUnicode_CheckExact(items[0])) {
9846 res = items[0];
9847 Py_INCREF(res);
9848 Py_DECREF(fseq);
9849 return res;
9850 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009851 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009852 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009853 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009854 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009855 /* Set up sep and seplen */
9856 if (separator == NULL) {
9857 /* fall back to a blank space separator */
9858 sep = PyUnicode_FromOrdinal(' ');
9859 if (!sep)
9860 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009861 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009862 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009863 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009864 else {
9865 if (!PyUnicode_Check(separator)) {
9866 PyErr_Format(PyExc_TypeError,
9867 "separator: expected str instance,"
9868 " %.80s found",
9869 Py_TYPE(separator)->tp_name);
9870 goto onError;
9871 }
9872 if (PyUnicode_READY(separator))
9873 goto onError;
9874 sep = separator;
9875 seplen = PyUnicode_GET_LENGTH(separator);
9876 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9877 /* inc refcount to keep this code path symmetric with the
9878 above case of a blank separator */
9879 Py_INCREF(sep);
9880 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009881 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009882 }
9883
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009884 /* There are at least two things to join, or else we have a subclass
9885 * of str in the sequence.
9886 * Do a pre-pass to figure out the total amount of space we'll
9887 * need (sz), and see whether all argument are strings.
9888 */
9889 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009890#ifdef Py_DEBUG
9891 use_memcpy = 0;
9892#else
9893 use_memcpy = 1;
9894#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009895 for (i = 0; i < seqlen; i++) {
9896 const Py_ssize_t old_sz = sz;
9897 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009898 if (!PyUnicode_Check(item)) {
9899 PyErr_Format(PyExc_TypeError,
9900 "sequence item %zd: expected str instance,"
9901 " %.80s found",
9902 i, Py_TYPE(item)->tp_name);
9903 goto onError;
9904 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009905 if (PyUnicode_READY(item) == -1)
9906 goto onError;
9907 sz += PyUnicode_GET_LENGTH(item);
9908 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009909 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009910 if (i != 0)
9911 sz += seplen;
9912 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9913 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009914 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009915 goto onError;
9916 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009917 if (use_memcpy && last_obj != NULL) {
9918 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9919 use_memcpy = 0;
9920 }
9921 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009922 }
Tim Petersced69f82003-09-16 20:30:58 +00009923
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009924 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009925 if (res == NULL)
9926 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009927
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009928 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009929#ifdef Py_DEBUG
9930 use_memcpy = 0;
9931#else
9932 if (use_memcpy) {
9933 res_data = PyUnicode_1BYTE_DATA(res);
9934 kind = PyUnicode_KIND(res);
9935 if (seplen != 0)
9936 sep_data = PyUnicode_1BYTE_DATA(sep);
9937 }
9938#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009939 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009940 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009941 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009942 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009943 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009944 if (use_memcpy) {
9945 Py_MEMCPY(res_data,
9946 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009947 kind * seplen);
9948 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009949 }
9950 else {
9951 copy_characters(res, res_offset, sep, 0, seplen);
9952 res_offset += seplen;
9953 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009954 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009955 itemlen = PyUnicode_GET_LENGTH(item);
9956 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009957 if (use_memcpy) {
9958 Py_MEMCPY(res_data,
9959 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009960 kind * itemlen);
9961 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009962 }
9963 else {
9964 copy_characters(res, res_offset, item, 0, itemlen);
9965 res_offset += itemlen;
9966 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009967 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009968 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009969 if (use_memcpy)
9970 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009971 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009972 else
9973 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009974
Tim Peters05eba1f2004-08-27 21:32:02 +00009975 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009976 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009977 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009978 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009979
Benjamin Peterson29060642009-01-31 22:14:21 +00009980 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009981 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009982 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009983 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009984 return NULL;
9985}
9986
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009987#define FILL(kind, data, value, start, length) \
9988 do { \
9989 Py_ssize_t i_ = 0; \
9990 assert(kind != PyUnicode_WCHAR_KIND); \
9991 switch ((kind)) { \
9992 case PyUnicode_1BYTE_KIND: { \
9993 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9994 memset(to_, (unsigned char)value, length); \
9995 break; \
9996 } \
9997 case PyUnicode_2BYTE_KIND: { \
9998 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9999 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10000 break; \
10001 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010002 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010003 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10004 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10005 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010006 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010007 } \
10008 } \
10009 } while (0)
10010
Victor Stinner3fe55312012-01-04 00:33:50 +010010011Py_ssize_t
10012PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10013 Py_UCS4 fill_char)
10014{
10015 Py_ssize_t maxlen;
10016 enum PyUnicode_Kind kind;
10017 void *data;
10018
10019 if (!PyUnicode_Check(unicode)) {
10020 PyErr_BadInternalCall();
10021 return -1;
10022 }
10023 if (PyUnicode_READY(unicode) == -1)
10024 return -1;
10025 if (unicode_check_modifiable(unicode))
10026 return -1;
10027
10028 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10029 PyErr_SetString(PyExc_ValueError,
10030 "fill character is bigger than "
10031 "the string maximum character");
10032 return -1;
10033 }
10034
10035 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10036 length = Py_MIN(maxlen, length);
10037 if (length <= 0)
10038 return 0;
10039
10040 kind = PyUnicode_KIND(unicode);
10041 data = PyUnicode_DATA(unicode);
10042 FILL(kind, data, fill_char, start, length);
10043 return length;
10044}
10045
Victor Stinner9310abb2011-10-05 00:59:23 +020010046static PyObject *
10047pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010048 Py_ssize_t left,
10049 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010050 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010051{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010052 PyObject *u;
10053 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010054 int kind;
10055 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010056
10057 if (left < 0)
10058 left = 0;
10059 if (right < 0)
10060 right = 0;
10061
Victor Stinnerc4b49542011-12-11 22:44:26 +010010062 if (left == 0 && right == 0)
10063 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010064
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010065 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10066 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010067 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10068 return NULL;
10069 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10071 if (fill > maxchar)
10072 maxchar = fill;
10073 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010074 if (!u)
10075 return NULL;
10076
10077 kind = PyUnicode_KIND(u);
10078 data = PyUnicode_DATA(u);
10079 if (left)
10080 FILL(kind, data, fill, 0, left);
10081 if (right)
10082 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010083 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010084 assert(_PyUnicode_CheckConsistency(u, 1));
10085 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010086}
10087
Alexander Belopolsky40018472011-02-26 01:02:56 +000010088PyObject *
10089PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010090{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010091 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010092
10093 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010094 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010095 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060010096 if (PyUnicode_READY(string) == -1) {
10097 Py_DECREF(string);
10098 return NULL;
10099 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010100
Benjamin Petersonead6b532011-12-20 17:23:42 -060010101 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010103 if (PyUnicode_IS_ASCII(string))
10104 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010105 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010106 PyUnicode_GET_LENGTH(string), keepends);
10107 else
10108 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010109 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010110 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010111 break;
10112 case PyUnicode_2BYTE_KIND:
10113 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010114 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010115 PyUnicode_GET_LENGTH(string), keepends);
10116 break;
10117 case PyUnicode_4BYTE_KIND:
10118 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010119 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010120 PyUnicode_GET_LENGTH(string), keepends);
10121 break;
10122 default:
10123 assert(0);
10124 list = 0;
10125 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010126 Py_DECREF(string);
10127 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010128}
10129
Alexander Belopolsky40018472011-02-26 01:02:56 +000010130static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010131split(PyObject *self,
10132 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010133 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010134{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010135 int kind1, kind2, kind;
10136 void *buf1, *buf2;
10137 Py_ssize_t len1, len2;
10138 PyObject* out;
10139
Guido van Rossumd57fd912000-03-10 22:53:23 +000010140 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010141 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010142
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010143 if (PyUnicode_READY(self) == -1)
10144 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010145
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010146 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010147 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010148 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010149 if (PyUnicode_IS_ASCII(self))
10150 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010151 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010152 PyUnicode_GET_LENGTH(self), maxcount
10153 );
10154 else
10155 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010156 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010157 PyUnicode_GET_LENGTH(self), maxcount
10158 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 case PyUnicode_2BYTE_KIND:
10160 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010161 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010162 PyUnicode_GET_LENGTH(self), maxcount
10163 );
10164 case PyUnicode_4BYTE_KIND:
10165 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010166 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010167 PyUnicode_GET_LENGTH(self), maxcount
10168 );
10169 default:
10170 assert(0);
10171 return NULL;
10172 }
10173
10174 if (PyUnicode_READY(substring) == -1)
10175 return NULL;
10176
10177 kind1 = PyUnicode_KIND(self);
10178 kind2 = PyUnicode_KIND(substring);
10179 kind = kind1 > kind2 ? kind1 : kind2;
10180 buf1 = PyUnicode_DATA(self);
10181 buf2 = PyUnicode_DATA(substring);
10182 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010183 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010184 if (!buf1)
10185 return NULL;
10186 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010187 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 if (!buf2) {
10189 if (kind1 != kind) PyMem_Free(buf1);
10190 return NULL;
10191 }
10192 len1 = PyUnicode_GET_LENGTH(self);
10193 len2 = PyUnicode_GET_LENGTH(substring);
10194
Benjamin Petersonead6b532011-12-20 17:23:42 -060010195 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010196 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010197 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10198 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010199 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010200 else
10201 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010202 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 break;
10204 case PyUnicode_2BYTE_KIND:
10205 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010206 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207 break;
10208 case PyUnicode_4BYTE_KIND:
10209 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010210 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010211 break;
10212 default:
10213 out = NULL;
10214 }
10215 if (kind1 != kind)
10216 PyMem_Free(buf1);
10217 if (kind2 != kind)
10218 PyMem_Free(buf2);
10219 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010220}
10221
Alexander Belopolsky40018472011-02-26 01:02:56 +000010222static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010223rsplit(PyObject *self,
10224 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010225 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010226{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010227 int kind1, kind2, kind;
10228 void *buf1, *buf2;
10229 Py_ssize_t len1, len2;
10230 PyObject* out;
10231
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010232 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010233 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010234
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010235 if (PyUnicode_READY(self) == -1)
10236 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010237
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010238 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010239 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010241 if (PyUnicode_IS_ASCII(self))
10242 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010243 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010244 PyUnicode_GET_LENGTH(self), maxcount
10245 );
10246 else
10247 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010248 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010249 PyUnicode_GET_LENGTH(self), maxcount
10250 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010251 case PyUnicode_2BYTE_KIND:
10252 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010253 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010254 PyUnicode_GET_LENGTH(self), maxcount
10255 );
10256 case PyUnicode_4BYTE_KIND:
10257 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010258 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010259 PyUnicode_GET_LENGTH(self), maxcount
10260 );
10261 default:
10262 assert(0);
10263 return NULL;
10264 }
10265
10266 if (PyUnicode_READY(substring) == -1)
10267 return NULL;
10268
10269 kind1 = PyUnicode_KIND(self);
10270 kind2 = PyUnicode_KIND(substring);
10271 kind = kind1 > kind2 ? kind1 : kind2;
10272 buf1 = PyUnicode_DATA(self);
10273 buf2 = PyUnicode_DATA(substring);
10274 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010275 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010276 if (!buf1)
10277 return NULL;
10278 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010279 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010280 if (!buf2) {
10281 if (kind1 != kind) PyMem_Free(buf1);
10282 return NULL;
10283 }
10284 len1 = PyUnicode_GET_LENGTH(self);
10285 len2 = PyUnicode_GET_LENGTH(substring);
10286
Benjamin Petersonead6b532011-12-20 17:23:42 -060010287 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010288 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010289 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10290 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010291 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010292 else
10293 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010294 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010295 break;
10296 case PyUnicode_2BYTE_KIND:
10297 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010298 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 break;
10300 case PyUnicode_4BYTE_KIND:
10301 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010302 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010303 break;
10304 default:
10305 out = NULL;
10306 }
10307 if (kind1 != kind)
10308 PyMem_Free(buf1);
10309 if (kind2 != kind)
10310 PyMem_Free(buf2);
10311 return out;
10312}
10313
10314static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010315anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10316 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010317{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010318 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010320 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10321 return asciilib_find(buf1, len1, buf2, len2, offset);
10322 else
10323 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010324 case PyUnicode_2BYTE_KIND:
10325 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10326 case PyUnicode_4BYTE_KIND:
10327 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10328 }
10329 assert(0);
10330 return -1;
10331}
10332
10333static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010334anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10335 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010336{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010337 switch (kind) {
10338 case PyUnicode_1BYTE_KIND:
10339 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10340 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10341 else
10342 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10343 case PyUnicode_2BYTE_KIND:
10344 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10345 case PyUnicode_4BYTE_KIND:
10346 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10347 }
10348 assert(0);
10349 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010350}
10351
Alexander Belopolsky40018472011-02-26 01:02:56 +000010352static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010353replace(PyObject *self, PyObject *str1,
10354 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010355{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010356 PyObject *u;
10357 char *sbuf = PyUnicode_DATA(self);
10358 char *buf1 = PyUnicode_DATA(str1);
10359 char *buf2 = PyUnicode_DATA(str2);
10360 int srelease = 0, release1 = 0, release2 = 0;
10361 int skind = PyUnicode_KIND(self);
10362 int kind1 = PyUnicode_KIND(str1);
10363 int kind2 = PyUnicode_KIND(str2);
10364 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10365 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10366 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010367 int mayshrink;
10368 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010369
10370 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010371 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010372 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010373 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010374
Victor Stinner59de0ee2011-10-07 10:01:28 +020010375 if (str1 == str2)
10376 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377 if (skind < kind1)
10378 /* substring too wide to be present */
10379 goto nothing;
10380
Victor Stinner49a0a212011-10-12 23:46:10 +020010381 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10382 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10383 /* Replacing str1 with str2 may cause a maxchar reduction in the
10384 result string. */
10385 mayshrink = (maxchar_str2 < maxchar);
10386 maxchar = Py_MAX(maxchar, maxchar_str2);
10387
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010389 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010391 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010392 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010393 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010394 Py_UCS4 u1, u2;
10395 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010396 Py_ssize_t index, pos;
10397 char *src;
10398
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010399 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010400 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10401 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010402 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010403 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010404 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010405 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010406 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010407 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010408 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010409
10410 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10411 index = 0;
10412 src = sbuf;
10413 while (--maxcount)
10414 {
10415 pos++;
10416 src += pos * PyUnicode_KIND(self);
10417 slen -= pos;
10418 index += pos;
10419 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10420 if (pos < 0)
10421 break;
10422 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10423 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010424 }
10425 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010426 int rkind = skind;
10427 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010428 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010429
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010430 if (kind1 < rkind) {
10431 /* widen substring */
10432 buf1 = _PyUnicode_AsKind(str1, rkind);
10433 if (!buf1) goto error;
10434 release1 = 1;
10435 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010436 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010437 if (i < 0)
10438 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439 if (rkind > kind2) {
10440 /* widen replacement */
10441 buf2 = _PyUnicode_AsKind(str2, rkind);
10442 if (!buf2) goto error;
10443 release2 = 1;
10444 }
10445 else if (rkind < kind2) {
10446 /* widen self and buf1 */
10447 rkind = kind2;
10448 if (release1) PyMem_Free(buf1);
10449 sbuf = _PyUnicode_AsKind(self, rkind);
10450 if (!sbuf) goto error;
10451 srelease = 1;
10452 buf1 = _PyUnicode_AsKind(str1, rkind);
10453 if (!buf1) goto error;
10454 release1 = 1;
10455 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010456 u = PyUnicode_New(slen, maxchar);
10457 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010458 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010459 assert(PyUnicode_KIND(u) == rkind);
10460 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010461
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010462 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010463 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010464 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010466 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010467 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010468
10469 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010470 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010471 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010472 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010473 if (i == -1)
10474 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010475 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010476 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010477 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010478 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010479 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010480 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010481 }
10482 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010483 Py_ssize_t n, i, j, ires;
10484 Py_ssize_t product, new_size;
10485 int rkind = skind;
10486 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010487
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010488 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010489 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010490 buf1 = _PyUnicode_AsKind(str1, rkind);
10491 if (!buf1) goto error;
10492 release1 = 1;
10493 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010494 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010495 if (n == 0)
10496 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010498 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010499 buf2 = _PyUnicode_AsKind(str2, rkind);
10500 if (!buf2) goto error;
10501 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010502 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010503 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010504 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010505 rkind = kind2;
10506 sbuf = _PyUnicode_AsKind(self, rkind);
10507 if (!sbuf) goto error;
10508 srelease = 1;
10509 if (release1) PyMem_Free(buf1);
10510 buf1 = _PyUnicode_AsKind(str1, rkind);
10511 if (!buf1) goto error;
10512 release1 = 1;
10513 }
10514 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10515 PyUnicode_GET_LENGTH(str1))); */
10516 product = n * (len2-len1);
10517 if ((product / (len2-len1)) != n) {
10518 PyErr_SetString(PyExc_OverflowError,
10519 "replace string is too long");
10520 goto error;
10521 }
10522 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010523 if (new_size == 0) {
10524 Py_INCREF(unicode_empty);
10525 u = unicode_empty;
10526 goto done;
10527 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010528 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10529 PyErr_SetString(PyExc_OverflowError,
10530 "replace string is too long");
10531 goto error;
10532 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010533 u = PyUnicode_New(new_size, maxchar);
10534 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010535 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010536 assert(PyUnicode_KIND(u) == rkind);
10537 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010538 ires = i = 0;
10539 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010540 while (n-- > 0) {
10541 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010542 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010543 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010544 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010545 if (j == -1)
10546 break;
10547 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010548 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010549 memcpy(res + rkind * ires,
10550 sbuf + rkind * i,
10551 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010552 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010553 }
10554 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010555 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010556 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010557 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010558 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010560 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010561 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010562 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010563 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010564 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010565 memcpy(res + rkind * ires,
10566 sbuf + rkind * i,
10567 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010568 }
10569 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010570 /* interleave */
10571 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010572 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010573 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010574 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010575 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010576 if (--n <= 0)
10577 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010578 memcpy(res + rkind * ires,
10579 sbuf + rkind * i,
10580 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 ires++;
10582 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010583 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010584 memcpy(res + rkind * ires,
10585 sbuf + rkind * i,
10586 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010587 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010588 }
10589
10590 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010591 unicode_adjust_maxchar(&u);
10592 if (u == NULL)
10593 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010594 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010595
10596 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010597 if (srelease)
10598 PyMem_FREE(sbuf);
10599 if (release1)
10600 PyMem_FREE(buf1);
10601 if (release2)
10602 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010603 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010604 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010605
Benjamin Peterson29060642009-01-31 22:14:21 +000010606 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010607 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010608 if (srelease)
10609 PyMem_FREE(sbuf);
10610 if (release1)
10611 PyMem_FREE(buf1);
10612 if (release2)
10613 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010614 return unicode_result_unchanged(self);
10615
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010616 error:
10617 if (srelease && sbuf)
10618 PyMem_FREE(sbuf);
10619 if (release1 && buf1)
10620 PyMem_FREE(buf1);
10621 if (release2 && buf2)
10622 PyMem_FREE(buf2);
10623 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010624}
10625
10626/* --- Unicode Object Methods --------------------------------------------- */
10627
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010628PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010629 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010630\n\
10631Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010632characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010633
10634static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010635unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010636{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010637 if (PyUnicode_READY(self) == -1)
10638 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010639 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010640}
10641
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010642PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010643 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010644\n\
10645Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010646have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010647
10648static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010649unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010650{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010651 if (PyUnicode_READY(self) == -1)
10652 return NULL;
10653 if (PyUnicode_GET_LENGTH(self) == 0)
10654 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010655 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010656}
10657
Benjamin Petersond5890c82012-01-14 13:23:30 -050010658PyDoc_STRVAR(casefold__doc__,
10659 "S.casefold() -> str\n\
10660\n\
10661Return a version of S suitable for caseless comparisons.");
10662
10663static PyObject *
10664unicode_casefold(PyObject *self)
10665{
10666 if (PyUnicode_READY(self) == -1)
10667 return NULL;
10668 if (PyUnicode_IS_ASCII(self))
10669 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010670 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010671}
10672
10673
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010674/* Argument converter. Coerces to a single unicode character */
10675
10676static int
10677convert_uc(PyObject *obj, void *addr)
10678{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010679 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010680 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010681
Benjamin Peterson14339b62009-01-31 16:36:08 +000010682 uniobj = PyUnicode_FromObject(obj);
10683 if (uniobj == NULL) {
10684 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010685 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010686 return 0;
10687 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010688 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010689 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010690 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010691 Py_DECREF(uniobj);
10692 return 0;
10693 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010694 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010695 Py_DECREF(uniobj);
10696 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010697}
10698
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010699PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010700 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010701\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010702Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010703done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010704
10705static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010706unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010707{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010708 Py_ssize_t marg, left;
10709 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010710 Py_UCS4 fillchar = ' ';
10711
Victor Stinnere9a29352011-10-01 02:14:59 +020010712 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010713 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010714
Benjamin Petersonbac79492012-01-14 13:34:47 -050010715 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010716 return NULL;
10717
Victor Stinnerc4b49542011-12-11 22:44:26 +010010718 if (PyUnicode_GET_LENGTH(self) >= width)
10719 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010720
Victor Stinnerc4b49542011-12-11 22:44:26 +010010721 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010722 left = marg / 2 + (marg & width & 1);
10723
Victor Stinner9310abb2011-10-05 00:59:23 +020010724 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010725}
10726
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010727/* This function assumes that str1 and str2 are readied by the caller. */
10728
Marc-André Lemburge5034372000-08-08 08:04:29 +000010729static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010730unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010731{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010732 int kind1, kind2;
10733 void *data1, *data2;
10734 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010735
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010736 kind1 = PyUnicode_KIND(str1);
10737 kind2 = PyUnicode_KIND(str2);
10738 data1 = PyUnicode_DATA(str1);
10739 data2 = PyUnicode_DATA(str2);
10740 len1 = PyUnicode_GET_LENGTH(str1);
10741 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010742
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010743 for (i = 0; i < len1 && i < len2; ++i) {
10744 Py_UCS4 c1, c2;
10745 c1 = PyUnicode_READ(kind1, data1, i);
10746 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010747
10748 if (c1 != c2)
10749 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010750 }
10751
10752 return (len1 < len2) ? -1 : (len1 != len2);
10753}
10754
Alexander Belopolsky40018472011-02-26 01:02:56 +000010755int
10756PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010757{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010758 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10759 if (PyUnicode_READY(left) == -1 ||
10760 PyUnicode_READY(right) == -1)
10761 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010762 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010763 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010764 PyErr_Format(PyExc_TypeError,
10765 "Can't compare %.100s and %.100s",
10766 left->ob_type->tp_name,
10767 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010768 return -1;
10769}
10770
Martin v. Löwis5b222132007-06-10 09:51:05 +000010771int
10772PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10773{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010774 Py_ssize_t i;
10775 int kind;
10776 void *data;
10777 Py_UCS4 chr;
10778
Victor Stinner910337b2011-10-03 03:20:16 +020010779 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010780 if (PyUnicode_READY(uni) == -1)
10781 return -1;
10782 kind = PyUnicode_KIND(uni);
10783 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010784 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010785 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10786 if (chr != str[i])
10787 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010788 /* This check keeps Python strings that end in '\0' from comparing equal
10789 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010790 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010791 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010792 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010793 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010794 return 0;
10795}
10796
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010797
Benjamin Peterson29060642009-01-31 22:14:21 +000010798#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010799 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010800
Alexander Belopolsky40018472011-02-26 01:02:56 +000010801PyObject *
10802PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010803{
10804 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010805
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010806 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10807 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010808 if (PyUnicode_READY(left) == -1 ||
10809 PyUnicode_READY(right) == -1)
10810 return NULL;
10811 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10812 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010813 if (op == Py_EQ) {
10814 Py_INCREF(Py_False);
10815 return Py_False;
10816 }
10817 if (op == Py_NE) {
10818 Py_INCREF(Py_True);
10819 return Py_True;
10820 }
10821 }
10822 if (left == right)
10823 result = 0;
10824 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010825 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010826
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010827 /* Convert the return value to a Boolean */
10828 switch (op) {
10829 case Py_EQ:
10830 v = TEST_COND(result == 0);
10831 break;
10832 case Py_NE:
10833 v = TEST_COND(result != 0);
10834 break;
10835 case Py_LE:
10836 v = TEST_COND(result <= 0);
10837 break;
10838 case Py_GE:
10839 v = TEST_COND(result >= 0);
10840 break;
10841 case Py_LT:
10842 v = TEST_COND(result == -1);
10843 break;
10844 case Py_GT:
10845 v = TEST_COND(result == 1);
10846 break;
10847 default:
10848 PyErr_BadArgument();
10849 return NULL;
10850 }
10851 Py_INCREF(v);
10852 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010853 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010854
Brian Curtindfc80e32011-08-10 20:28:54 -050010855 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010856}
10857
Alexander Belopolsky40018472011-02-26 01:02:56 +000010858int
10859PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010860{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010861 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010862 int kind1, kind2, kind;
10863 void *buf1, *buf2;
10864 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010865 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010866
10867 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010868 sub = PyUnicode_FromObject(element);
10869 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010870 PyErr_Format(PyExc_TypeError,
10871 "'in <string>' requires string as left operand, not %s",
10872 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010873 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010874 }
10875
Thomas Wouters477c8d52006-05-27 19:21:47 +000010876 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010877 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010878 Py_DECREF(sub);
10879 return -1;
10880 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010881 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10882 Py_DECREF(sub);
10883 Py_DECREF(str);
10884 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010885
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010886 kind1 = PyUnicode_KIND(str);
10887 kind2 = PyUnicode_KIND(sub);
10888 kind = kind1 > kind2 ? kind1 : kind2;
10889 buf1 = PyUnicode_DATA(str);
10890 buf2 = PyUnicode_DATA(sub);
10891 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010892 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010893 if (!buf1) {
10894 Py_DECREF(sub);
10895 return -1;
10896 }
10897 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010898 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010899 if (!buf2) {
10900 Py_DECREF(sub);
10901 if (kind1 != kind) PyMem_Free(buf1);
10902 return -1;
10903 }
10904 len1 = PyUnicode_GET_LENGTH(str);
10905 len2 = PyUnicode_GET_LENGTH(sub);
10906
Benjamin Petersonead6b532011-12-20 17:23:42 -060010907 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010908 case PyUnicode_1BYTE_KIND:
10909 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10910 break;
10911 case PyUnicode_2BYTE_KIND:
10912 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10913 break;
10914 case PyUnicode_4BYTE_KIND:
10915 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10916 break;
10917 default:
10918 result = -1;
10919 assert(0);
10920 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010921
10922 Py_DECREF(str);
10923 Py_DECREF(sub);
10924
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010925 if (kind1 != kind)
10926 PyMem_Free(buf1);
10927 if (kind2 != kind)
10928 PyMem_Free(buf2);
10929
Guido van Rossum403d68b2000-03-13 15:55:09 +000010930 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010931}
10932
Guido van Rossumd57fd912000-03-10 22:53:23 +000010933/* Concat to string or Unicode object giving a new Unicode object. */
10934
Alexander Belopolsky40018472011-02-26 01:02:56 +000010935PyObject *
10936PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010937{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010938 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010939 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010940 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010941
10942 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010943 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010944 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010945 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010946 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010947 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010948 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010949
10950 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010951 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010952 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010953 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010954 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010955 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010956 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010957 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010958 }
10959
Victor Stinner488fa492011-12-12 00:01:39 +010010960 u_len = PyUnicode_GET_LENGTH(u);
10961 v_len = PyUnicode_GET_LENGTH(v);
10962 if (u_len > PY_SSIZE_T_MAX - v_len) {
10963 PyErr_SetString(PyExc_OverflowError,
10964 "strings are too large to concat");
10965 goto onError;
10966 }
10967 new_len = u_len + v_len;
10968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010969 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010970 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10971 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010972
Guido van Rossumd57fd912000-03-10 22:53:23 +000010973 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010974 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010975 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010976 goto onError;
Victor Stinner488fa492011-12-12 00:01:39 +010010977 copy_characters(w, 0, u, 0, u_len);
10978 copy_characters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010979 Py_DECREF(u);
10980 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010981 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010982 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010983
Benjamin Peterson29060642009-01-31 22:14:21 +000010984 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010985 Py_XDECREF(u);
10986 Py_XDECREF(v);
10987 return NULL;
10988}
10989
Walter Dörwald1ab83302007-05-18 17:15:44 +000010990void
Victor Stinner23e56682011-10-03 03:54:37 +020010991PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010992{
Victor Stinner23e56682011-10-03 03:54:37 +020010993 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010994 Py_UCS4 maxchar, maxchar2;
10995 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010996
10997 if (p_left == NULL) {
10998 if (!PyErr_Occurred())
10999 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011000 return;
11001 }
Victor Stinner23e56682011-10-03 03:54:37 +020011002 left = *p_left;
11003 if (right == NULL || !PyUnicode_Check(left)) {
11004 if (!PyErr_Occurred())
11005 PyErr_BadInternalCall();
11006 goto error;
11007 }
11008
Benjamin Petersonbac79492012-01-14 13:34:47 -050011009 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011010 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011011 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011012 goto error;
11013
Victor Stinner488fa492011-12-12 00:01:39 +010011014 /* Shortcuts */
11015 if (left == unicode_empty) {
11016 Py_DECREF(left);
11017 Py_INCREF(right);
11018 *p_left = right;
11019 return;
11020 }
11021 if (right == unicode_empty)
11022 return;
11023
11024 left_len = PyUnicode_GET_LENGTH(left);
11025 right_len = PyUnicode_GET_LENGTH(right);
11026 if (left_len > PY_SSIZE_T_MAX - right_len) {
11027 PyErr_SetString(PyExc_OverflowError,
11028 "strings are too large to concat");
11029 goto error;
11030 }
11031 new_len = left_len + right_len;
11032
11033 if (unicode_modifiable(left)
11034 && PyUnicode_CheckExact(right)
11035 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011036 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11037 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011038 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011039 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011040 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11041 {
11042 /* append inplace */
11043 if (unicode_resize(p_left, new_len) != 0) {
11044 /* XXX if _PyUnicode_Resize() fails, 'left' has been
11045 * deallocated so it cannot be put back into
11046 * 'variable'. The MemoryError is raised when there
11047 * is no value in 'variable', which might (very
11048 * remotely) be a cause of incompatibilities.
11049 */
11050 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020011051 }
Victor Stinner488fa492011-12-12 00:01:39 +010011052 /* copy 'right' into the newly allocated area of 'left' */
11053 copy_characters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011054 }
Victor Stinner488fa492011-12-12 00:01:39 +010011055 else {
11056 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11057 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11058 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011059
Victor Stinner488fa492011-12-12 00:01:39 +010011060 /* Concat the two Unicode strings */
11061 res = PyUnicode_New(new_len, maxchar);
11062 if (res == NULL)
11063 goto error;
11064 copy_characters(res, 0, left, 0, left_len);
11065 copy_characters(res, left_len, right, 0, right_len);
11066 Py_DECREF(left);
11067 *p_left = res;
11068 }
11069 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011070 return;
11071
11072error:
Victor Stinner488fa492011-12-12 00:01:39 +010011073 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011074}
11075
11076void
11077PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11078{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011079 PyUnicode_Append(pleft, right);
11080 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011081}
11082
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011083PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011084 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011085\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011086Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011087string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011088interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011089
11090static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011091unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011092{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011093 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011094 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011095 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011096 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011097 int kind1, kind2, kind;
11098 void *buf1, *buf2;
11099 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011100
Jesus Ceaac451502011-04-20 17:09:23 +020011101 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11102 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011103 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011105 kind1 = PyUnicode_KIND(self);
11106 kind2 = PyUnicode_KIND(substring);
11107 kind = kind1 > kind2 ? kind1 : kind2;
11108 buf1 = PyUnicode_DATA(self);
11109 buf2 = PyUnicode_DATA(substring);
11110 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011111 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011112 if (!buf1) {
11113 Py_DECREF(substring);
11114 return NULL;
11115 }
11116 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011117 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011118 if (!buf2) {
11119 Py_DECREF(substring);
11120 if (kind1 != kind) PyMem_Free(buf1);
11121 return NULL;
11122 }
11123 len1 = PyUnicode_GET_LENGTH(self);
11124 len2 = PyUnicode_GET_LENGTH(substring);
11125
11126 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060011127 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011128 case PyUnicode_1BYTE_KIND:
11129 iresult = ucs1lib_count(
11130 ((Py_UCS1*)buf1) + start, end - start,
11131 buf2, len2, PY_SSIZE_T_MAX
11132 );
11133 break;
11134 case PyUnicode_2BYTE_KIND:
11135 iresult = ucs2lib_count(
11136 ((Py_UCS2*)buf1) + start, end - start,
11137 buf2, len2, PY_SSIZE_T_MAX
11138 );
11139 break;
11140 case PyUnicode_4BYTE_KIND:
11141 iresult = ucs4lib_count(
11142 ((Py_UCS4*)buf1) + start, end - start,
11143 buf2, len2, PY_SSIZE_T_MAX
11144 );
11145 break;
11146 default:
11147 assert(0); iresult = 0;
11148 }
11149
11150 result = PyLong_FromSsize_t(iresult);
11151
11152 if (kind1 != kind)
11153 PyMem_Free(buf1);
11154 if (kind2 != kind)
11155 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011156
11157 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011158
Guido van Rossumd57fd912000-03-10 22:53:23 +000011159 return result;
11160}
11161
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011162PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011163 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011164\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011165Encode S using the codec registered for encoding. Default encoding\n\
11166is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011167handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011168a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11169'xmlcharrefreplace' as well as any other name registered with\n\
11170codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011171
11172static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011173unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011175 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011176 char *encoding = NULL;
11177 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011178
Benjamin Peterson308d6372009-09-18 21:42:35 +000011179 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11180 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011181 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011182 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011183}
11184
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011185PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011186 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011187\n\
11188Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011189If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190
11191static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011192unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011194 Py_ssize_t i, j, line_pos, src_len, incr;
11195 Py_UCS4 ch;
11196 PyObject *u;
11197 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011198 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011199 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011200 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201
11202 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011203 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204
Antoine Pitrou22425222011-10-04 19:10:51 +020011205 if (PyUnicode_READY(self) == -1)
11206 return NULL;
11207
Thomas Wouters7e474022000-07-16 12:04:32 +000011208 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011209 src_len = PyUnicode_GET_LENGTH(self);
11210 i = j = line_pos = 0;
11211 kind = PyUnicode_KIND(self);
11212 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011213 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011214 for (; i < src_len; i++) {
11215 ch = PyUnicode_READ(kind, src_data, i);
11216 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011217 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011218 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011219 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011220 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011221 goto overflow;
11222 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011223 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011224 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011225 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011226 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011227 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011228 goto overflow;
11229 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011231 if (ch == '\n' || ch == '\r')
11232 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011233 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011234 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011235 if (!found)
11236 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011237
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011239 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011240 if (!u)
11241 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011242 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011243
Antoine Pitroue71d5742011-10-04 15:55:09 +020011244 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011245
Antoine Pitroue71d5742011-10-04 15:55:09 +020011246 for (; i < src_len; i++) {
11247 ch = PyUnicode_READ(kind, src_data, i);
11248 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011249 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011250 incr = tabsize - (line_pos % tabsize);
11251 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011252 FILL(kind, dest_data, ' ', j, incr);
11253 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011254 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011255 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011256 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011257 line_pos++;
11258 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011259 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011260 if (ch == '\n' || ch == '\r')
11261 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011262 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011263 }
11264 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011265 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011266
Antoine Pitroue71d5742011-10-04 15:55:09 +020011267 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011268 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11269 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011270}
11271
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011272PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011273 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011274\n\
11275Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011276such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011277arguments start and end are interpreted as in slice notation.\n\
11278\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011279Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011280
11281static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011282unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011283{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011284 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011285 Py_ssize_t start;
11286 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011287 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011288
Jesus Ceaac451502011-04-20 17:09:23 +020011289 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11290 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011291 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011292
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011293 if (PyUnicode_READY(self) == -1)
11294 return NULL;
11295 if (PyUnicode_READY(substring) == -1)
11296 return NULL;
11297
Victor Stinner7931d9a2011-11-04 00:22:48 +010011298 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011299
11300 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011302 if (result == -2)
11303 return NULL;
11304
Christian Heimes217cfd12007-12-02 14:31:20 +000011305 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011306}
11307
11308static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011309unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011310{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011311 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11312 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011313 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011314 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011315}
11316
Guido van Rossumc2504932007-09-18 19:42:40 +000011317/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011318 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011319static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011320unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011321{
Guido van Rossumc2504932007-09-18 19:42:40 +000011322 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011323 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011324
Benjamin Peterson69e97272012-02-21 11:08:50 -050011325 assert(_Py_HashSecret_Initialized);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011326 if (_PyUnicode_HASH(self) != -1)
11327 return _PyUnicode_HASH(self);
11328 if (PyUnicode_READY(self) == -1)
11329 return -1;
11330 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011331 /*
11332 We make the hash of the empty string be 0, rather than using
11333 (prefix ^ suffix), since this slightly obfuscates the hash secret
11334 */
11335 if (len == 0) {
11336 _PyUnicode_HASH(self) = 0;
11337 return 0;
11338 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011339
11340 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011341#define HASH(P) \
11342 x ^= (Py_uhash_t) *P << 7; \
11343 while (--len >= 0) \
11344 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011345
Georg Brandl2fb477c2012-02-21 00:33:36 +010011346 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011347 switch (PyUnicode_KIND(self)) {
11348 case PyUnicode_1BYTE_KIND: {
11349 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11350 HASH(c);
11351 break;
11352 }
11353 case PyUnicode_2BYTE_KIND: {
11354 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11355 HASH(s);
11356 break;
11357 }
11358 default: {
11359 Py_UCS4 *l;
11360 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11361 "Impossible switch case in unicode_hash");
11362 l = PyUnicode_4BYTE_DATA(self);
11363 HASH(l);
11364 break;
11365 }
11366 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011367 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11368 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011369
Guido van Rossumc2504932007-09-18 19:42:40 +000011370 if (x == -1)
11371 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011372 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011373 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011374}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011375#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011376
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011377PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011378 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011379\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011380Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011381
11382static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011383unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011384{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011385 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011386 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011387 Py_ssize_t start;
11388 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011389
Jesus Ceaac451502011-04-20 17:09:23 +020011390 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11391 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011392 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011393
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011394 if (PyUnicode_READY(self) == -1)
11395 return NULL;
11396 if (PyUnicode_READY(substring) == -1)
11397 return NULL;
11398
Victor Stinner7931d9a2011-11-04 00:22:48 +010011399 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011400
11401 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011402
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011403 if (result == -2)
11404 return NULL;
11405
Guido van Rossumd57fd912000-03-10 22:53:23 +000011406 if (result < 0) {
11407 PyErr_SetString(PyExc_ValueError, "substring not found");
11408 return NULL;
11409 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011410
Christian Heimes217cfd12007-12-02 14:31:20 +000011411 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011412}
11413
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011414PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011415 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011417Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011418at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419
11420static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011421unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011422{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011423 Py_ssize_t i, length;
11424 int kind;
11425 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426 int cased;
11427
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011428 if (PyUnicode_READY(self) == -1)
11429 return NULL;
11430 length = PyUnicode_GET_LENGTH(self);
11431 kind = PyUnicode_KIND(self);
11432 data = PyUnicode_DATA(self);
11433
Guido van Rossumd57fd912000-03-10 22:53:23 +000011434 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011435 if (length == 1)
11436 return PyBool_FromLong(
11437 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011438
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011439 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011440 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011441 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011442
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011444 for (i = 0; i < length; i++) {
11445 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011446
Benjamin Peterson29060642009-01-31 22:14:21 +000011447 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11448 return PyBool_FromLong(0);
11449 else if (!cased && Py_UNICODE_ISLOWER(ch))
11450 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011451 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011452 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011453}
11454
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011455PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011456 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011457\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011458Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011459at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011460
11461static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011462unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011463{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011464 Py_ssize_t i, length;
11465 int kind;
11466 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011467 int cased;
11468
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011469 if (PyUnicode_READY(self) == -1)
11470 return NULL;
11471 length = PyUnicode_GET_LENGTH(self);
11472 kind = PyUnicode_KIND(self);
11473 data = PyUnicode_DATA(self);
11474
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011476 if (length == 1)
11477 return PyBool_FromLong(
11478 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011479
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011480 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011481 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011482 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011483
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011485 for (i = 0; i < length; i++) {
11486 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011487
Benjamin Peterson29060642009-01-31 22:14:21 +000011488 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11489 return PyBool_FromLong(0);
11490 else if (!cased && Py_UNICODE_ISUPPER(ch))
11491 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011493 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494}
11495
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011496PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011497 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011499Return True if S is a titlecased string and there is at least one\n\
11500character in S, i.e. upper- and titlecase characters may only\n\
11501follow uncased characters and lowercase characters only cased ones.\n\
11502Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011503
11504static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011505unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011506{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011507 Py_ssize_t i, length;
11508 int kind;
11509 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510 int cased, previous_is_cased;
11511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011512 if (PyUnicode_READY(self) == -1)
11513 return NULL;
11514 length = PyUnicode_GET_LENGTH(self);
11515 kind = PyUnicode_KIND(self);
11516 data = PyUnicode_DATA(self);
11517
Guido van Rossumd57fd912000-03-10 22:53:23 +000011518 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011519 if (length == 1) {
11520 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11521 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11522 (Py_UNICODE_ISUPPER(ch) != 0));
11523 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011525 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011526 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011527 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011528
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529 cased = 0;
11530 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011531 for (i = 0; i < length; i++) {
11532 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011533
Benjamin Peterson29060642009-01-31 22:14:21 +000011534 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11535 if (previous_is_cased)
11536 return PyBool_FromLong(0);
11537 previous_is_cased = 1;
11538 cased = 1;
11539 }
11540 else if (Py_UNICODE_ISLOWER(ch)) {
11541 if (!previous_is_cased)
11542 return PyBool_FromLong(0);
11543 previous_is_cased = 1;
11544 cased = 1;
11545 }
11546 else
11547 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011548 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011549 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011550}
11551
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011552PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011553 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011555Return True if all characters in S are whitespace\n\
11556and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557
11558static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011559unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011561 Py_ssize_t i, length;
11562 int kind;
11563 void *data;
11564
11565 if (PyUnicode_READY(self) == -1)
11566 return NULL;
11567 length = PyUnicode_GET_LENGTH(self);
11568 kind = PyUnicode_KIND(self);
11569 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570
Guido van Rossumd57fd912000-03-10 22:53:23 +000011571 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011572 if (length == 1)
11573 return PyBool_FromLong(
11574 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011575
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011576 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011577 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011578 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011579
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011580 for (i = 0; i < length; i++) {
11581 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011582 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011583 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011585 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586}
11587
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011588PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011589 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011590\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011591Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011592and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011593
11594static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011595unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011596{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011597 Py_ssize_t i, length;
11598 int kind;
11599 void *data;
11600
11601 if (PyUnicode_READY(self) == -1)
11602 return NULL;
11603 length = PyUnicode_GET_LENGTH(self);
11604 kind = PyUnicode_KIND(self);
11605 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011606
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011607 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011608 if (length == 1)
11609 return PyBool_FromLong(
11610 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011611
11612 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011613 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011614 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011615
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011616 for (i = 0; i < length; i++) {
11617 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011618 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011619 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011620 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011621}
11622
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011623PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011624 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011625\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011626Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011627and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011628
11629static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011630unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011631{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011632 int kind;
11633 void *data;
11634 Py_ssize_t len, i;
11635
11636 if (PyUnicode_READY(self) == -1)
11637 return NULL;
11638
11639 kind = PyUnicode_KIND(self);
11640 data = PyUnicode_DATA(self);
11641 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011642
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011643 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011644 if (len == 1) {
11645 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11646 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11647 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011648
11649 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011650 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011651 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011652
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011653 for (i = 0; i < len; i++) {
11654 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011655 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011656 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011657 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011658 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011659}
11660
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011661PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011662 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011663\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011664Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011665False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011666
11667static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011668unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011669{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011670 Py_ssize_t i, length;
11671 int kind;
11672 void *data;
11673
11674 if (PyUnicode_READY(self) == -1)
11675 return NULL;
11676 length = PyUnicode_GET_LENGTH(self);
11677 kind = PyUnicode_KIND(self);
11678 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011679
Guido van Rossumd57fd912000-03-10 22:53:23 +000011680 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 if (length == 1)
11682 return PyBool_FromLong(
11683 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011684
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011685 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011686 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011687 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011688
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011689 for (i = 0; i < length; i++) {
11690 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011691 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011693 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011694}
11695
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011696PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011697 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011698\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011699Return True if all characters in S are digits\n\
11700and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701
11702static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011703unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011704{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011705 Py_ssize_t i, length;
11706 int kind;
11707 void *data;
11708
11709 if (PyUnicode_READY(self) == -1)
11710 return NULL;
11711 length = PyUnicode_GET_LENGTH(self);
11712 kind = PyUnicode_KIND(self);
11713 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011714
Guido van Rossumd57fd912000-03-10 22:53:23 +000011715 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011716 if (length == 1) {
11717 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11718 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11719 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011720
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011721 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011722 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011723 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011724
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011725 for (i = 0; i < length; i++) {
11726 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011727 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011728 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011729 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011730}
11731
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011732PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011733 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011734\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011735Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011736False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011737
11738static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011739unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011740{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011741 Py_ssize_t i, length;
11742 int kind;
11743 void *data;
11744
11745 if (PyUnicode_READY(self) == -1)
11746 return NULL;
11747 length = PyUnicode_GET_LENGTH(self);
11748 kind = PyUnicode_KIND(self);
11749 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011750
Guido van Rossumd57fd912000-03-10 22:53:23 +000011751 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011752 if (length == 1)
11753 return PyBool_FromLong(
11754 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011755
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011756 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011757 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011758 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011759
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011760 for (i = 0; i < length; i++) {
11761 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011762 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011763 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011764 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011765}
11766
Martin v. Löwis47383402007-08-15 07:32:56 +000011767int
11768PyUnicode_IsIdentifier(PyObject *self)
11769{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011770 int kind;
11771 void *data;
11772 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011773 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011774
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011775 if (PyUnicode_READY(self) == -1) {
11776 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011777 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011778 }
11779
11780 /* Special case for empty strings */
11781 if (PyUnicode_GET_LENGTH(self) == 0)
11782 return 0;
11783 kind = PyUnicode_KIND(self);
11784 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011785
11786 /* PEP 3131 says that the first character must be in
11787 XID_Start and subsequent characters in XID_Continue,
11788 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011789 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011790 letters, digits, underscore). However, given the current
11791 definition of XID_Start and XID_Continue, it is sufficient
11792 to check just for these, except that _ must be allowed
11793 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011794 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011795 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011796 return 0;
11797
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011798 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011799 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011800 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011801 return 1;
11802}
11803
11804PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011805 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011806\n\
11807Return True if S is a valid identifier according\n\
11808to the language definition.");
11809
11810static PyObject*
11811unicode_isidentifier(PyObject *self)
11812{
11813 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11814}
11815
Georg Brandl559e5d72008-06-11 18:37:52 +000011816PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011817 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011818\n\
11819Return True if all characters in S are considered\n\
11820printable in repr() or S is empty, False otherwise.");
11821
11822static PyObject*
11823unicode_isprintable(PyObject *self)
11824{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011825 Py_ssize_t i, length;
11826 int kind;
11827 void *data;
11828
11829 if (PyUnicode_READY(self) == -1)
11830 return NULL;
11831 length = PyUnicode_GET_LENGTH(self);
11832 kind = PyUnicode_KIND(self);
11833 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011834
11835 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011836 if (length == 1)
11837 return PyBool_FromLong(
11838 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011839
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011840 for (i = 0; i < length; i++) {
11841 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011842 Py_RETURN_FALSE;
11843 }
11844 }
11845 Py_RETURN_TRUE;
11846}
11847
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011848PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011849 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011850\n\
11851Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011852iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011853
11854static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011855unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011856{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011857 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011858}
11859
Martin v. Löwis18e16552006-02-15 17:27:45 +000011860static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011861unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011862{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011863 if (PyUnicode_READY(self) == -1)
11864 return -1;
11865 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866}
11867
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011868PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011869 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011870\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011871Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011872done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011873
11874static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011875unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011876{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011877 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011878 Py_UCS4 fillchar = ' ';
11879
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011880 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011881 return NULL;
11882
Benjamin Petersonbac79492012-01-14 13:34:47 -050011883 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011884 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885
Victor Stinnerc4b49542011-12-11 22:44:26 +010011886 if (PyUnicode_GET_LENGTH(self) >= width)
11887 return unicode_result_unchanged(self);
11888
11889 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011890}
11891
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011892PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011893 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011895Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011896
11897static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011898unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011899{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011900 if (PyUnicode_READY(self) == -1)
11901 return NULL;
11902 if (PyUnicode_IS_ASCII(self))
11903 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011904 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011905}
11906
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011907#define LEFTSTRIP 0
11908#define RIGHTSTRIP 1
11909#define BOTHSTRIP 2
11910
11911/* Arrays indexed by above */
11912static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11913
11914#define STRIPNAME(i) (stripformat[i]+3)
11915
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011916/* externally visible for str.strip(unicode) */
11917PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011918_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011919{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011920 void *data;
11921 int kind;
11922 Py_ssize_t i, j, len;
11923 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011924
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011925 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11926 return NULL;
11927
11928 kind = PyUnicode_KIND(self);
11929 data = PyUnicode_DATA(self);
11930 len = PyUnicode_GET_LENGTH(self);
11931 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11932 PyUnicode_DATA(sepobj),
11933 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011934
Benjamin Peterson14339b62009-01-31 16:36:08 +000011935 i = 0;
11936 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011937 while (i < len &&
11938 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011939 i++;
11940 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011941 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011942
Benjamin Peterson14339b62009-01-31 16:36:08 +000011943 j = len;
11944 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011945 do {
11946 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011947 } while (j >= i &&
11948 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011949 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011950 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011951
Victor Stinner7931d9a2011-11-04 00:22:48 +010011952 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011953}
11954
11955PyObject*
11956PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11957{
11958 unsigned char *data;
11959 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011960 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011961
Victor Stinnerde636f32011-10-01 03:55:54 +020011962 if (PyUnicode_READY(self) == -1)
11963 return NULL;
11964
11965 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11966
Victor Stinner12bab6d2011-10-01 01:53:49 +020011967 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Victor Stinnerc4b49542011-12-11 22:44:26 +010011968 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011969
Victor Stinner12bab6d2011-10-01 01:53:49 +020011970 length = end - start;
11971 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011972 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011973
Victor Stinnerde636f32011-10-01 03:55:54 +020011974 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011975 PyErr_SetString(PyExc_IndexError, "string index out of range");
11976 return NULL;
11977 }
11978
Victor Stinnerb9275c12011-10-05 14:01:42 +020011979 if (PyUnicode_IS_ASCII(self)) {
11980 kind = PyUnicode_KIND(self);
11981 data = PyUnicode_1BYTE_DATA(self);
11982 return unicode_fromascii(data + start, length);
11983 }
11984 else {
11985 kind = PyUnicode_KIND(self);
11986 data = PyUnicode_1BYTE_DATA(self);
11987 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011988 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011989 length);
11990 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011991}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011992
11993static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011994do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011995{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011996 int kind;
11997 void *data;
11998 Py_ssize_t len, i, j;
11999
12000 if (PyUnicode_READY(self) == -1)
12001 return NULL;
12002
12003 kind = PyUnicode_KIND(self);
12004 data = PyUnicode_DATA(self);
12005 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012006
Benjamin Peterson14339b62009-01-31 16:36:08 +000012007 i = 0;
12008 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012009 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012010 i++;
12011 }
12012 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012013
Benjamin Peterson14339b62009-01-31 16:36:08 +000012014 j = len;
12015 if (striptype != LEFTSTRIP) {
12016 do {
12017 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012018 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012019 j++;
12020 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012021
Victor Stinner7931d9a2011-11-04 00:22:48 +010012022 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012023}
12024
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012025
12026static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012027do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012028{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012029 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012030
Benjamin Peterson14339b62009-01-31 16:36:08 +000012031 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
12032 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012033
Benjamin Peterson14339b62009-01-31 16:36:08 +000012034 if (sep != NULL && sep != Py_None) {
12035 if (PyUnicode_Check(sep))
12036 return _PyUnicode_XStrip(self, striptype, sep);
12037 else {
12038 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012039 "%s arg must be None or str",
12040 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012041 return NULL;
12042 }
12043 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012044
Benjamin Peterson14339b62009-01-31 16:36:08 +000012045 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012046}
12047
12048
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012049PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012050 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012051\n\
12052Return a copy of the string S with leading and trailing\n\
12053whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012054If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012055
12056static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012057unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012058{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012059 if (PyTuple_GET_SIZE(args) == 0)
12060 return do_strip(self, BOTHSTRIP); /* Common case */
12061 else
12062 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012063}
12064
12065
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012066PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012067 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012068\n\
12069Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012070If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012071
12072static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012073unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012074{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012075 if (PyTuple_GET_SIZE(args) == 0)
12076 return do_strip(self, LEFTSTRIP); /* Common case */
12077 else
12078 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012079}
12080
12081
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012082PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012083 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012084\n\
12085Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012086If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012087
12088static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012089unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012090{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012091 if (PyTuple_GET_SIZE(args) == 0)
12092 return do_strip(self, RIGHTSTRIP); /* Common case */
12093 else
12094 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012095}
12096
12097
Guido van Rossumd57fd912000-03-10 22:53:23 +000012098static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012099unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012100{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012101 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012102 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012103
Georg Brandl222de0f2009-04-12 12:01:50 +000012104 if (len < 1) {
12105 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020012106 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000012107 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012108
Victor Stinnerc4b49542011-12-11 22:44:26 +010012109 /* no repeat, return original string */
12110 if (len == 1)
12111 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012112
Benjamin Petersonbac79492012-01-14 13:34:47 -050012113 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012114 return NULL;
12115
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012116 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012117 PyErr_SetString(PyExc_OverflowError,
12118 "repeated string is too long");
12119 return NULL;
12120 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012121 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012122
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012123 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012124 if (!u)
12125 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012126 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012127
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012128 if (PyUnicode_GET_LENGTH(str) == 1) {
12129 const int kind = PyUnicode_KIND(str);
12130 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012131 if (kind == PyUnicode_1BYTE_KIND) {
12132 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012133 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012134 }
12135 else if (kind == PyUnicode_2BYTE_KIND) {
12136 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012137 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012138 ucs2[n] = fill_char;
12139 } else {
12140 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12141 assert(kind == PyUnicode_4BYTE_KIND);
12142 for (n = 0; n < len; ++n)
12143 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012144 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012145 }
12146 else {
12147 /* number of characters copied this far */
12148 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012149 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012150 char *to = (char *) PyUnicode_DATA(u);
12151 Py_MEMCPY(to, PyUnicode_DATA(str),
12152 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012153 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012154 n = (done <= nchars-done) ? done : nchars-done;
12155 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012156 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012157 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012158 }
12159
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012160 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012161 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012162}
12163
Alexander Belopolsky40018472011-02-26 01:02:56 +000012164PyObject *
12165PyUnicode_Replace(PyObject *obj,
12166 PyObject *subobj,
12167 PyObject *replobj,
12168 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012169{
12170 PyObject *self;
12171 PyObject *str1;
12172 PyObject *str2;
12173 PyObject *result;
12174
12175 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012176 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012177 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012178 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012179 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012180 Py_DECREF(self);
12181 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012182 }
12183 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012184 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012185 Py_DECREF(self);
12186 Py_DECREF(str1);
12187 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012189 if (PyUnicode_READY(self) == -1 ||
12190 PyUnicode_READY(str1) == -1 ||
12191 PyUnicode_READY(str2) == -1)
12192 result = NULL;
12193 else
12194 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012195 Py_DECREF(self);
12196 Py_DECREF(str1);
12197 Py_DECREF(str2);
12198 return result;
12199}
12200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012201PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012202 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012203\n\
12204Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012205old replaced by new. If the optional argument count is\n\
12206given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012207
12208static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012209unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012210{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012211 PyObject *str1;
12212 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012213 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012214 PyObject *result;
12215
Martin v. Löwis18e16552006-02-15 17:27:45 +000012216 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012217 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012218 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012219 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012220 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012221 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012222 return NULL;
12223 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012224 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012225 Py_DECREF(str1);
12226 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012227 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012228 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12229 result = NULL;
12230 else
12231 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012232
12233 Py_DECREF(str1);
12234 Py_DECREF(str2);
12235 return result;
12236}
12237
Alexander Belopolsky40018472011-02-26 01:02:56 +000012238static PyObject *
12239unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012240{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012241 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012242 Py_ssize_t isize;
12243 Py_ssize_t osize, squote, dquote, i, o;
12244 Py_UCS4 max, quote;
12245 int ikind, okind;
12246 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012247
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012248 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012249 return NULL;
12250
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012251 isize = PyUnicode_GET_LENGTH(unicode);
12252 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012253
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012254 /* Compute length of output, quote characters, and
12255 maximum character */
12256 osize = 2; /* quotes */
12257 max = 127;
12258 squote = dquote = 0;
12259 ikind = PyUnicode_KIND(unicode);
12260 for (i = 0; i < isize; i++) {
12261 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12262 switch (ch) {
12263 case '\'': squote++; osize++; break;
12264 case '"': dquote++; osize++; break;
12265 case '\\': case '\t': case '\r': case '\n':
12266 osize += 2; break;
12267 default:
12268 /* Fast-path ASCII */
12269 if (ch < ' ' || ch == 0x7f)
12270 osize += 4; /* \xHH */
12271 else if (ch < 0x7f)
12272 osize++;
12273 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12274 osize++;
12275 max = ch > max ? ch : max;
12276 }
12277 else if (ch < 0x100)
12278 osize += 4; /* \xHH */
12279 else if (ch < 0x10000)
12280 osize += 6; /* \uHHHH */
12281 else
12282 osize += 10; /* \uHHHHHHHH */
12283 }
12284 }
12285
12286 quote = '\'';
12287 if (squote) {
12288 if (dquote)
12289 /* Both squote and dquote present. Use squote,
12290 and escape them */
12291 osize += squote;
12292 else
12293 quote = '"';
12294 }
12295
12296 repr = PyUnicode_New(osize, max);
12297 if (repr == NULL)
12298 return NULL;
12299 okind = PyUnicode_KIND(repr);
12300 odata = PyUnicode_DATA(repr);
12301
12302 PyUnicode_WRITE(okind, odata, 0, quote);
12303 PyUnicode_WRITE(okind, odata, osize-1, quote);
12304
12305 for (i = 0, o = 1; i < isize; i++) {
12306 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012307
12308 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012309 if ((ch == quote) || (ch == '\\')) {
12310 PyUnicode_WRITE(okind, odata, o++, '\\');
12311 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012312 continue;
12313 }
12314
Benjamin Peterson29060642009-01-31 22:14:21 +000012315 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012316 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012317 PyUnicode_WRITE(okind, odata, o++, '\\');
12318 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012319 }
12320 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012321 PyUnicode_WRITE(okind, odata, o++, '\\');
12322 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012323 }
12324 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012325 PyUnicode_WRITE(okind, odata, o++, '\\');
12326 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012327 }
12328
12329 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012330 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012331 PyUnicode_WRITE(okind, odata, o++, '\\');
12332 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012333 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12334 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012335 }
12336
Georg Brandl559e5d72008-06-11 18:37:52 +000012337 /* Copy ASCII characters as-is */
12338 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012339 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012340 }
12341
Benjamin Peterson29060642009-01-31 22:14:21 +000012342 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012343 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012344 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012345 (categories Z* and C* except ASCII space)
12346 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012347 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012348 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012349 if (ch <= 0xff) {
12350 PyUnicode_WRITE(okind, odata, o++, '\\');
12351 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012352 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12353 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012354 }
12355 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012356 else if (ch >= 0x10000) {
12357 PyUnicode_WRITE(okind, odata, o++, '\\');
12358 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012359 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12360 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12361 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12362 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12363 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12364 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12365 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12366 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012367 }
12368 /* Map 16-bit characters to '\uxxxx' */
12369 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012370 PyUnicode_WRITE(okind, odata, o++, '\\');
12371 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012372 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12373 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12374 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12375 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012376 }
12377 }
12378 /* Copy characters as-is */
12379 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012380 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012381 }
12382 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012383 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012384 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012385 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012386 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012387}
12388
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012389PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012390 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012391\n\
12392Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012393such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012394arguments start and end are interpreted as in slice notation.\n\
12395\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012396Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012397
12398static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012399unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012400{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012401 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012402 Py_ssize_t start;
12403 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012404 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012405
Jesus Ceaac451502011-04-20 17:09:23 +020012406 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12407 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012408 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012409
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012410 if (PyUnicode_READY(self) == -1)
12411 return NULL;
12412 if (PyUnicode_READY(substring) == -1)
12413 return NULL;
12414
Victor Stinner7931d9a2011-11-04 00:22:48 +010012415 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012416
12417 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012419 if (result == -2)
12420 return NULL;
12421
Christian Heimes217cfd12007-12-02 14:31:20 +000012422 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012423}
12424
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012425PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012426 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012427\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012428Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012429
12430static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012431unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012432{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012433 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012434 Py_ssize_t start;
12435 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012436 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012437
Jesus Ceaac451502011-04-20 17:09:23 +020012438 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12439 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012440 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012441
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012442 if (PyUnicode_READY(self) == -1)
12443 return NULL;
12444 if (PyUnicode_READY(substring) == -1)
12445 return NULL;
12446
Victor Stinner7931d9a2011-11-04 00:22:48 +010012447 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012448
12449 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012450
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012451 if (result == -2)
12452 return NULL;
12453
Guido van Rossumd57fd912000-03-10 22:53:23 +000012454 if (result < 0) {
12455 PyErr_SetString(PyExc_ValueError, "substring not found");
12456 return NULL;
12457 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012458
Christian Heimes217cfd12007-12-02 14:31:20 +000012459 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012460}
12461
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012462PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012463 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012464\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012465Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012466done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012467
12468static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012469unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012470{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012471 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012472 Py_UCS4 fillchar = ' ';
12473
Victor Stinnere9a29352011-10-01 02:14:59 +020012474 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012475 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012476
Benjamin Petersonbac79492012-01-14 13:34:47 -050012477 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012478 return NULL;
12479
Victor Stinnerc4b49542011-12-11 22:44:26 +010012480 if (PyUnicode_GET_LENGTH(self) >= width)
12481 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012482
Victor Stinnerc4b49542011-12-11 22:44:26 +010012483 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012484}
12485
Alexander Belopolsky40018472011-02-26 01:02:56 +000012486PyObject *
12487PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012488{
12489 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012490
Guido van Rossumd57fd912000-03-10 22:53:23 +000012491 s = PyUnicode_FromObject(s);
12492 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012493 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012494 if (sep != NULL) {
12495 sep = PyUnicode_FromObject(sep);
12496 if (sep == NULL) {
12497 Py_DECREF(s);
12498 return NULL;
12499 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012500 }
12501
Victor Stinner9310abb2011-10-05 00:59:23 +020012502 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012503
12504 Py_DECREF(s);
12505 Py_XDECREF(sep);
12506 return result;
12507}
12508
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012509PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012510 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012511\n\
12512Return a list of the words in S, using sep as the\n\
12513delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012514splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012515whitespace string is a separator and empty strings are\n\
12516removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012517
12518static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012519unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012520{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012521 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012522 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012523 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012524
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012525 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12526 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012527 return NULL;
12528
12529 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012530 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012531 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012532 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012533 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012534 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012535}
12536
Thomas Wouters477c8d52006-05-27 19:21:47 +000012537PyObject *
12538PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12539{
12540 PyObject* str_obj;
12541 PyObject* sep_obj;
12542 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012543 int kind1, kind2, kind;
12544 void *buf1 = NULL, *buf2 = NULL;
12545 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012546
12547 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012548 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012549 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012550 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012551 if (!sep_obj) {
12552 Py_DECREF(str_obj);
12553 return NULL;
12554 }
12555 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12556 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012557 Py_DECREF(str_obj);
12558 return NULL;
12559 }
12560
Victor Stinner14f8f022011-10-05 20:58:25 +020012561 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012562 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012563 kind = Py_MAX(kind1, kind2);
12564 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012565 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012566 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012567 if (!buf1)
12568 goto onError;
12569 buf2 = PyUnicode_DATA(sep_obj);
12570 if (kind2 != kind)
12571 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12572 if (!buf2)
12573 goto onError;
12574 len1 = PyUnicode_GET_LENGTH(str_obj);
12575 len2 = PyUnicode_GET_LENGTH(sep_obj);
12576
Benjamin Petersonead6b532011-12-20 17:23:42 -060012577 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012578 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012579 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12580 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12581 else
12582 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012583 break;
12584 case PyUnicode_2BYTE_KIND:
12585 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12586 break;
12587 case PyUnicode_4BYTE_KIND:
12588 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12589 break;
12590 default:
12591 assert(0);
12592 out = 0;
12593 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012594
12595 Py_DECREF(sep_obj);
12596 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012597 if (kind1 != kind)
12598 PyMem_Free(buf1);
12599 if (kind2 != kind)
12600 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012601
12602 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012603 onError:
12604 Py_DECREF(sep_obj);
12605 Py_DECREF(str_obj);
12606 if (kind1 != kind && buf1)
12607 PyMem_Free(buf1);
12608 if (kind2 != kind && buf2)
12609 PyMem_Free(buf2);
12610 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012611}
12612
12613
12614PyObject *
12615PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12616{
12617 PyObject* str_obj;
12618 PyObject* sep_obj;
12619 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012620 int kind1, kind2, kind;
12621 void *buf1 = NULL, *buf2 = NULL;
12622 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012623
12624 str_obj = PyUnicode_FromObject(str_in);
12625 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012626 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012627 sep_obj = PyUnicode_FromObject(sep_in);
12628 if (!sep_obj) {
12629 Py_DECREF(str_obj);
12630 return NULL;
12631 }
12632
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012633 kind1 = PyUnicode_KIND(str_in);
12634 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012635 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012636 buf1 = PyUnicode_DATA(str_in);
12637 if (kind1 != kind)
12638 buf1 = _PyUnicode_AsKind(str_in, kind);
12639 if (!buf1)
12640 goto onError;
12641 buf2 = PyUnicode_DATA(sep_obj);
12642 if (kind2 != kind)
12643 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12644 if (!buf2)
12645 goto onError;
12646 len1 = PyUnicode_GET_LENGTH(str_obj);
12647 len2 = PyUnicode_GET_LENGTH(sep_obj);
12648
Benjamin Petersonead6b532011-12-20 17:23:42 -060012649 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012650 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012651 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12652 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12653 else
12654 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012655 break;
12656 case PyUnicode_2BYTE_KIND:
12657 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12658 break;
12659 case PyUnicode_4BYTE_KIND:
12660 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12661 break;
12662 default:
12663 assert(0);
12664 out = 0;
12665 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012666
12667 Py_DECREF(sep_obj);
12668 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012669 if (kind1 != kind)
12670 PyMem_Free(buf1);
12671 if (kind2 != kind)
12672 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012673
12674 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012675 onError:
12676 Py_DECREF(sep_obj);
12677 Py_DECREF(str_obj);
12678 if (kind1 != kind && buf1)
12679 PyMem_Free(buf1);
12680 if (kind2 != kind && buf2)
12681 PyMem_Free(buf2);
12682 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012683}
12684
12685PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012686 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012687\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012688Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012689the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012690found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012691
12692static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012693unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012694{
Victor Stinner9310abb2011-10-05 00:59:23 +020012695 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012696}
12697
12698PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012699 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012700\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012701Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012702the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012703separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012704
12705static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012706unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012707{
Victor Stinner9310abb2011-10-05 00:59:23 +020012708 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012709}
12710
Alexander Belopolsky40018472011-02-26 01:02:56 +000012711PyObject *
12712PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012713{
12714 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012715
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012716 s = PyUnicode_FromObject(s);
12717 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012718 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012719 if (sep != NULL) {
12720 sep = PyUnicode_FromObject(sep);
12721 if (sep == NULL) {
12722 Py_DECREF(s);
12723 return NULL;
12724 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012725 }
12726
Victor Stinner9310abb2011-10-05 00:59:23 +020012727 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012728
12729 Py_DECREF(s);
12730 Py_XDECREF(sep);
12731 return result;
12732}
12733
12734PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012735 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012736\n\
12737Return a list of the words in S, using sep as the\n\
12738delimiter string, starting at the end of the string and\n\
12739working to the front. If maxsplit is given, at most maxsplit\n\
12740splits are done. If sep is not specified, any whitespace string\n\
12741is a separator.");
12742
12743static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012744unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012745{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012746 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012747 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012748 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012749
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012750 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12751 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012752 return NULL;
12753
12754 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012755 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012756 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012757 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012758 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012759 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012760}
12761
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012762PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012763 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012764\n\
12765Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012766Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012767is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012768
12769static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012770unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012771{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012772 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012773 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012774
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012775 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12776 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012777 return NULL;
12778
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012779 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012780}
12781
12782static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012783PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012784{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012785 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012786}
12787
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012788PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012789 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012790\n\
12791Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012792and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012793
12794static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012795unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012796{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012797 if (PyUnicode_READY(self) == -1)
12798 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012799 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012800}
12801
Georg Brandlceee0772007-11-27 23:48:05 +000012802PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012803 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012804\n\
12805Return a translation table usable for str.translate().\n\
12806If there is only one argument, it must be a dictionary mapping Unicode\n\
12807ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012808Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012809If there are two arguments, they must be strings of equal length, and\n\
12810in the resulting dictionary, each character in x will be mapped to the\n\
12811character at the same position in y. If there is a third argument, it\n\
12812must be a string, whose characters will be mapped to None in the result.");
12813
12814static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012815unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012816{
12817 PyObject *x, *y = NULL, *z = NULL;
12818 PyObject *new = NULL, *key, *value;
12819 Py_ssize_t i = 0;
12820 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012821
Georg Brandlceee0772007-11-27 23:48:05 +000012822 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12823 return NULL;
12824 new = PyDict_New();
12825 if (!new)
12826 return NULL;
12827 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012828 int x_kind, y_kind, z_kind;
12829 void *x_data, *y_data, *z_data;
12830
Georg Brandlceee0772007-11-27 23:48:05 +000012831 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012832 if (!PyUnicode_Check(x)) {
12833 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12834 "be a string if there is a second argument");
12835 goto err;
12836 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012837 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012838 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12839 "arguments must have equal length");
12840 goto err;
12841 }
12842 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012843 x_kind = PyUnicode_KIND(x);
12844 y_kind = PyUnicode_KIND(y);
12845 x_data = PyUnicode_DATA(x);
12846 y_data = PyUnicode_DATA(y);
12847 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12848 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012849 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012850 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012851 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012852 if (!value) {
12853 Py_DECREF(key);
12854 goto err;
12855 }
Georg Brandlceee0772007-11-27 23:48:05 +000012856 res = PyDict_SetItem(new, key, value);
12857 Py_DECREF(key);
12858 Py_DECREF(value);
12859 if (res < 0)
12860 goto err;
12861 }
12862 /* create entries for deleting chars in z */
12863 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012864 z_kind = PyUnicode_KIND(z);
12865 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012866 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012867 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012868 if (!key)
12869 goto err;
12870 res = PyDict_SetItem(new, key, Py_None);
12871 Py_DECREF(key);
12872 if (res < 0)
12873 goto err;
12874 }
12875 }
12876 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012877 int kind;
12878 void *data;
12879
Georg Brandlceee0772007-11-27 23:48:05 +000012880 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012881 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012882 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12883 "to maketrans it must be a dict");
12884 goto err;
12885 }
12886 /* copy entries into the new dict, converting string keys to int keys */
12887 while (PyDict_Next(x, &i, &key, &value)) {
12888 if (PyUnicode_Check(key)) {
12889 /* convert string keys to integer keys */
12890 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012891 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012892 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12893 "table must be of length 1");
12894 goto err;
12895 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012896 kind = PyUnicode_KIND(key);
12897 data = PyUnicode_DATA(key);
12898 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012899 if (!newkey)
12900 goto err;
12901 res = PyDict_SetItem(new, newkey, value);
12902 Py_DECREF(newkey);
12903 if (res < 0)
12904 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012905 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012906 /* just keep integer keys */
12907 if (PyDict_SetItem(new, key, value) < 0)
12908 goto err;
12909 } else {
12910 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12911 "be strings or integers");
12912 goto err;
12913 }
12914 }
12915 }
12916 return new;
12917 err:
12918 Py_DECREF(new);
12919 return NULL;
12920}
12921
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012922PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012923 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012924\n\
12925Return a copy of the string S, where all characters have been mapped\n\
12926through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012927Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012928Unmapped characters are left untouched. Characters mapped to None\n\
12929are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012930
12931static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012932unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012933{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012934 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012935}
12936
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012937PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012938 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012939\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012940Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012941
12942static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012943unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012944{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012945 if (PyUnicode_READY(self) == -1)
12946 return NULL;
12947 if (PyUnicode_IS_ASCII(self))
12948 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012949 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012950}
12951
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012952PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012953 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012954\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012955Pad a numeric string S with zeros on the left, to fill a field\n\
12956of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012957
12958static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012959unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012960{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012961 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012962 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012963 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012964 int kind;
12965 void *data;
12966 Py_UCS4 chr;
12967
Martin v. Löwis18e16552006-02-15 17:27:45 +000012968 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012969 return NULL;
12970
Benjamin Petersonbac79492012-01-14 13:34:47 -050012971 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012972 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012973
Victor Stinnerc4b49542011-12-11 22:44:26 +010012974 if (PyUnicode_GET_LENGTH(self) >= width)
12975 return unicode_result_unchanged(self);
12976
12977 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012978
12979 u = pad(self, fill, 0, '0');
12980
Walter Dörwald068325e2002-04-15 13:36:47 +000012981 if (u == NULL)
12982 return NULL;
12983
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012984 kind = PyUnicode_KIND(u);
12985 data = PyUnicode_DATA(u);
12986 chr = PyUnicode_READ(kind, data, fill);
12987
12988 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012989 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012990 PyUnicode_WRITE(kind, data, 0, chr);
12991 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012992 }
12993
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012994 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012995 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012996}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012997
12998#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012999static PyObject *
13000unicode__decimal2ascii(PyObject *self)
13001{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013002 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013003}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013004#endif
13005
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013006PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013007 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013008\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013009Return True if S starts with the specified prefix, False otherwise.\n\
13010With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013011With optional end, stop comparing S at that position.\n\
13012prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013013
13014static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013015unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013016 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013017{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013018 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013019 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013020 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013021 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013022 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013023
Jesus Ceaac451502011-04-20 17:09:23 +020013024 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013025 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013026 if (PyTuple_Check(subobj)) {
13027 Py_ssize_t i;
13028 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013029 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013030 if (substring == NULL)
13031 return NULL;
13032 result = tailmatch(self, substring, start, end, -1);
13033 Py_DECREF(substring);
13034 if (result) {
13035 Py_RETURN_TRUE;
13036 }
13037 }
13038 /* nothing matched */
13039 Py_RETURN_FALSE;
13040 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013041 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013042 if (substring == NULL) {
13043 if (PyErr_ExceptionMatches(PyExc_TypeError))
13044 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13045 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013046 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013047 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013048 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013049 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013050 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013051}
13052
13053
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013054PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013055 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013056\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013057Return True if S ends with the specified suffix, False otherwise.\n\
13058With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013059With optional end, stop comparing S at that position.\n\
13060suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013061
13062static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013063unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013064 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013065{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013066 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013067 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013068 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013069 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013070 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013071
Jesus Ceaac451502011-04-20 17:09:23 +020013072 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013073 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013074 if (PyTuple_Check(subobj)) {
13075 Py_ssize_t i;
13076 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013077 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013078 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013079 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013080 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013081 result = tailmatch(self, substring, start, end, +1);
13082 Py_DECREF(substring);
13083 if (result) {
13084 Py_RETURN_TRUE;
13085 }
13086 }
13087 Py_RETURN_FALSE;
13088 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013089 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013090 if (substring == NULL) {
13091 if (PyErr_ExceptionMatches(PyExc_TypeError))
13092 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13093 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013094 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013095 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013096 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013097 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013098 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013099}
13100
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013101#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013102
13103PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013104 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013105\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013106Return a formatted version of S, using substitutions from args and kwargs.\n\
13107The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013108
Eric Smith27bbca62010-11-04 17:06:58 +000013109PyDoc_STRVAR(format_map__doc__,
13110 "S.format_map(mapping) -> str\n\
13111\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013112Return a formatted version of S, using substitutions from mapping.\n\
13113The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013114
Eric Smith4a7d76d2008-05-30 18:10:19 +000013115static PyObject *
13116unicode__format__(PyObject* self, PyObject* args)
13117{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013118 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013119
13120 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13121 return NULL;
13122
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013123 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013124 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013125 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013126}
13127
Eric Smith8c663262007-08-25 02:26:07 +000013128PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013129 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013130\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013131Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013132
13133static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013134unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013135{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013136 Py_ssize_t size;
13137
13138 /* If it's a compact object, account for base structure +
13139 character data. */
13140 if (PyUnicode_IS_COMPACT_ASCII(v))
13141 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13142 else if (PyUnicode_IS_COMPACT(v))
13143 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013144 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013145 else {
13146 /* If it is a two-block object, account for base object, and
13147 for character block if present. */
13148 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013149 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013150 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013151 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013152 }
13153 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013154 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013155 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013156 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013157 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013158 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013159
13160 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013161}
13162
13163PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013164 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013165
13166static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013167unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013168{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013169 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013170 if (!copy)
13171 return NULL;
13172 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013173}
13174
Guido van Rossumd57fd912000-03-10 22:53:23 +000013175static PyMethodDef unicode_methods[] = {
13176
13177 /* Order is according to common usage: often used methods should
13178 appear first, since lookup is done sequentially. */
13179
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013180 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013181 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013182 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13183 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013184 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13185 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013186 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013187 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13188 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13189 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13190 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13191 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013192 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013193 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13194 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13195 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013196 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013197 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13198 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13199 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013200 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013201 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013202 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013203 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013204 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13205 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13206 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13207 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13208 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13209 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13210 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13211 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13212 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13213 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13214 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13215 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13216 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13217 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013218 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013219 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013220 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013221 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013222 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013223 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013224 {"maketrans", (PyCFunction) unicode_maketrans,
13225 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013226 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013227#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013228 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013229 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013230#endif
13231
Benjamin Peterson14339b62009-01-31 16:36:08 +000013232 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013233 {NULL, NULL}
13234};
13235
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013236static PyObject *
13237unicode_mod(PyObject *v, PyObject *w)
13238{
Brian Curtindfc80e32011-08-10 20:28:54 -050013239 if (!PyUnicode_Check(v))
13240 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013241 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013242}
13243
13244static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013245 0, /*nb_add*/
13246 0, /*nb_subtract*/
13247 0, /*nb_multiply*/
13248 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013249};
13250
Guido van Rossumd57fd912000-03-10 22:53:23 +000013251static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013252 (lenfunc) unicode_length, /* sq_length */
13253 PyUnicode_Concat, /* sq_concat */
13254 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13255 (ssizeargfunc) unicode_getitem, /* sq_item */
13256 0, /* sq_slice */
13257 0, /* sq_ass_item */
13258 0, /* sq_ass_slice */
13259 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013260};
13261
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013262static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013263unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013264{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013265 if (PyUnicode_READY(self) == -1)
13266 return NULL;
13267
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013268 if (PyIndex_Check(item)) {
13269 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013270 if (i == -1 && PyErr_Occurred())
13271 return NULL;
13272 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013273 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013274 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013275 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013276 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013277 PyObject *result;
13278 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013279 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013280 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013281
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013282 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013283 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013284 return NULL;
13285 }
13286
13287 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013288 Py_INCREF(unicode_empty);
13289 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013290 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013291 slicelength == PyUnicode_GET_LENGTH(self)) {
13292 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013293 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013294 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013295 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013296 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013297 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013298 src_kind = PyUnicode_KIND(self);
13299 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013300 if (!PyUnicode_IS_ASCII(self)) {
13301 kind_limit = kind_maxchar_limit(src_kind);
13302 max_char = 0;
13303 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13304 ch = PyUnicode_READ(src_kind, src_data, cur);
13305 if (ch > max_char) {
13306 max_char = ch;
13307 if (max_char >= kind_limit)
13308 break;
13309 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013310 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013311 }
Victor Stinner55c99112011-10-13 01:17:06 +020013312 else
13313 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013314 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013315 if (result == NULL)
13316 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013317 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013318 dest_data = PyUnicode_DATA(result);
13319
13320 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013321 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13322 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013323 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013324 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013325 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013326 } else {
13327 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13328 return NULL;
13329 }
13330}
13331
13332static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013333 (lenfunc)unicode_length, /* mp_length */
13334 (binaryfunc)unicode_subscript, /* mp_subscript */
13335 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013336};
13337
Guido van Rossumd57fd912000-03-10 22:53:23 +000013338
Guido van Rossumd57fd912000-03-10 22:53:23 +000013339/* Helpers for PyUnicode_Format() */
13340
13341static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013342getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013343{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013344 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013345 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013346 (*p_argidx)++;
13347 if (arglen < 0)
13348 return args;
13349 else
13350 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013351 }
13352 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013353 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013354 return NULL;
13355}
13356
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013357/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013358
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013359static PyObject *
13360formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013361{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013362 char *p;
13363 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013364 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013365
Guido van Rossumd57fd912000-03-10 22:53:23 +000013366 x = PyFloat_AsDouble(v);
13367 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013368 return NULL;
13369
Guido van Rossumd57fd912000-03-10 22:53:23 +000013370 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013371 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013372
Eric Smith0923d1d2009-04-16 20:16:10 +000013373 p = PyOS_double_to_string(x, type, prec,
13374 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013375 if (p == NULL)
13376 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013377 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013378 PyMem_Free(p);
13379 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013380}
13381
Tim Peters38fd5b62000-09-21 05:43:11 +000013382static PyObject*
13383formatlong(PyObject *val, int flags, int prec, int type)
13384{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013385 char *buf;
13386 int len;
13387 PyObject *str; /* temporary string object. */
13388 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013389
Benjamin Peterson14339b62009-01-31 16:36:08 +000013390 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13391 if (!str)
13392 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013393 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013394 Py_DECREF(str);
13395 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013396}
13397
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013398static Py_UCS4
13399formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013400{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013401 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013402 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013403 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013404 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013405 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013406 goto onError;
13407 }
13408 else {
13409 /* Integer input truncated to a character */
13410 long x;
13411 x = PyLong_AsLong(v);
13412 if (x == -1 && PyErr_Occurred())
13413 goto onError;
13414
Victor Stinner8faf8212011-12-08 22:14:11 +010013415 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013416 PyErr_SetString(PyExc_OverflowError,
13417 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013418 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013419 }
13420
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013421 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013422 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013423
Benjamin Peterson29060642009-01-31 22:14:21 +000013424 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013425 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013426 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013427 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013428}
13429
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013430static int
13431repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13432{
13433 int r;
13434 assert(count > 0);
13435 assert(PyUnicode_Check(obj));
13436 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013437 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013438 if (repeated == NULL)
13439 return -1;
13440 r = _PyAccu_Accumulate(acc, repeated);
13441 Py_DECREF(repeated);
13442 return r;
13443 }
13444 else {
13445 do {
13446 if (_PyAccu_Accumulate(acc, obj))
13447 return -1;
13448 } while (--count);
13449 return 0;
13450 }
13451}
13452
Alexander Belopolsky40018472011-02-26 01:02:56 +000013453PyObject *
13454PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013455{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013456 void *fmt;
13457 int fmtkind;
13458 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013459 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013460 int r;
13461 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013462 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013463 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013464 PyObject *temp = NULL;
13465 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013466 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013467 _PyAccu acc;
13468 static PyObject *plus, *minus, *blank, *zero, *percent;
13469
13470 if (!plus && !(plus = get_latin1_char('+')))
13471 return NULL;
13472 if (!minus && !(minus = get_latin1_char('-')))
13473 return NULL;
13474 if (!blank && !(blank = get_latin1_char(' ')))
13475 return NULL;
13476 if (!zero && !(zero = get_latin1_char('0')))
13477 return NULL;
13478 if (!percent && !(percent = get_latin1_char('%')))
13479 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013480
Guido van Rossumd57fd912000-03-10 22:53:23 +000013481 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013482 PyErr_BadInternalCall();
13483 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013484 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013485 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013486 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013487 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013488 if (PyUnicode_READY(uformat) == -1)
13489 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013490 if (_PyAccu_Init(&acc))
13491 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013492 fmt = PyUnicode_DATA(uformat);
13493 fmtkind = PyUnicode_KIND(uformat);
13494 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13495 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013496
Guido van Rossumd57fd912000-03-10 22:53:23 +000013497 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013498 arglen = PyTuple_Size(args);
13499 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013500 }
13501 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013502 arglen = -1;
13503 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013504 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013505 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013506 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013507 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013508
13509 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013510 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013511 PyObject *nonfmt;
13512 Py_ssize_t nonfmtpos;
13513 nonfmtpos = fmtpos++;
13514 while (fmtcnt >= 0 &&
13515 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13516 fmtpos++;
13517 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013518 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013519 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013520 if (nonfmt == NULL)
13521 goto onError;
13522 r = _PyAccu_Accumulate(&acc, nonfmt);
13523 Py_DECREF(nonfmt);
13524 if (r)
13525 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013526 }
13527 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013528 /* Got a format specifier */
13529 int flags = 0;
13530 Py_ssize_t width = -1;
13531 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013532 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013533 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013534 int isnumok;
13535 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013536 void *pbuf = NULL;
13537 Py_ssize_t pindex, len;
13538 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013539
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013540 fmtpos++;
13541 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13542 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013543 Py_ssize_t keylen;
13544 PyObject *key;
13545 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013546
Benjamin Peterson29060642009-01-31 22:14:21 +000013547 if (dict == NULL) {
13548 PyErr_SetString(PyExc_TypeError,
13549 "format requires a mapping");
13550 goto onError;
13551 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013552 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013553 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013554 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013555 /* Skip over balanced parentheses */
13556 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013557 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013558 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013559 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013560 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013561 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013562 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013563 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013564 if (fmtcnt < 0 || pcount > 0) {
13565 PyErr_SetString(PyExc_ValueError,
13566 "incomplete format key");
13567 goto onError;
13568 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013569 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013570 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013571 if (key == NULL)
13572 goto onError;
13573 if (args_owned) {
13574 Py_DECREF(args);
13575 args_owned = 0;
13576 }
13577 args = PyObject_GetItem(dict, key);
13578 Py_DECREF(key);
13579 if (args == NULL) {
13580 goto onError;
13581 }
13582 args_owned = 1;
13583 arglen = -1;
13584 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013585 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013586 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013587 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013588 case '-': flags |= F_LJUST; continue;
13589 case '+': flags |= F_SIGN; continue;
13590 case ' ': flags |= F_BLANK; continue;
13591 case '#': flags |= F_ALT; continue;
13592 case '0': flags |= F_ZERO; continue;
13593 }
13594 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013595 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013596 if (c == '*') {
13597 v = getnextarg(args, arglen, &argidx);
13598 if (v == NULL)
13599 goto onError;
13600 if (!PyLong_Check(v)) {
13601 PyErr_SetString(PyExc_TypeError,
13602 "* wants int");
13603 goto onError;
13604 }
13605 width = PyLong_AsLong(v);
13606 if (width == -1 && PyErr_Occurred())
13607 goto onError;
13608 if (width < 0) {
13609 flags |= F_LJUST;
13610 width = -width;
13611 }
13612 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013613 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013614 }
13615 else if (c >= '0' && c <= '9') {
13616 width = c - '0';
13617 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013618 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013619 if (c < '0' || c > '9')
13620 break;
13621 if ((width*10) / 10 != width) {
13622 PyErr_SetString(PyExc_ValueError,
13623 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013624 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013625 }
13626 width = width*10 + (c - '0');
13627 }
13628 }
13629 if (c == '.') {
13630 prec = 0;
13631 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013632 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013633 if (c == '*') {
13634 v = getnextarg(args, arglen, &argidx);
13635 if (v == NULL)
13636 goto onError;
13637 if (!PyLong_Check(v)) {
13638 PyErr_SetString(PyExc_TypeError,
13639 "* wants int");
13640 goto onError;
13641 }
13642 prec = PyLong_AsLong(v);
13643 if (prec == -1 && PyErr_Occurred())
13644 goto onError;
13645 if (prec < 0)
13646 prec = 0;
13647 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013648 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013649 }
13650 else if (c >= '0' && c <= '9') {
13651 prec = c - '0';
13652 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013653 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013654 if (c < '0' || c > '9')
13655 break;
13656 if ((prec*10) / 10 != prec) {
13657 PyErr_SetString(PyExc_ValueError,
13658 "prec too big");
13659 goto onError;
13660 }
13661 prec = prec*10 + (c - '0');
13662 }
13663 }
13664 } /* prec */
13665 if (fmtcnt >= 0) {
13666 if (c == 'h' || c == 'l' || c == 'L') {
13667 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013668 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013669 }
13670 }
13671 if (fmtcnt < 0) {
13672 PyErr_SetString(PyExc_ValueError,
13673 "incomplete format");
13674 goto onError;
13675 }
13676 if (c != '%') {
13677 v = getnextarg(args, arglen, &argidx);
13678 if (v == NULL)
13679 goto onError;
13680 }
13681 sign = 0;
13682 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013683 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013684 switch (c) {
13685
13686 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013687 _PyAccu_Accumulate(&acc, percent);
13688 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013689
13690 case 's':
13691 case 'r':
13692 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013693 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013694 temp = v;
13695 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013696 }
13697 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013698 if (c == 's')
13699 temp = PyObject_Str(v);
13700 else if (c == 'r')
13701 temp = PyObject_Repr(v);
13702 else
13703 temp = PyObject_ASCII(v);
13704 if (temp == NULL)
13705 goto onError;
13706 if (PyUnicode_Check(temp))
13707 /* nothing to do */;
13708 else {
13709 Py_DECREF(temp);
13710 PyErr_SetString(PyExc_TypeError,
13711 "%s argument has non-string str()");
13712 goto onError;
13713 }
13714 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013715 if (PyUnicode_READY(temp) == -1) {
13716 Py_CLEAR(temp);
13717 goto onError;
13718 }
13719 pbuf = PyUnicode_DATA(temp);
13720 kind = PyUnicode_KIND(temp);
13721 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013722 if (prec >= 0 && len > prec)
13723 len = prec;
13724 break;
13725
13726 case 'i':
13727 case 'd':
13728 case 'u':
13729 case 'o':
13730 case 'x':
13731 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013732 isnumok = 0;
13733 if (PyNumber_Check(v)) {
13734 PyObject *iobj=NULL;
13735
13736 if (PyLong_Check(v)) {
13737 iobj = v;
13738 Py_INCREF(iobj);
13739 }
13740 else {
13741 iobj = PyNumber_Long(v);
13742 }
13743 if (iobj!=NULL) {
13744 if (PyLong_Check(iobj)) {
13745 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013746 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013747 Py_DECREF(iobj);
13748 if (!temp)
13749 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013750 if (PyUnicode_READY(temp) == -1) {
13751 Py_CLEAR(temp);
13752 goto onError;
13753 }
13754 pbuf = PyUnicode_DATA(temp);
13755 kind = PyUnicode_KIND(temp);
13756 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013757 sign = 1;
13758 }
13759 else {
13760 Py_DECREF(iobj);
13761 }
13762 }
13763 }
13764 if (!isnumok) {
13765 PyErr_Format(PyExc_TypeError,
13766 "%%%c format: a number is required, "
13767 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13768 goto onError;
13769 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013770 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013771 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013772 fillobj = zero;
13773 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013774 break;
13775
13776 case 'e':
13777 case 'E':
13778 case 'f':
13779 case 'F':
13780 case 'g':
13781 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013782 temp = formatfloat(v, flags, prec, c);
13783 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013784 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013785 if (PyUnicode_READY(temp) == -1) {
13786 Py_CLEAR(temp);
13787 goto onError;
13788 }
13789 pbuf = PyUnicode_DATA(temp);
13790 kind = PyUnicode_KIND(temp);
13791 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013792 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013793 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013794 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013795 fillobj = zero;
13796 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013797 break;
13798
13799 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013800 {
13801 Py_UCS4 ch = formatchar(v);
13802 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013803 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013804 temp = _PyUnicode_FromUCS4(&ch, 1);
13805 if (temp == NULL)
13806 goto onError;
13807 pbuf = PyUnicode_DATA(temp);
13808 kind = PyUnicode_KIND(temp);
13809 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013810 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013811 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013812
13813 default:
13814 PyErr_Format(PyExc_ValueError,
13815 "unsupported format character '%c' (0x%x) "
13816 "at index %zd",
13817 (31<=c && c<=126) ? (char)c : '?',
13818 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013819 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013820 goto onError;
13821 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013822 /* pbuf is initialized here. */
13823 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013824 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013825 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13826 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013827 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013828 pindex++;
13829 }
13830 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13831 signobj = plus;
13832 len--;
13833 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013834 }
13835 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013836 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013837 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013838 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013839 else
13840 sign = 0;
13841 }
13842 if (width < len)
13843 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013844 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013845 if (fill != ' ') {
13846 assert(signobj != NULL);
13847 if (_PyAccu_Accumulate(&acc, signobj))
13848 goto onError;
13849 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013850 if (width > len)
13851 width--;
13852 }
13853 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013854 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013855 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013856 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013857 second = get_latin1_char(
13858 PyUnicode_READ(kind, pbuf, pindex + 1));
13859 pindex += 2;
13860 if (second == NULL ||
13861 _PyAccu_Accumulate(&acc, zero) ||
13862 _PyAccu_Accumulate(&acc, second))
13863 goto onError;
13864 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013865 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013866 width -= 2;
13867 if (width < 0)
13868 width = 0;
13869 len -= 2;
13870 }
13871 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013872 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013873 if (repeat_accumulate(&acc, fillobj, width - len))
13874 goto onError;
13875 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013876 }
13877 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013878 if (sign) {
13879 assert(signobj != NULL);
13880 if (_PyAccu_Accumulate(&acc, signobj))
13881 goto onError;
13882 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013883 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013884 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13885 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013886 second = get_latin1_char(
13887 PyUnicode_READ(kind, pbuf, pindex + 1));
13888 pindex += 2;
13889 if (second == NULL ||
13890 _PyAccu_Accumulate(&acc, zero) ||
13891 _PyAccu_Accumulate(&acc, second))
13892 goto onError;
13893 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013894 }
13895 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013896 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013897 if (temp != NULL) {
13898 assert(pbuf == PyUnicode_DATA(temp));
13899 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013900 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013901 else {
13902 const char *p = (const char *) pbuf;
13903 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013904 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013905 v = PyUnicode_FromKindAndData(kind, p, len);
13906 }
13907 if (v == NULL)
13908 goto onError;
13909 r = _PyAccu_Accumulate(&acc, v);
13910 Py_DECREF(v);
13911 if (r)
13912 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013913 if (width > len && repeat_accumulate(&acc, blank, width - len))
13914 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013915 if (dict && (argidx < arglen) && c != '%') {
13916 PyErr_SetString(PyExc_TypeError,
13917 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013918 goto onError;
13919 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013920 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013921 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013922 } /* until end */
13923 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013924 PyErr_SetString(PyExc_TypeError,
13925 "not all arguments converted during string formatting");
13926 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013927 }
13928
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013929 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013930 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013931 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013932 }
13933 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013934 Py_XDECREF(temp);
13935 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013936 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013937
Benjamin Peterson29060642009-01-31 22:14:21 +000013938 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013939 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013940 Py_XDECREF(temp);
13941 Py_XDECREF(second);
13942 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013943 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013944 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013945 }
13946 return NULL;
13947}
13948
Jeremy Hylton938ace62002-07-17 16:30:39 +000013949static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013950unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13951
Tim Peters6d6c1a32001-08-02 04:15:00 +000013952static PyObject *
13953unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13954{
Benjamin Peterson29060642009-01-31 22:14:21 +000013955 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013956 static char *kwlist[] = {"object", "encoding", "errors", 0};
13957 char *encoding = NULL;
13958 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013959
Benjamin Peterson14339b62009-01-31 16:36:08 +000013960 if (type != &PyUnicode_Type)
13961 return unicode_subtype_new(type, args, kwds);
13962 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013963 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013964 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013965 if (x == NULL) {
13966 Py_INCREF(unicode_empty);
13967 return unicode_empty;
13968 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013969 if (encoding == NULL && errors == NULL)
13970 return PyObject_Str(x);
13971 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013972 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013973}
13974
Guido van Rossume023fe02001-08-30 03:12:59 +000013975static PyObject *
13976unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13977{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013978 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013979 Py_ssize_t length, char_size;
13980 int share_wstr, share_utf8;
13981 unsigned int kind;
13982 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013983
Benjamin Peterson14339b62009-01-31 16:36:08 +000013984 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013985
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013986 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013987 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013988 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013989 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050013990 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013991 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013992 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013993 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013994
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013995 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013996 if (self == NULL) {
13997 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013998 return NULL;
13999 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014000 kind = PyUnicode_KIND(unicode);
14001 length = PyUnicode_GET_LENGTH(unicode);
14002
14003 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014004#ifdef Py_DEBUG
14005 _PyUnicode_HASH(self) = -1;
14006#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014007 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014008#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014009 _PyUnicode_STATE(self).interned = 0;
14010 _PyUnicode_STATE(self).kind = kind;
14011 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014012 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014013 _PyUnicode_STATE(self).ready = 1;
14014 _PyUnicode_WSTR(self) = NULL;
14015 _PyUnicode_UTF8_LENGTH(self) = 0;
14016 _PyUnicode_UTF8(self) = NULL;
14017 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014018 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014019
14020 share_utf8 = 0;
14021 share_wstr = 0;
14022 if (kind == PyUnicode_1BYTE_KIND) {
14023 char_size = 1;
14024 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14025 share_utf8 = 1;
14026 }
14027 else if (kind == PyUnicode_2BYTE_KIND) {
14028 char_size = 2;
14029 if (sizeof(wchar_t) == 2)
14030 share_wstr = 1;
14031 }
14032 else {
14033 assert(kind == PyUnicode_4BYTE_KIND);
14034 char_size = 4;
14035 if (sizeof(wchar_t) == 4)
14036 share_wstr = 1;
14037 }
14038
14039 /* Ensure we won't overflow the length. */
14040 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14041 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014042 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014043 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014044 data = PyObject_MALLOC((length + 1) * char_size);
14045 if (data == NULL) {
14046 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014047 goto onError;
14048 }
14049
Victor Stinnerc3c74152011-10-02 20:39:55 +020014050 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014051 if (share_utf8) {
14052 _PyUnicode_UTF8_LENGTH(self) = length;
14053 _PyUnicode_UTF8(self) = data;
14054 }
14055 if (share_wstr) {
14056 _PyUnicode_WSTR_LENGTH(self) = length;
14057 _PyUnicode_WSTR(self) = (wchar_t *)data;
14058 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014059
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014060 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014061 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014062 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014063#ifdef Py_DEBUG
14064 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14065#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014066 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014067 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014068
14069onError:
14070 Py_DECREF(unicode);
14071 Py_DECREF(self);
14072 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014073}
14074
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014075PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000014076 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014077\n\
Collin Winterd474ce82007-08-07 19:42:11 +000014078Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000014079encoding defaults to the current default string encoding.\n\
14080errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014081
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014082static PyObject *unicode_iter(PyObject *seq);
14083
Guido van Rossumd57fd912000-03-10 22:53:23 +000014084PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014085 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014086 "str", /* tp_name */
14087 sizeof(PyUnicodeObject), /* tp_size */
14088 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014089 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014090 (destructor)unicode_dealloc, /* tp_dealloc */
14091 0, /* tp_print */
14092 0, /* tp_getattr */
14093 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014094 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014095 unicode_repr, /* tp_repr */
14096 &unicode_as_number, /* tp_as_number */
14097 &unicode_as_sequence, /* tp_as_sequence */
14098 &unicode_as_mapping, /* tp_as_mapping */
14099 (hashfunc) unicode_hash, /* tp_hash*/
14100 0, /* tp_call*/
14101 (reprfunc) unicode_str, /* tp_str */
14102 PyObject_GenericGetAttr, /* tp_getattro */
14103 0, /* tp_setattro */
14104 0, /* tp_as_buffer */
14105 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014106 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014107 unicode_doc, /* tp_doc */
14108 0, /* tp_traverse */
14109 0, /* tp_clear */
14110 PyUnicode_RichCompare, /* tp_richcompare */
14111 0, /* tp_weaklistoffset */
14112 unicode_iter, /* tp_iter */
14113 0, /* tp_iternext */
14114 unicode_methods, /* tp_methods */
14115 0, /* tp_members */
14116 0, /* tp_getset */
14117 &PyBaseObject_Type, /* tp_base */
14118 0, /* tp_dict */
14119 0, /* tp_descr_get */
14120 0, /* tp_descr_set */
14121 0, /* tp_dictoffset */
14122 0, /* tp_init */
14123 0, /* tp_alloc */
14124 unicode_new, /* tp_new */
14125 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014126};
14127
14128/* Initialize the Unicode implementation */
14129
Victor Stinner3a50e702011-10-18 21:21:00 +020014130int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014131{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014132 int i;
14133
Thomas Wouters477c8d52006-05-27 19:21:47 +000014134 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014135 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014136 0x000A, /* LINE FEED */
14137 0x000D, /* CARRIAGE RETURN */
14138 0x001C, /* FILE SEPARATOR */
14139 0x001D, /* GROUP SEPARATOR */
14140 0x001E, /* RECORD SEPARATOR */
14141 0x0085, /* NEXT LINE */
14142 0x2028, /* LINE SEPARATOR */
14143 0x2029, /* PARAGRAPH SEPARATOR */
14144 };
14145
Fred Drakee4315f52000-05-09 19:53:39 +000014146 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014147 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014148 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014149 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014150 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014151
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014152 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014153 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014154 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014155 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014156
14157 /* initialize the linebreak bloom filter */
14158 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014159 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014160 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014161
14162 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014163
14164#ifdef HAVE_MBCS
14165 winver.dwOSVersionInfoSize = sizeof(winver);
14166 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14167 PyErr_SetFromWindowsErr(0);
14168 return -1;
14169 }
14170#endif
14171 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014172}
14173
14174/* Finalize the Unicode implementation */
14175
Christian Heimesa156e092008-02-16 07:38:31 +000014176int
14177PyUnicode_ClearFreeList(void)
14178{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014179 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014180}
14181
Guido van Rossumd57fd912000-03-10 22:53:23 +000014182void
Thomas Wouters78890102000-07-22 19:25:51 +000014183_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014184{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014185 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014186
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014187 Py_XDECREF(unicode_empty);
14188 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014189
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014190 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014191 if (unicode_latin1[i]) {
14192 Py_DECREF(unicode_latin1[i]);
14193 unicode_latin1[i] = NULL;
14194 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014195 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014196 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014197 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014198}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014199
Walter Dörwald16807132007-05-25 13:52:07 +000014200void
14201PyUnicode_InternInPlace(PyObject **p)
14202{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014203 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014204 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014205#ifdef Py_DEBUG
14206 assert(s != NULL);
14207 assert(_PyUnicode_CHECK(s));
14208#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014209 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014210 return;
14211#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014212 /* If it's a subclass, we don't really know what putting
14213 it in the interned dict might do. */
14214 if (!PyUnicode_CheckExact(s))
14215 return;
14216 if (PyUnicode_CHECK_INTERNED(s))
14217 return;
14218 if (interned == NULL) {
14219 interned = PyDict_New();
14220 if (interned == NULL) {
14221 PyErr_Clear(); /* Don't leave an exception */
14222 return;
14223 }
14224 }
14225 /* It might be that the GetItem call fails even
14226 though the key is present in the dictionary,
14227 namely when this happens during a stack overflow. */
14228 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014229 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014230 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014231
Benjamin Peterson29060642009-01-31 22:14:21 +000014232 if (t) {
14233 Py_INCREF(t);
14234 Py_DECREF(*p);
14235 *p = t;
14236 return;
14237 }
Walter Dörwald16807132007-05-25 13:52:07 +000014238
Benjamin Peterson14339b62009-01-31 16:36:08 +000014239 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014240 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014241 PyErr_Clear();
14242 PyThreadState_GET()->recursion_critical = 0;
14243 return;
14244 }
14245 PyThreadState_GET()->recursion_critical = 0;
14246 /* The two references in interned are not counted by refcnt.
14247 The deallocator will take care of this */
14248 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014249 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014250}
14251
14252void
14253PyUnicode_InternImmortal(PyObject **p)
14254{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014255 PyUnicode_InternInPlace(p);
14256 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014257 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014258 Py_INCREF(*p);
14259 }
Walter Dörwald16807132007-05-25 13:52:07 +000014260}
14261
14262PyObject *
14263PyUnicode_InternFromString(const char *cp)
14264{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014265 PyObject *s = PyUnicode_FromString(cp);
14266 if (s == NULL)
14267 return NULL;
14268 PyUnicode_InternInPlace(&s);
14269 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014270}
14271
Alexander Belopolsky40018472011-02-26 01:02:56 +000014272void
14273_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014274{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014275 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014276 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014277 Py_ssize_t i, n;
14278 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014279
Benjamin Peterson14339b62009-01-31 16:36:08 +000014280 if (interned == NULL || !PyDict_Check(interned))
14281 return;
14282 keys = PyDict_Keys(interned);
14283 if (keys == NULL || !PyList_Check(keys)) {
14284 PyErr_Clear();
14285 return;
14286 }
Walter Dörwald16807132007-05-25 13:52:07 +000014287
Benjamin Peterson14339b62009-01-31 16:36:08 +000014288 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14289 detector, interned unicode strings are not forcibly deallocated;
14290 rather, we give them their stolen references back, and then clear
14291 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014292
Benjamin Peterson14339b62009-01-31 16:36:08 +000014293 n = PyList_GET_SIZE(keys);
14294 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014295 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014296 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014297 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014298 if (PyUnicode_READY(s) == -1) {
14299 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014300 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014301 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014302 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014303 case SSTATE_NOT_INTERNED:
14304 /* XXX Shouldn't happen */
14305 break;
14306 case SSTATE_INTERNED_IMMORTAL:
14307 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014308 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014309 break;
14310 case SSTATE_INTERNED_MORTAL:
14311 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014312 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014313 break;
14314 default:
14315 Py_FatalError("Inconsistent interned string state.");
14316 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014317 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014318 }
14319 fprintf(stderr, "total size of all interned strings: "
14320 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14321 "mortal/immortal\n", mortal_size, immortal_size);
14322 Py_DECREF(keys);
14323 PyDict_Clear(interned);
14324 Py_DECREF(interned);
14325 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014326}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014327
14328
14329/********************* Unicode Iterator **************************/
14330
14331typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014332 PyObject_HEAD
14333 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014334 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014335} unicodeiterobject;
14336
14337static void
14338unicodeiter_dealloc(unicodeiterobject *it)
14339{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014340 _PyObject_GC_UNTRACK(it);
14341 Py_XDECREF(it->it_seq);
14342 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014343}
14344
14345static int
14346unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14347{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014348 Py_VISIT(it->it_seq);
14349 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014350}
14351
14352static PyObject *
14353unicodeiter_next(unicodeiterobject *it)
14354{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014355 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014356
Benjamin Peterson14339b62009-01-31 16:36:08 +000014357 assert(it != NULL);
14358 seq = it->it_seq;
14359 if (seq == NULL)
14360 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014361 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014362
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014363 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14364 int kind = PyUnicode_KIND(seq);
14365 void *data = PyUnicode_DATA(seq);
14366 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14367 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014368 if (item != NULL)
14369 ++it->it_index;
14370 return item;
14371 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014372
Benjamin Peterson14339b62009-01-31 16:36:08 +000014373 Py_DECREF(seq);
14374 it->it_seq = NULL;
14375 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014376}
14377
14378static PyObject *
14379unicodeiter_len(unicodeiterobject *it)
14380{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014381 Py_ssize_t len = 0;
14382 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014383 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014384 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014385}
14386
14387PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14388
14389static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014390 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014391 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014392 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014393};
14394
14395PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014396 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14397 "str_iterator", /* tp_name */
14398 sizeof(unicodeiterobject), /* tp_basicsize */
14399 0, /* tp_itemsize */
14400 /* methods */
14401 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14402 0, /* tp_print */
14403 0, /* tp_getattr */
14404 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014405 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014406 0, /* tp_repr */
14407 0, /* tp_as_number */
14408 0, /* tp_as_sequence */
14409 0, /* tp_as_mapping */
14410 0, /* tp_hash */
14411 0, /* tp_call */
14412 0, /* tp_str */
14413 PyObject_GenericGetAttr, /* tp_getattro */
14414 0, /* tp_setattro */
14415 0, /* tp_as_buffer */
14416 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14417 0, /* tp_doc */
14418 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14419 0, /* tp_clear */
14420 0, /* tp_richcompare */
14421 0, /* tp_weaklistoffset */
14422 PyObject_SelfIter, /* tp_iter */
14423 (iternextfunc)unicodeiter_next, /* tp_iternext */
14424 unicodeiter_methods, /* tp_methods */
14425 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014426};
14427
14428static PyObject *
14429unicode_iter(PyObject *seq)
14430{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014431 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014432
Benjamin Peterson14339b62009-01-31 16:36:08 +000014433 if (!PyUnicode_Check(seq)) {
14434 PyErr_BadInternalCall();
14435 return NULL;
14436 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014437 if (PyUnicode_READY(seq) == -1)
14438 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014439 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14440 if (it == NULL)
14441 return NULL;
14442 it->it_index = 0;
14443 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014444 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014445 _PyObject_GC_TRACK(it);
14446 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014447}
14448
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014449
14450size_t
14451Py_UNICODE_strlen(const Py_UNICODE *u)
14452{
14453 int res = 0;
14454 while(*u++)
14455 res++;
14456 return res;
14457}
14458
14459Py_UNICODE*
14460Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14461{
14462 Py_UNICODE *u = s1;
14463 while ((*u++ = *s2++));
14464 return s1;
14465}
14466
14467Py_UNICODE*
14468Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14469{
14470 Py_UNICODE *u = s1;
14471 while ((*u++ = *s2++))
14472 if (n-- == 0)
14473 break;
14474 return s1;
14475}
14476
14477Py_UNICODE*
14478Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14479{
14480 Py_UNICODE *u1 = s1;
14481 u1 += Py_UNICODE_strlen(u1);
14482 Py_UNICODE_strcpy(u1, s2);
14483 return s1;
14484}
14485
14486int
14487Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14488{
14489 while (*s1 && *s2 && *s1 == *s2)
14490 s1++, s2++;
14491 if (*s1 && *s2)
14492 return (*s1 < *s2) ? -1 : +1;
14493 if (*s1)
14494 return 1;
14495 if (*s2)
14496 return -1;
14497 return 0;
14498}
14499
14500int
14501Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14502{
14503 register Py_UNICODE u1, u2;
14504 for (; n != 0; n--) {
14505 u1 = *s1;
14506 u2 = *s2;
14507 if (u1 != u2)
14508 return (u1 < u2) ? -1 : +1;
14509 if (u1 == '\0')
14510 return 0;
14511 s1++;
14512 s2++;
14513 }
14514 return 0;
14515}
14516
14517Py_UNICODE*
14518Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14519{
14520 const Py_UNICODE *p;
14521 for (p = s; *p; p++)
14522 if (*p == c)
14523 return (Py_UNICODE*)p;
14524 return NULL;
14525}
14526
14527Py_UNICODE*
14528Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14529{
14530 const Py_UNICODE *p;
14531 p = s + Py_UNICODE_strlen(s);
14532 while (p != s) {
14533 p--;
14534 if (*p == c)
14535 return (Py_UNICODE*)p;
14536 }
14537 return NULL;
14538}
Victor Stinner331ea922010-08-10 16:37:20 +000014539
Victor Stinner71133ff2010-09-01 23:43:53 +000014540Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014541PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014542{
Victor Stinner577db2c2011-10-11 22:12:48 +020014543 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014544 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014545
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014546 if (!PyUnicode_Check(unicode)) {
14547 PyErr_BadArgument();
14548 return NULL;
14549 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014550 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014551 if (u == NULL)
14552 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014553 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014554 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014555 PyErr_NoMemory();
14556 return NULL;
14557 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014558 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014559 size *= sizeof(Py_UNICODE);
14560 copy = PyMem_Malloc(size);
14561 if (copy == NULL) {
14562 PyErr_NoMemory();
14563 return NULL;
14564 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014565 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014566 return copy;
14567}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014568
Georg Brandl66c221e2010-10-14 07:04:07 +000014569/* A _string module, to export formatter_parser and formatter_field_name_split
14570 to the string.Formatter class implemented in Python. */
14571
14572static PyMethodDef _string_methods[] = {
14573 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14574 METH_O, PyDoc_STR("split the argument as a field name")},
14575 {"formatter_parser", (PyCFunction) formatter_parser,
14576 METH_O, PyDoc_STR("parse the argument as a format string")},
14577 {NULL, NULL}
14578};
14579
14580static struct PyModuleDef _string_module = {
14581 PyModuleDef_HEAD_INIT,
14582 "_string",
14583 PyDoc_STR("string helper module"),
14584 0,
14585 _string_methods,
14586 NULL,
14587 NULL,
14588 NULL,
14589 NULL
14590};
14591
14592PyMODINIT_FUNC
14593PyInit__string(void)
14594{
14595 return PyModule_Create(&_string_module);
14596}
14597
14598
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014599#ifdef __cplusplus
14600}
14601#endif