blob: 2841b07e8ae3783542ee5af43b5791cef44492ff [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050044#include "bytes_methods.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000045
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000046#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000047#include <windows.h>
48#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000049
Guido van Rossumd57fd912000-03-10 22:53:23 +000050/* Endianness switches; defaults to little endian */
51
52#ifdef WORDS_BIGENDIAN
53# define BYTEORDER_IS_BIG_ENDIAN
54#else
55# define BYTEORDER_IS_LITTLE_ENDIAN
56#endif
57
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000058/* --- Globals ------------------------------------------------------------
59
60 The globals are initialized by the _PyUnicode_Init() API and should
61 not be used before calling that API.
62
63*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000064
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000065
66#ifdef __cplusplus
67extern "C" {
68#endif
69
Victor Stinner8faf8212011-12-08 22:14:11 +010070/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
71#define MAX_UNICODE 0x10ffff
72
Victor Stinner910337b2011-10-03 03:20:16 +020073#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020074# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020075#else
76# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
77#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020078
Victor Stinnere90fe6a2011-10-01 16:48:13 +020079#define _PyUnicode_UTF8(op) \
80 (((PyCompactUnicodeObject*)(op))->utf8)
81#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020082 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020083 assert(PyUnicode_IS_READY(op)), \
84 PyUnicode_IS_COMPACT_ASCII(op) ? \
85 ((char*)((PyASCIIObject*)(op) + 1)) : \
86 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020087#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020088 (((PyCompactUnicodeObject*)(op))->utf8_length)
89#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020090 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020091 assert(PyUnicode_IS_READY(op)), \
92 PyUnicode_IS_COMPACT_ASCII(op) ? \
93 ((PyASCIIObject*)(op))->length : \
94 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020095#define _PyUnicode_WSTR(op) \
96 (((PyASCIIObject*)(op))->wstr)
97#define _PyUnicode_WSTR_LENGTH(op) \
98 (((PyCompactUnicodeObject*)(op))->wstr_length)
99#define _PyUnicode_LENGTH(op) \
100 (((PyASCIIObject *)(op))->length)
101#define _PyUnicode_STATE(op) \
102 (((PyASCIIObject *)(op))->state)
103#define _PyUnicode_HASH(op) \
104 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200105#define _PyUnicode_KIND(op) \
106 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200107 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200108#define _PyUnicode_GET_LENGTH(op) \
109 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200110 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200111#define _PyUnicode_DATA_ANY(op) \
112 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200113
Victor Stinner910337b2011-10-03 03:20:16 +0200114#undef PyUnicode_READY
115#define PyUnicode_READY(op) \
116 (assert(_PyUnicode_CHECK(op)), \
117 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200118 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100119 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200120
Victor Stinnerc379ead2011-10-03 12:52:27 +0200121#define _PyUnicode_SHARE_UTF8(op) \
122 (assert(_PyUnicode_CHECK(op)), \
123 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
124 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
125#define _PyUnicode_SHARE_WSTR(op) \
126 (assert(_PyUnicode_CHECK(op)), \
127 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
128
Victor Stinner829c0ad2011-10-03 01:08:02 +0200129/* true if the Unicode object has an allocated UTF-8 memory block
130 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200131#define _PyUnicode_HAS_UTF8_MEMORY(op) \
132 (assert(_PyUnicode_CHECK(op)), \
133 (!PyUnicode_IS_COMPACT_ASCII(op) \
134 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200135 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
136
Victor Stinner03490912011-10-03 23:45:12 +0200137/* true if the Unicode object has an allocated wstr memory block
138 (not shared with other data) */
139#define _PyUnicode_HAS_WSTR_MEMORY(op) \
140 (assert(_PyUnicode_CHECK(op)), \
141 (_PyUnicode_WSTR(op) && \
142 (!PyUnicode_IS_READY(op) || \
143 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
144
Victor Stinner910337b2011-10-03 03:20:16 +0200145/* Generic helper macro to convert characters of different types.
146 from_type and to_type have to be valid type names, begin and end
147 are pointers to the source characters which should be of type
148 "from_type *". to is a pointer of type "to_type *" and points to the
149 buffer where the result characters are written to. */
150#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
151 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200152 to_type *_to = (to_type *) to; \
153 const from_type *_iter = (begin); \
154 const from_type *_end = (end); \
155 Py_ssize_t n = (_end) - (_iter); \
156 const from_type *_unrolled_end = \
157 _iter + (n & ~ (Py_ssize_t) 3); \
158 while (_iter < (_unrolled_end)) { \
159 _to[0] = (to_type) _iter[0]; \
160 _to[1] = (to_type) _iter[1]; \
161 _to[2] = (to_type) _iter[2]; \
162 _to[3] = (to_type) _iter[3]; \
163 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200164 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200165 while (_iter < (_end)) \
166 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200167 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200168
Walter Dörwald16807132007-05-25 13:52:07 +0000169/* This dictionary holds all interned unicode strings. Note that references
170 to strings in this dictionary are *not* counted in the string's ob_refcnt.
171 When the interned string reaches a refcnt of 0 the string deallocation
172 function will delete the reference from this dictionary.
173
174 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000175 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000176*/
177static PyObject *interned;
178
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000179/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200180static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000181
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200182/* List of static strings. */
183static _Py_Identifier *static_strings;
184
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000185/* Single character Unicode strings in the Latin-1 range are being
186 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200187static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000188
Christian Heimes190d79e2008-01-30 11:58:22 +0000189/* Fast detection of the most frequent whitespace characters */
190const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000191 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000192/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000193/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000194/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000195/* case 0x000C: * FORM FEED */
196/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000197 0, 1, 1, 1, 1, 1, 0, 0,
198 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000199/* case 0x001C: * FILE SEPARATOR */
200/* case 0x001D: * GROUP SEPARATOR */
201/* case 0x001E: * RECORD SEPARATOR */
202/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000203 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000204/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000205 1, 0, 0, 0, 0, 0, 0, 0,
206 0, 0, 0, 0, 0, 0, 0, 0,
207 0, 0, 0, 0, 0, 0, 0, 0,
208 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000209
Benjamin Peterson14339b62009-01-31 16:36:08 +0000210 0, 0, 0, 0, 0, 0, 0, 0,
211 0, 0, 0, 0, 0, 0, 0, 0,
212 0, 0, 0, 0, 0, 0, 0, 0,
213 0, 0, 0, 0, 0, 0, 0, 0,
214 0, 0, 0, 0, 0, 0, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0,
217 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000218};
219
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200220/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200221static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200222static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200223static void copy_characters(
224 PyObject *to, Py_ssize_t to_start,
225 PyObject *from, Py_ssize_t from_start,
226 Py_ssize_t how_many);
Victor Stinner488fa492011-12-12 00:01:39 +0100227static int unicode_modifiable(PyObject *unicode);
228
Victor Stinnerfe226c02011-10-03 03:52:20 +0200229
Alexander Belopolsky40018472011-02-26 01:02:56 +0000230static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200231unicode_fromascii(const unsigned char *s, Py_ssize_t size);
232static PyObject *
233_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
234static PyObject *
235_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
236static PyObject *
237_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
238
239static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000240unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000241 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100242 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000243 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
244
Alexander Belopolsky40018472011-02-26 01:02:56 +0000245static void
246raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300247 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100248 PyObject *unicode,
249 Py_ssize_t startpos, Py_ssize_t endpos,
250 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000251
Christian Heimes190d79e2008-01-30 11:58:22 +0000252/* Same for linebreaks */
253static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000254 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000255/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000256/* 0x000B, * LINE TABULATION */
257/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000258/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000259 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000260 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000261/* 0x001C, * FILE SEPARATOR */
262/* 0x001D, * GROUP SEPARATOR */
263/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000264 0, 0, 0, 0, 1, 1, 1, 0,
265 0, 0, 0, 0, 0, 0, 0, 0,
266 0, 0, 0, 0, 0, 0, 0, 0,
267 0, 0, 0, 0, 0, 0, 0, 0,
268 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000269
Benjamin Peterson14339b62009-01-31 16:36:08 +0000270 0, 0, 0, 0, 0, 0, 0, 0,
271 0, 0, 0, 0, 0, 0, 0, 0,
272 0, 0, 0, 0, 0, 0, 0, 0,
273 0, 0, 0, 0, 0, 0, 0, 0,
274 0, 0, 0, 0, 0, 0, 0, 0,
275 0, 0, 0, 0, 0, 0, 0, 0,
276 0, 0, 0, 0, 0, 0, 0, 0,
277 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000278};
279
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300280/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
281 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000282Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000283PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000284{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000285#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000286 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000287#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000288 /* This is actually an illegal character, so it should
289 not be passed to unichr. */
290 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000291#endif
292}
293
Victor Stinner910337b2011-10-03 03:20:16 +0200294#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200295int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100296_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200297{
298 PyASCIIObject *ascii;
299 unsigned int kind;
300
301 assert(PyUnicode_Check(op));
302
303 ascii = (PyASCIIObject *)op;
304 kind = ascii->state.kind;
305
Victor Stinnera3b334d2011-10-03 13:53:37 +0200306 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200307 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200308 assert(ascii->state.ready == 1);
309 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200310 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200311 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200312 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200313
Victor Stinnera41463c2011-10-04 01:05:08 +0200314 if (ascii->state.compact == 1) {
315 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200316 assert(kind == PyUnicode_1BYTE_KIND
317 || kind == PyUnicode_2BYTE_KIND
318 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200319 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200320 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200321 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100322 }
323 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200324 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
325
326 data = unicode->data.any;
327 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100328 assert(ascii->length == 0);
329 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200330 assert(ascii->state.compact == 0);
331 assert(ascii->state.ascii == 0);
332 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100333 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 assert(ascii->wstr != NULL);
335 assert(data == NULL);
336 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200337 }
338 else {
339 assert(kind == PyUnicode_1BYTE_KIND
340 || kind == PyUnicode_2BYTE_KIND
341 || kind == PyUnicode_4BYTE_KIND);
342 assert(ascii->state.compact == 0);
343 assert(ascii->state.ready == 1);
344 assert(data != NULL);
345 if (ascii->state.ascii) {
346 assert (compact->utf8 == data);
347 assert (compact->utf8_length == ascii->length);
348 }
349 else
350 assert (compact->utf8 != data);
351 }
352 }
353 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200354 if (
355#if SIZEOF_WCHAR_T == 2
356 kind == PyUnicode_2BYTE_KIND
357#else
358 kind == PyUnicode_4BYTE_KIND
359#endif
360 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200361 {
362 assert(ascii->wstr == data);
363 assert(compact->wstr_length == ascii->length);
364 } else
365 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200366 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200367
368 if (compact->utf8 == NULL)
369 assert(compact->utf8_length == 0);
370 if (ascii->wstr == NULL)
371 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200372 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200373 /* check that the best kind is used */
374 if (check_content && kind != PyUnicode_WCHAR_KIND)
375 {
376 Py_ssize_t i;
377 Py_UCS4 maxchar = 0;
378 void *data = PyUnicode_DATA(ascii);
379 for (i=0; i < ascii->length; i++)
380 {
381 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
382 if (ch > maxchar)
383 maxchar = ch;
384 }
385 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100386 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200387 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100388 assert(maxchar <= 255);
389 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200390 else
391 assert(maxchar < 128);
392 }
Victor Stinner77faf692011-11-20 18:56:05 +0100393 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200394 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100395 assert(maxchar <= 0xFFFF);
396 }
397 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200398 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100399 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100400 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200401 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400402 return 1;
403}
Victor Stinner910337b2011-10-03 03:20:16 +0200404#endif
405
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100406static PyObject*
407unicode_result_wchar(PyObject *unicode)
408{
409#ifndef Py_DEBUG
410 Py_ssize_t len;
411
412 assert(Py_REFCNT(unicode) == 1);
413
414 len = _PyUnicode_WSTR_LENGTH(unicode);
415 if (len == 0) {
416 Py_INCREF(unicode_empty);
417 Py_DECREF(unicode);
418 return unicode_empty;
419 }
420
421 if (len == 1) {
422 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
423 if (ch < 256) {
424 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
425 Py_DECREF(unicode);
426 return latin1_char;
427 }
428 }
429
430 if (_PyUnicode_Ready(unicode) < 0) {
431 Py_XDECREF(unicode);
432 return NULL;
433 }
434#else
435 /* don't make the result ready in debug mode to ensure that the caller
436 makes the string ready before using it */
437 assert(_PyUnicode_CheckConsistency(unicode, 1));
438#endif
439 return unicode;
440}
441
442static PyObject*
443unicode_result_ready(PyObject *unicode)
444{
445 Py_ssize_t length;
446
447 length = PyUnicode_GET_LENGTH(unicode);
448 if (length == 0) {
449 if (unicode != unicode_empty) {
450 Py_INCREF(unicode_empty);
451 Py_DECREF(unicode);
452 }
453 return unicode_empty;
454 }
455
456 if (length == 1) {
457 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
458 if (ch < 256) {
459 PyObject *latin1_char = unicode_latin1[ch];
460 if (latin1_char != NULL) {
461 if (unicode != latin1_char) {
462 Py_INCREF(latin1_char);
463 Py_DECREF(unicode);
464 }
465 return latin1_char;
466 }
467 else {
468 assert(_PyUnicode_CheckConsistency(unicode, 1));
469 Py_INCREF(unicode);
470 unicode_latin1[ch] = unicode;
471 return unicode;
472 }
473 }
474 }
475
476 assert(_PyUnicode_CheckConsistency(unicode, 1));
477 return unicode;
478}
479
480static PyObject*
481unicode_result(PyObject *unicode)
482{
483 assert(_PyUnicode_CHECK(unicode));
484 if (PyUnicode_IS_READY(unicode))
485 return unicode_result_ready(unicode);
486 else
487 return unicode_result_wchar(unicode);
488}
489
Victor Stinnerc4b49542011-12-11 22:44:26 +0100490static PyObject*
491unicode_result_unchanged(PyObject *unicode)
492{
493 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500494 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100495 return NULL;
496 Py_INCREF(unicode);
497 return unicode;
498 }
499 else
500 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100501 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100502}
503
Victor Stinner3a50e702011-10-18 21:21:00 +0200504#ifdef HAVE_MBCS
505static OSVERSIONINFOEX winver;
506#endif
507
Thomas Wouters477c8d52006-05-27 19:21:47 +0000508/* --- Bloom Filters ----------------------------------------------------- */
509
510/* stuff to implement simple "bloom filters" for Unicode characters.
511 to keep things simple, we use a single bitmask, using the least 5
512 bits from each unicode characters as the bit index. */
513
514/* the linebreak mask is set up by Unicode_Init below */
515
Antoine Pitrouf068f942010-01-13 14:19:12 +0000516#if LONG_BIT >= 128
517#define BLOOM_WIDTH 128
518#elif LONG_BIT >= 64
519#define BLOOM_WIDTH 64
520#elif LONG_BIT >= 32
521#define BLOOM_WIDTH 32
522#else
523#error "LONG_BIT is smaller than 32"
524#endif
525
Thomas Wouters477c8d52006-05-27 19:21:47 +0000526#define BLOOM_MASK unsigned long
527
528static BLOOM_MASK bloom_linebreak;
529
Antoine Pitrouf068f942010-01-13 14:19:12 +0000530#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
531#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000532
Benjamin Peterson29060642009-01-31 22:14:21 +0000533#define BLOOM_LINEBREAK(ch) \
534 ((ch) < 128U ? ascii_linebreak[(ch)] : \
535 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000536
Alexander Belopolsky40018472011-02-26 01:02:56 +0000537Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200538make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539{
540 /* calculate simple bloom-style bitmask for a given unicode string */
541
Antoine Pitrouf068f942010-01-13 14:19:12 +0000542 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543 Py_ssize_t i;
544
545 mask = 0;
546 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200547 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000548
549 return mask;
550}
551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200552#define BLOOM_MEMBER(mask, chr, str) \
553 (BLOOM(mask, chr) \
554 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000555
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200556/* Compilation of templated routines */
557
558#include "stringlib/asciilib.h"
559#include "stringlib/fastsearch.h"
560#include "stringlib/partition.h"
561#include "stringlib/split.h"
562#include "stringlib/count.h"
563#include "stringlib/find.h"
564#include "stringlib/find_max_char.h"
565#include "stringlib/localeutil.h"
566#include "stringlib/undef.h"
567
568#include "stringlib/ucs1lib.h"
569#include "stringlib/fastsearch.h"
570#include "stringlib/partition.h"
571#include "stringlib/split.h"
572#include "stringlib/count.h"
573#include "stringlib/find.h"
574#include "stringlib/find_max_char.h"
575#include "stringlib/localeutil.h"
576#include "stringlib/undef.h"
577
578#include "stringlib/ucs2lib.h"
579#include "stringlib/fastsearch.h"
580#include "stringlib/partition.h"
581#include "stringlib/split.h"
582#include "stringlib/count.h"
583#include "stringlib/find.h"
584#include "stringlib/find_max_char.h"
585#include "stringlib/localeutil.h"
586#include "stringlib/undef.h"
587
588#include "stringlib/ucs4lib.h"
589#include "stringlib/fastsearch.h"
590#include "stringlib/partition.h"
591#include "stringlib/split.h"
592#include "stringlib/count.h"
593#include "stringlib/find.h"
594#include "stringlib/find_max_char.h"
595#include "stringlib/localeutil.h"
596#include "stringlib/undef.h"
597
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200598#include "stringlib/unicodedefs.h"
599#include "stringlib/fastsearch.h"
600#include "stringlib/count.h"
601#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100602#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200603
Guido van Rossumd57fd912000-03-10 22:53:23 +0000604/* --- Unicode Object ----------------------------------------------------- */
605
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200606static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200607fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200608
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200609Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
610 Py_ssize_t size, Py_UCS4 ch,
611 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200612{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200613 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
614
615 switch (kind) {
616 case PyUnicode_1BYTE_KIND:
617 {
618 Py_UCS1 ch1 = (Py_UCS1) ch;
619 if (ch1 == ch)
620 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
621 else
622 return -1;
623 }
624 case PyUnicode_2BYTE_KIND:
625 {
626 Py_UCS2 ch2 = (Py_UCS2) ch;
627 if (ch2 == ch)
628 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
629 else
630 return -1;
631 }
632 case PyUnicode_4BYTE_KIND:
633 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
634 default:
635 assert(0);
636 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200637 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200638}
639
Victor Stinnerfe226c02011-10-03 03:52:20 +0200640static PyObject*
641resize_compact(PyObject *unicode, Py_ssize_t length)
642{
643 Py_ssize_t char_size;
644 Py_ssize_t struct_size;
645 Py_ssize_t new_size;
646 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100647 PyObject *new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200648 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100649 assert(PyUnicode_IS_COMPACT(unicode));
650
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200651 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100652 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200653 struct_size = sizeof(PyASCIIObject);
654 else
655 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200656 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200657
Victor Stinnerfe226c02011-10-03 03:52:20 +0200658 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
659 PyErr_NoMemory();
660 return NULL;
661 }
662 new_size = (struct_size + (length + 1) * char_size);
663
Victor Stinner84def372011-12-11 20:04:56 +0100664 _Py_DEC_REFTOTAL;
665 _Py_ForgetReference(unicode);
666
667 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
668 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100669 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200670 PyErr_NoMemory();
671 return NULL;
672 }
Victor Stinner84def372011-12-11 20:04:56 +0100673 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200674 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100675
Victor Stinnerfe226c02011-10-03 03:52:20 +0200676 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200677 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200678 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100679 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200680 _PyUnicode_WSTR_LENGTH(unicode) = length;
681 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200682 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
683 length, 0);
684 return unicode;
685}
686
Alexander Belopolsky40018472011-02-26 01:02:56 +0000687static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200688resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000689{
Victor Stinner95663112011-10-04 01:03:50 +0200690 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100691 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200692 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200693 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000694
Victor Stinnerfe226c02011-10-03 03:52:20 +0200695 if (PyUnicode_IS_READY(unicode)) {
696 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200697 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200698 void *data;
699
700 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200701 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200702 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
703 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200704
705 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
706 PyErr_NoMemory();
707 return -1;
708 }
709 new_size = (length + 1) * char_size;
710
Victor Stinner7a9105a2011-12-12 00:13:42 +0100711 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
712 {
713 PyObject_DEL(_PyUnicode_UTF8(unicode));
714 _PyUnicode_UTF8(unicode) = NULL;
715 _PyUnicode_UTF8_LENGTH(unicode) = 0;
716 }
717
Victor Stinnerfe226c02011-10-03 03:52:20 +0200718 data = (PyObject *)PyObject_REALLOC(data, new_size);
719 if (data == NULL) {
720 PyErr_NoMemory();
721 return -1;
722 }
723 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200724 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200725 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200726 _PyUnicode_WSTR_LENGTH(unicode) = length;
727 }
728 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200729 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200730 _PyUnicode_UTF8_LENGTH(unicode) = length;
731 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200732 _PyUnicode_LENGTH(unicode) = length;
733 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200734 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200735 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200736 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200737 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200738 }
Victor Stinner95663112011-10-04 01:03:50 +0200739 assert(_PyUnicode_WSTR(unicode) != NULL);
740
741 /* check for integer overflow */
742 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
743 PyErr_NoMemory();
744 return -1;
745 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100746 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200747 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100748 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200749 if (!wstr) {
750 PyErr_NoMemory();
751 return -1;
752 }
753 _PyUnicode_WSTR(unicode) = wstr;
754 _PyUnicode_WSTR(unicode)[length] = 0;
755 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200756 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000757 return 0;
758}
759
Victor Stinnerfe226c02011-10-03 03:52:20 +0200760static PyObject*
761resize_copy(PyObject *unicode, Py_ssize_t length)
762{
763 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100764 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200765 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100766
Benjamin Petersonbac79492012-01-14 13:34:47 -0500767 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100768 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200769
770 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
771 if (copy == NULL)
772 return NULL;
773
774 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200775 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200776 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200777 }
778 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200779 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100780
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200781 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200782 if (w == NULL)
783 return NULL;
784 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
785 copy_length = Py_MIN(copy_length, length);
786 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
787 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200788 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200789 }
790}
791
Guido van Rossumd57fd912000-03-10 22:53:23 +0000792/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000793 Ux0000 terminated; some code (e.g. new_identifier)
794 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000795
796 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000797 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000798
799*/
800
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200801#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200802static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200803#endif
804
Alexander Belopolsky40018472011-02-26 01:02:56 +0000805static PyUnicodeObject *
806_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000807{
808 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200809 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000810
Thomas Wouters477c8d52006-05-27 19:21:47 +0000811 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000812 if (length == 0 && unicode_empty != NULL) {
813 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200814 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000815 }
816
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000817 /* Ensure we won't overflow the size. */
818 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
819 return (PyUnicodeObject *)PyErr_NoMemory();
820 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200821 if (length < 0) {
822 PyErr_SetString(PyExc_SystemError,
823 "Negative size passed to _PyUnicode_New");
824 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000825 }
826
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200827#ifdef Py_DEBUG
828 ++unicode_old_new_calls;
829#endif
830
831 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
832 if (unicode == NULL)
833 return NULL;
834 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
835 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
836 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100837 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000838 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100839 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000840 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200841
Jeremy Hyltond8082792003-09-16 19:41:39 +0000842 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000843 * the caller fails before initializing str -- unicode_resize()
844 * reads str[0], and the Keep-Alive optimization can keep memory
845 * allocated for str alive across a call to unicode_dealloc(unicode).
846 * We don't want unicode_resize to read uninitialized memory in
847 * that case.
848 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200849 _PyUnicode_WSTR(unicode)[0] = 0;
850 _PyUnicode_WSTR(unicode)[length] = 0;
851 _PyUnicode_WSTR_LENGTH(unicode) = length;
852 _PyUnicode_HASH(unicode) = -1;
853 _PyUnicode_STATE(unicode).interned = 0;
854 _PyUnicode_STATE(unicode).kind = 0;
855 _PyUnicode_STATE(unicode).compact = 0;
856 _PyUnicode_STATE(unicode).ready = 0;
857 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200858 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200859 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200860 _PyUnicode_UTF8(unicode) = NULL;
861 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100862 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000863 return unicode;
864}
865
Victor Stinnerf42dc442011-10-02 23:33:16 +0200866static const char*
867unicode_kind_name(PyObject *unicode)
868{
Victor Stinner42dfd712011-10-03 14:41:45 +0200869 /* don't check consistency: unicode_kind_name() is called from
870 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200871 if (!PyUnicode_IS_COMPACT(unicode))
872 {
873 if (!PyUnicode_IS_READY(unicode))
874 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600875 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200876 {
877 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200878 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200879 return "legacy ascii";
880 else
881 return "legacy latin1";
882 case PyUnicode_2BYTE_KIND:
883 return "legacy UCS2";
884 case PyUnicode_4BYTE_KIND:
885 return "legacy UCS4";
886 default:
887 return "<legacy invalid kind>";
888 }
889 }
890 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600891 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200892 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200893 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200894 return "ascii";
895 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200896 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200897 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200898 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200899 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200900 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200901 default:
902 return "<invalid compact kind>";
903 }
904}
905
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200906#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200907static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200908
909/* Functions wrapping macros for use in debugger */
910char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200911 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200912}
913
914void *_PyUnicode_compact_data(void *unicode) {
915 return _PyUnicode_COMPACT_DATA(unicode);
916}
917void *_PyUnicode_data(void *unicode){
918 printf("obj %p\n", unicode);
919 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
920 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
921 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
922 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
923 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
924 return PyUnicode_DATA(unicode);
925}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200926
927void
928_PyUnicode_Dump(PyObject *op)
929{
930 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200931 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
932 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
933 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200934
Victor Stinnera849a4b2011-10-03 12:12:11 +0200935 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200936 {
937 if (ascii->state.ascii)
938 data = (ascii + 1);
939 else
940 data = (compact + 1);
941 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200942 else
943 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200944 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
945
Victor Stinnera849a4b2011-10-03 12:12:11 +0200946 if (ascii->wstr == data)
947 printf("shared ");
948 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200949
Victor Stinnera3b334d2011-10-03 13:53:37 +0200950 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200951 printf(" (%zu), ", compact->wstr_length);
952 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
953 printf("shared ");
954 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200955 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200956 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200957}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200958#endif
959
960PyObject *
961PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
962{
963 PyObject *obj;
964 PyCompactUnicodeObject *unicode;
965 void *data;
966 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200967 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200968 Py_ssize_t char_size;
969 Py_ssize_t struct_size;
970
971 /* Optimization for empty strings */
972 if (size == 0 && unicode_empty != NULL) {
973 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200974 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200975 }
976
977#ifdef Py_DEBUG
978 ++unicode_new_new_calls;
979#endif
980
Victor Stinner9e9d6892011-10-04 01:02:02 +0200981 is_ascii = 0;
982 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200983 struct_size = sizeof(PyCompactUnicodeObject);
984 if (maxchar < 128) {
985 kind_state = PyUnicode_1BYTE_KIND;
986 char_size = 1;
987 is_ascii = 1;
988 struct_size = sizeof(PyASCIIObject);
989 }
990 else if (maxchar < 256) {
991 kind_state = PyUnicode_1BYTE_KIND;
992 char_size = 1;
993 }
994 else if (maxchar < 65536) {
995 kind_state = PyUnicode_2BYTE_KIND;
996 char_size = 2;
997 if (sizeof(wchar_t) == 2)
998 is_sharing = 1;
999 }
1000 else {
Victor Stinner15e9ed22012-02-22 13:36:20 +01001001 assert(maxchar <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001002 kind_state = PyUnicode_4BYTE_KIND;
1003 char_size = 4;
1004 if (sizeof(wchar_t) == 4)
1005 is_sharing = 1;
1006 }
1007
1008 /* Ensure we won't overflow the size. */
1009 if (size < 0) {
1010 PyErr_SetString(PyExc_SystemError,
1011 "Negative size passed to PyUnicode_New");
1012 return NULL;
1013 }
1014 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1015 return PyErr_NoMemory();
1016
1017 /* Duplicated allocation code from _PyObject_New() instead of a call to
1018 * PyObject_New() so we are able to allocate space for the object and
1019 * it's data buffer.
1020 */
1021 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1022 if (obj == NULL)
1023 return PyErr_NoMemory();
1024 obj = PyObject_INIT(obj, &PyUnicode_Type);
1025 if (obj == NULL)
1026 return NULL;
1027
1028 unicode = (PyCompactUnicodeObject *)obj;
1029 if (is_ascii)
1030 data = ((PyASCIIObject*)obj) + 1;
1031 else
1032 data = unicode + 1;
1033 _PyUnicode_LENGTH(unicode) = size;
1034 _PyUnicode_HASH(unicode) = -1;
1035 _PyUnicode_STATE(unicode).interned = 0;
1036 _PyUnicode_STATE(unicode).kind = kind_state;
1037 _PyUnicode_STATE(unicode).compact = 1;
1038 _PyUnicode_STATE(unicode).ready = 1;
1039 _PyUnicode_STATE(unicode).ascii = is_ascii;
1040 if (is_ascii) {
1041 ((char*)data)[size] = 0;
1042 _PyUnicode_WSTR(unicode) = NULL;
1043 }
1044 else if (kind_state == PyUnicode_1BYTE_KIND) {
1045 ((char*)data)[size] = 0;
1046 _PyUnicode_WSTR(unicode) = NULL;
1047 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001048 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001049 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001050 }
1051 else {
1052 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001053 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054 if (kind_state == PyUnicode_2BYTE_KIND)
1055 ((Py_UCS2*)data)[size] = 0;
1056 else /* kind_state == PyUnicode_4BYTE_KIND */
1057 ((Py_UCS4*)data)[size] = 0;
1058 if (is_sharing) {
1059 _PyUnicode_WSTR_LENGTH(unicode) = size;
1060 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1061 }
1062 else {
1063 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1064 _PyUnicode_WSTR(unicode) = NULL;
1065 }
1066 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01001067 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001068 return obj;
1069}
1070
1071#if SIZEOF_WCHAR_T == 2
1072/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1073 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001074 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001075
1076 This function assumes that unicode can hold one more code point than wstr
1077 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001078static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001079unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001080 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001081{
1082 const wchar_t *iter;
1083 Py_UCS4 *ucs4_out;
1084
Victor Stinner910337b2011-10-03 03:20:16 +02001085 assert(unicode != NULL);
1086 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001087 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1088 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1089
1090 for (iter = begin; iter < end; ) {
1091 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1092 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001093 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1094 && (iter+1) < end
1095 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001096 {
Victor Stinner551ac952011-11-29 22:58:13 +01001097 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001098 iter += 2;
1099 }
1100 else {
1101 *ucs4_out++ = *iter;
1102 iter++;
1103 }
1104 }
1105 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1106 _PyUnicode_GET_LENGTH(unicode)));
1107
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001108}
1109#endif
1110
Victor Stinnercd9950f2011-10-02 00:34:53 +02001111static int
Victor Stinner488fa492011-12-12 00:01:39 +01001112unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001113{
Victor Stinner488fa492011-12-12 00:01:39 +01001114 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001115 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001116 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001117 return -1;
1118 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001119 return 0;
1120}
1121
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001122static int
1123_copy_characters(PyObject *to, Py_ssize_t to_start,
1124 PyObject *from, Py_ssize_t from_start,
1125 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001126{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001127 unsigned int from_kind, to_kind;
1128 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001129 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001130
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001131 assert(PyUnicode_Check(from));
1132 assert(PyUnicode_Check(to));
1133 assert(PyUnicode_IS_READY(from));
1134 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001135
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001136 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1137 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1138 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001139
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001140 if (how_many == 0)
1141 return 0;
1142
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001143 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001144 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001145 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001146 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001147
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001148#ifdef Py_DEBUG
1149 if (!check_maxchar
1150 && (from_kind > to_kind
1151 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001152 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001153 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1154 Py_UCS4 ch;
1155 Py_ssize_t i;
1156 for (i=0; i < how_many; i++) {
1157 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1158 assert(ch <= to_maxchar);
1159 }
1160 }
1161#endif
1162 fast = (from_kind == to_kind);
1163 if (check_maxchar
1164 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1165 {
1166 /* deny latin1 => ascii */
1167 fast = 0;
1168 }
1169
1170 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001171 Py_MEMCPY((char*)to_data + to_kind * to_start,
1172 (char*)from_data + from_kind * from_start,
1173 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001174 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001175 else if (from_kind == PyUnicode_1BYTE_KIND
1176 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001177 {
1178 _PyUnicode_CONVERT_BYTES(
1179 Py_UCS1, Py_UCS2,
1180 PyUnicode_1BYTE_DATA(from) + from_start,
1181 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1182 PyUnicode_2BYTE_DATA(to) + to_start
1183 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001184 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001185 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001186 && to_kind == PyUnicode_4BYTE_KIND)
1187 {
1188 _PyUnicode_CONVERT_BYTES(
1189 Py_UCS1, Py_UCS4,
1190 PyUnicode_1BYTE_DATA(from) + from_start,
1191 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1192 PyUnicode_4BYTE_DATA(to) + to_start
1193 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001194 }
1195 else if (from_kind == PyUnicode_2BYTE_KIND
1196 && to_kind == PyUnicode_4BYTE_KIND)
1197 {
1198 _PyUnicode_CONVERT_BYTES(
1199 Py_UCS2, Py_UCS4,
1200 PyUnicode_2BYTE_DATA(from) + from_start,
1201 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1202 PyUnicode_4BYTE_DATA(to) + to_start
1203 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001204 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001205 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001206 /* check if max_char(from substring) <= max_char(to) */
1207 if (from_kind > to_kind
1208 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001209 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001210 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001211 /* slow path to check for character overflow */
1212 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001213 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001214 Py_ssize_t i;
1215
Victor Stinner56c161a2011-10-06 02:47:11 +02001216#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001217 for (i=0; i < how_many; i++) {
1218 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001219 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001220 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1221 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001222#else
1223 if (!check_maxchar) {
1224 for (i=0; i < how_many; i++) {
1225 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1226 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1227 }
1228 }
1229 else {
1230 for (i=0; i < how_many; i++) {
1231 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1232 if (ch > to_maxchar)
1233 return 1;
1234 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1235 }
1236 }
1237#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001238 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001239 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001240 assert(0 && "inconsistent state");
1241 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001242 }
1243 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001244 return 0;
1245}
1246
1247static void
1248copy_characters(PyObject *to, Py_ssize_t to_start,
1249 PyObject *from, Py_ssize_t from_start,
1250 Py_ssize_t how_many)
1251{
1252 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1253}
1254
1255Py_ssize_t
1256PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1257 PyObject *from, Py_ssize_t from_start,
1258 Py_ssize_t how_many)
1259{
1260 int err;
1261
1262 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1263 PyErr_BadInternalCall();
1264 return -1;
1265 }
1266
Benjamin Petersonbac79492012-01-14 13:34:47 -05001267 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001268 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001269 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001270 return -1;
1271
1272 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1273 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1274 PyErr_Format(PyExc_SystemError,
1275 "Cannot write %zi characters at %zi "
1276 "in a string of %zi characters",
1277 how_many, to_start, PyUnicode_GET_LENGTH(to));
1278 return -1;
1279 }
1280
1281 if (how_many == 0)
1282 return 0;
1283
Victor Stinner488fa492011-12-12 00:01:39 +01001284 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001285 return -1;
1286
1287 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1288 if (err) {
1289 PyErr_Format(PyExc_SystemError,
1290 "Cannot copy %s characters "
1291 "into a string of %s characters",
1292 unicode_kind_name(from),
1293 unicode_kind_name(to));
1294 return -1;
1295 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001296 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001297}
1298
Victor Stinner17222162011-09-28 22:15:37 +02001299/* Find the maximum code point and count the number of surrogate pairs so a
1300 correct string length can be computed before converting a string to UCS4.
1301 This function counts single surrogates as a character and not as a pair.
1302
1303 Return 0 on success, or -1 on error. */
1304static int
1305find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1306 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001307{
1308 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001309 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001310
Victor Stinnerc53be962011-10-02 21:33:54 +02001311 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001312 *num_surrogates = 0;
1313 *maxchar = 0;
1314
1315 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001317 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1318 && (iter+1) < end
1319 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001321 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001322 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001323 iter += 2;
1324 }
1325 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001326#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001327 {
1328 ch = *iter;
1329 iter++;
1330 }
1331 if (ch > *maxchar) {
1332 *maxchar = ch;
1333 if (*maxchar > MAX_UNICODE) {
1334 PyErr_Format(PyExc_ValueError,
1335 "character U+%x is not in range [U+0000; U+10ffff]",
1336 ch);
1337 return -1;
1338 }
1339 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001340 }
1341 return 0;
1342}
1343
1344#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001345static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001346#endif
1347
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001348int
1349_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350{
1351 wchar_t *end;
1352 Py_UCS4 maxchar = 0;
1353 Py_ssize_t num_surrogates;
1354#if SIZEOF_WCHAR_T == 2
1355 Py_ssize_t length_wo_surrogates;
1356#endif
1357
Georg Brandl7597add2011-10-05 16:36:47 +02001358 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001359 strings were created using _PyObject_New() and where no canonical
1360 representation (the str field) has been set yet aka strings
1361 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001362 assert(_PyUnicode_CHECK(unicode));
1363 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001364 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001365 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001366 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001367 /* Actually, it should neither be interned nor be anything else: */
1368 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001369
1370#ifdef Py_DEBUG
1371 ++unicode_ready_calls;
1372#endif
1373
1374 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001375 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001376 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001377 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001378
1379 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001380 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1381 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001382 PyErr_NoMemory();
1383 return -1;
1384 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001385 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001386 _PyUnicode_WSTR(unicode), end,
1387 PyUnicode_1BYTE_DATA(unicode));
1388 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1389 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1390 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1391 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001392 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001393 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001394 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001395 }
1396 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001397 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001398 _PyUnicode_UTF8(unicode) = NULL;
1399 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001400 }
1401 PyObject_FREE(_PyUnicode_WSTR(unicode));
1402 _PyUnicode_WSTR(unicode) = NULL;
1403 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1404 }
1405 /* In this case we might have to convert down from 4-byte native
1406 wchar_t to 2-byte unicode. */
1407 else if (maxchar < 65536) {
1408 assert(num_surrogates == 0 &&
1409 "FindMaxCharAndNumSurrogatePairs() messed up");
1410
Victor Stinner506f5922011-09-28 22:34:18 +02001411#if SIZEOF_WCHAR_T == 2
1412 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001413 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001414 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1415 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1416 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001417 _PyUnicode_UTF8(unicode) = NULL;
1418 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001419#else
1420 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001421 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001422 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001423 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001424 PyErr_NoMemory();
1425 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001426 }
Victor Stinner506f5922011-09-28 22:34:18 +02001427 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1428 _PyUnicode_WSTR(unicode), end,
1429 PyUnicode_2BYTE_DATA(unicode));
1430 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1431 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1432 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001433 _PyUnicode_UTF8(unicode) = NULL;
1434 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001435 PyObject_FREE(_PyUnicode_WSTR(unicode));
1436 _PyUnicode_WSTR(unicode) = NULL;
1437 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1438#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001439 }
1440 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1441 else {
1442#if SIZEOF_WCHAR_T == 2
1443 /* in case the native representation is 2-bytes, we need to allocate a
1444 new normalized 4-byte version. */
1445 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001446 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1447 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001448 PyErr_NoMemory();
1449 return -1;
1450 }
1451 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1452 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001453 _PyUnicode_UTF8(unicode) = NULL;
1454 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001455 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1456 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001457 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001458 PyObject_FREE(_PyUnicode_WSTR(unicode));
1459 _PyUnicode_WSTR(unicode) = NULL;
1460 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1461#else
1462 assert(num_surrogates == 0);
1463
Victor Stinnerc3c74152011-10-02 20:39:55 +02001464 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001465 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001466 _PyUnicode_UTF8(unicode) = NULL;
1467 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001468 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1469#endif
1470 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1471 }
1472 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001473 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001474 return 0;
1475}
1476
Alexander Belopolsky40018472011-02-26 01:02:56 +00001477static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001478unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001479{
Walter Dörwald16807132007-05-25 13:52:07 +00001480 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001481 case SSTATE_NOT_INTERNED:
1482 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001483
Benjamin Peterson29060642009-01-31 22:14:21 +00001484 case SSTATE_INTERNED_MORTAL:
1485 /* revive dead object temporarily for DelItem */
1486 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001487 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001488 Py_FatalError(
1489 "deletion of interned string failed");
1490 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001491
Benjamin Peterson29060642009-01-31 22:14:21 +00001492 case SSTATE_INTERNED_IMMORTAL:
1493 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001494
Benjamin Peterson29060642009-01-31 22:14:21 +00001495 default:
1496 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001497 }
1498
Victor Stinner03490912011-10-03 23:45:12 +02001499 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001500 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001501 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001502 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001503 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1504 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001505
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001506 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001507}
1508
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001509#ifdef Py_DEBUG
1510static int
1511unicode_is_singleton(PyObject *unicode)
1512{
1513 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1514 if (unicode == unicode_empty)
1515 return 1;
1516 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1517 {
1518 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1519 if (ch < 256 && unicode_latin1[ch] == unicode)
1520 return 1;
1521 }
1522 return 0;
1523}
1524#endif
1525
Alexander Belopolsky40018472011-02-26 01:02:56 +00001526static int
Victor Stinner488fa492011-12-12 00:01:39 +01001527unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001528{
Victor Stinner488fa492011-12-12 00:01:39 +01001529 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001530 if (Py_REFCNT(unicode) != 1)
1531 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001532 if (_PyUnicode_HASH(unicode) != -1)
1533 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001534 if (PyUnicode_CHECK_INTERNED(unicode))
1535 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001536 if (!PyUnicode_CheckExact(unicode))
1537 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001538#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001539 /* singleton refcount is greater than 1 */
1540 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001541#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001542 return 1;
1543}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001544
Victor Stinnerfe226c02011-10-03 03:52:20 +02001545static int
1546unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1547{
1548 PyObject *unicode;
1549 Py_ssize_t old_length;
1550
1551 assert(p_unicode != NULL);
1552 unicode = *p_unicode;
1553
1554 assert(unicode != NULL);
1555 assert(PyUnicode_Check(unicode));
1556 assert(0 <= length);
1557
Victor Stinner910337b2011-10-03 03:20:16 +02001558 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001559 old_length = PyUnicode_WSTR_LENGTH(unicode);
1560 else
1561 old_length = PyUnicode_GET_LENGTH(unicode);
1562 if (old_length == length)
1563 return 0;
1564
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001565 if (length == 0) {
1566 Py_DECREF(*p_unicode);
1567 *p_unicode = unicode_empty;
1568 Py_INCREF(*p_unicode);
1569 return 0;
1570 }
1571
Victor Stinner488fa492011-12-12 00:01:39 +01001572 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001573 PyObject *copy = resize_copy(unicode, length);
1574 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001575 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001576 Py_DECREF(*p_unicode);
1577 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001578 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001579 }
1580
Victor Stinnerfe226c02011-10-03 03:52:20 +02001581 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001582 PyObject *new_unicode = resize_compact(unicode, length);
1583 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001584 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001585 *p_unicode = new_unicode;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001586 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001587 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001588 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001589 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001590}
1591
Alexander Belopolsky40018472011-02-26 01:02:56 +00001592int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001593PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001594{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001595 PyObject *unicode;
1596 if (p_unicode == NULL) {
1597 PyErr_BadInternalCall();
1598 return -1;
1599 }
1600 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001601 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001602 {
1603 PyErr_BadInternalCall();
1604 return -1;
1605 }
1606 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001607}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001608
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001609static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001610unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001611{
1612 PyObject *result;
1613 assert(PyUnicode_IS_READY(*p_unicode));
1614 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1615 return 0;
1616 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1617 maxchar);
1618 if (result == NULL)
1619 return -1;
1620 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1621 PyUnicode_GET_LENGTH(*p_unicode));
1622 Py_DECREF(*p_unicode);
1623 *p_unicode = result;
1624 return 0;
1625}
1626
1627static int
1628unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1629 Py_UCS4 ch)
1630{
Victor Stinner15e9ed22012-02-22 13:36:20 +01001631 assert(ch <= MAX_UNICODE);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001632 if (unicode_widen(p_unicode, ch) < 0)
1633 return -1;
1634 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1635 PyUnicode_DATA(*p_unicode),
1636 (*pos)++, ch);
1637 return 0;
1638}
1639
Victor Stinnerc5166102012-02-22 13:55:02 +01001640/* Copy a ASCII or latin1 char* string into a Python Unicode string.
1641 Return the length of the input string.
1642
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001643 WARNING: The function doesn't copy the terminating null character and
1644 doesn't check the maximum character (may write a latin1 character in an
1645 ASCII string). */
Victor Stinnerc5166102012-02-22 13:55:02 +01001646static Py_ssize_t
1647unicode_write_cstr(PyObject *unicode, Py_ssize_t index, const char *str)
1648{
1649 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1650 void *data = PyUnicode_DATA(unicode);
1651
1652 switch (kind) {
1653 case PyUnicode_1BYTE_KIND: {
1654 Py_ssize_t len = strlen(str);
1655 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001656 memcpy((char *) data + index, str, len);
Victor Stinnerc5166102012-02-22 13:55:02 +01001657 return len;
1658 }
1659 case PyUnicode_2BYTE_KIND: {
1660 Py_UCS2 *start = (Py_UCS2 *)data + index;
1661 Py_UCS2 *ucs2 = start;
1662 assert(index <= PyUnicode_GET_LENGTH(unicode));
1663
1664 for (; *str; ++ucs2, ++str)
1665 *ucs2 = (Py_UCS2)*str;
1666
1667 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
1668 return ucs2 - start;
1669 }
1670 default: {
1671 Py_UCS4 *start = (Py_UCS4 *)data + index;
1672 Py_UCS4 *ucs4 = start;
1673 assert(kind == PyUnicode_4BYTE_KIND);
1674 assert(index <= PyUnicode_GET_LENGTH(unicode));
1675
1676 for (; *str; ++ucs4, ++str)
1677 *ucs4 = (Py_UCS4)*str;
1678
1679 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
1680 return ucs4 - start;
1681 }
1682 }
1683}
1684
1685
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001686static PyObject*
1687get_latin1_char(unsigned char ch)
1688{
Victor Stinnera464fc12011-10-02 20:39:30 +02001689 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001690 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001691 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001692 if (!unicode)
1693 return NULL;
1694 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001695 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001696 unicode_latin1[ch] = unicode;
1697 }
1698 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001699 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001700}
1701
Alexander Belopolsky40018472011-02-26 01:02:56 +00001702PyObject *
1703PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001704{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001705 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001706 Py_UCS4 maxchar = 0;
1707 Py_ssize_t num_surrogates;
1708
1709 if (u == NULL)
1710 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001711
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001712 /* If the Unicode data is known at construction time, we can apply
1713 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001714
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001715 /* Optimization for empty strings */
1716 if (size == 0 && unicode_empty != NULL) {
1717 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001718 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001719 }
Tim Petersced69f82003-09-16 20:30:58 +00001720
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001721 /* Single character Unicode objects in the Latin-1 range are
1722 shared when using this constructor */
1723 if (size == 1 && *u < 256)
1724 return get_latin1_char((unsigned char)*u);
1725
1726 /* If not empty and not single character, copy the Unicode data
1727 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001728 if (find_maxchar_surrogates(u, u + size,
1729 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001730 return NULL;
1731
Victor Stinner8faf8212011-12-08 22:14:11 +01001732 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001733 if (!unicode)
1734 return NULL;
1735
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001736 switch (PyUnicode_KIND(unicode)) {
1737 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001738 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001739 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1740 break;
1741 case PyUnicode_2BYTE_KIND:
1742#if Py_UNICODE_SIZE == 2
1743 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1744#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001745 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001746 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1747#endif
1748 break;
1749 case PyUnicode_4BYTE_KIND:
1750#if SIZEOF_WCHAR_T == 2
1751 /* This is the only case which has to process surrogates, thus
1752 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001753 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001754#else
1755 assert(num_surrogates == 0);
1756 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1757#endif
1758 break;
1759 default:
1760 assert(0 && "Impossible state");
1761 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001762
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001763 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001764}
1765
Alexander Belopolsky40018472011-02-26 01:02:56 +00001766PyObject *
1767PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001768{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001769 if (size < 0) {
1770 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001771 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001772 return NULL;
1773 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001774 if (u != NULL)
1775 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1776 else
1777 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001778}
1779
Alexander Belopolsky40018472011-02-26 01:02:56 +00001780PyObject *
1781PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001782{
1783 size_t size = strlen(u);
1784 if (size > PY_SSIZE_T_MAX) {
1785 PyErr_SetString(PyExc_OverflowError, "input too long");
1786 return NULL;
1787 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001788 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001789}
1790
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001791PyObject *
1792_PyUnicode_FromId(_Py_Identifier *id)
1793{
1794 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001795 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1796 strlen(id->string),
1797 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001798 if (!id->object)
1799 return NULL;
1800 PyUnicode_InternInPlace(&id->object);
1801 assert(!id->next);
1802 id->next = static_strings;
1803 static_strings = id;
1804 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001805 return id->object;
1806}
1807
1808void
1809_PyUnicode_ClearStaticStrings()
1810{
1811 _Py_Identifier *i;
1812 for (i = static_strings; i; i = i->next) {
1813 Py_DECREF(i->object);
1814 i->object = NULL;
1815 i->next = NULL;
1816 }
1817}
1818
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001819/* Internal function, don't check maximum character */
1820
Victor Stinnere57b1c02011-09-28 22:20:48 +02001821static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001822unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001823{
Victor Stinner785938e2011-12-11 20:09:03 +01001824 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001825 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001826#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001827 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001828#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001829 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001830 }
Victor Stinner785938e2011-12-11 20:09:03 +01001831 unicode = PyUnicode_New(size, 127);
1832 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001833 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001834 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1835 assert(_PyUnicode_CheckConsistency(unicode, 1));
1836 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001837}
1838
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001839static Py_UCS4
1840kind_maxchar_limit(unsigned int kind)
1841{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001842 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001843 case PyUnicode_1BYTE_KIND:
1844 return 0x80;
1845 case PyUnicode_2BYTE_KIND:
1846 return 0x100;
1847 case PyUnicode_4BYTE_KIND:
1848 return 0x10000;
1849 default:
1850 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001851 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001852 }
1853}
1854
Victor Stinner702c7342011-10-05 13:50:52 +02001855static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001856_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001857{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001858 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001859 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001860
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001861 if (size == 0) {
1862 Py_INCREF(unicode_empty);
1863 return unicode_empty;
1864 }
1865 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001866 if (size == 1)
1867 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001868
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001869 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001870 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001871 if (!res)
1872 return NULL;
1873 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001874 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001875 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001876}
1877
Victor Stinnere57b1c02011-09-28 22:20:48 +02001878static PyObject*
1879_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001880{
1881 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001882 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001883
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001884 if (size == 0) {
1885 Py_INCREF(unicode_empty);
1886 return unicode_empty;
1887 }
1888 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001889 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001890 return get_latin1_char((unsigned char)u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001891
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001892 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001893 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001894 if (!res)
1895 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001896 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001897 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001898 else {
1899 _PyUnicode_CONVERT_BYTES(
1900 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1901 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001902 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001903 return res;
1904}
1905
Victor Stinnere57b1c02011-09-28 22:20:48 +02001906static PyObject*
1907_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001908{
1909 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001910 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001911
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001912 if (size == 0) {
1913 Py_INCREF(unicode_empty);
1914 return unicode_empty;
1915 }
1916 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001917 if (size == 1 && u[0] < 256)
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001918 return get_latin1_char((unsigned char)u[0]);
1919
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001920 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001921 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001922 if (!res)
1923 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001924 if (max_char < 256)
1925 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1926 PyUnicode_1BYTE_DATA(res));
1927 else if (max_char < 0x10000)
1928 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1929 PyUnicode_2BYTE_DATA(res));
1930 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001931 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001932 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001933 return res;
1934}
1935
1936PyObject*
1937PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1938{
Victor Stinnercfed46e2011-11-22 01:29:14 +01001939 if (size < 0) {
1940 PyErr_SetString(PyExc_ValueError, "size must be positive");
1941 return NULL;
1942 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06001943 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001944 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001945 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001946 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001947 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001948 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001949 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001950 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02001951 PyErr_SetString(PyExc_SystemError, "invalid kind");
1952 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001953 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001954}
1955
Victor Stinner25a4b292011-10-06 12:31:55 +02001956/* Ensure that a string uses the most efficient storage, if it is not the
1957 case: create a new string with of the right kind. Write NULL into *p_unicode
1958 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001959static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001960unicode_adjust_maxchar(PyObject **p_unicode)
1961{
1962 PyObject *unicode, *copy;
1963 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001964 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001965 unsigned int kind;
1966
1967 assert(p_unicode != NULL);
1968 unicode = *p_unicode;
1969 assert(PyUnicode_IS_READY(unicode));
1970 if (PyUnicode_IS_ASCII(unicode))
1971 return;
1972
1973 len = PyUnicode_GET_LENGTH(unicode);
1974 kind = PyUnicode_KIND(unicode);
1975 if (kind == PyUnicode_1BYTE_KIND) {
1976 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001977 max_char = ucs1lib_find_max_char(u, u + len);
1978 if (max_char >= 128)
1979 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001980 }
1981 else if (kind == PyUnicode_2BYTE_KIND) {
1982 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001983 max_char = ucs2lib_find_max_char(u, u + len);
1984 if (max_char >= 256)
1985 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001986 }
1987 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001988 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001989 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001990 max_char = ucs4lib_find_max_char(u, u + len);
1991 if (max_char >= 0x10000)
1992 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001993 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001994 copy = PyUnicode_New(len, max_char);
1995 copy_characters(copy, 0, unicode, 0, len);
1996 Py_DECREF(unicode);
1997 *p_unicode = copy;
1998}
1999
Victor Stinner034f6cf2011-09-30 02:26:44 +02002000PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002001_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002002{
Victor Stinner87af4f22011-11-21 23:03:47 +01002003 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002004 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002005
Victor Stinner034f6cf2011-09-30 02:26:44 +02002006 if (!PyUnicode_Check(unicode)) {
2007 PyErr_BadInternalCall();
2008 return NULL;
2009 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002010 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002011 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002012
Victor Stinner87af4f22011-11-21 23:03:47 +01002013 length = PyUnicode_GET_LENGTH(unicode);
2014 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002015 if (!copy)
2016 return NULL;
2017 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2018
Victor Stinner87af4f22011-11-21 23:03:47 +01002019 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2020 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002021 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002022 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002023}
2024
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002025
Victor Stinnerbc603d12011-10-02 01:00:40 +02002026/* Widen Unicode objects to larger buffers. Don't write terminating null
2027 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002028
2029void*
2030_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2031{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002032 Py_ssize_t len;
2033 void *result;
2034 unsigned int skind;
2035
Benjamin Petersonbac79492012-01-14 13:34:47 -05002036 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002037 return NULL;
2038
2039 len = PyUnicode_GET_LENGTH(s);
2040 skind = PyUnicode_KIND(s);
2041 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002042 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002043 return NULL;
2044 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002045 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002046 case PyUnicode_2BYTE_KIND:
2047 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2048 if (!result)
2049 return PyErr_NoMemory();
2050 assert(skind == PyUnicode_1BYTE_KIND);
2051 _PyUnicode_CONVERT_BYTES(
2052 Py_UCS1, Py_UCS2,
2053 PyUnicode_1BYTE_DATA(s),
2054 PyUnicode_1BYTE_DATA(s) + len,
2055 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002056 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002057 case PyUnicode_4BYTE_KIND:
2058 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2059 if (!result)
2060 return PyErr_NoMemory();
2061 if (skind == PyUnicode_2BYTE_KIND) {
2062 _PyUnicode_CONVERT_BYTES(
2063 Py_UCS2, Py_UCS4,
2064 PyUnicode_2BYTE_DATA(s),
2065 PyUnicode_2BYTE_DATA(s) + len,
2066 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002067 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002068 else {
2069 assert(skind == PyUnicode_1BYTE_KIND);
2070 _PyUnicode_CONVERT_BYTES(
2071 Py_UCS1, Py_UCS4,
2072 PyUnicode_1BYTE_DATA(s),
2073 PyUnicode_1BYTE_DATA(s) + len,
2074 result);
2075 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002076 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002077 default:
2078 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002079 }
Victor Stinner01698042011-10-04 00:04:26 +02002080 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002081 return NULL;
2082}
2083
2084static Py_UCS4*
2085as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2086 int copy_null)
2087{
2088 int kind;
2089 void *data;
2090 Py_ssize_t len, targetlen;
2091 if (PyUnicode_READY(string) == -1)
2092 return NULL;
2093 kind = PyUnicode_KIND(string);
2094 data = PyUnicode_DATA(string);
2095 len = PyUnicode_GET_LENGTH(string);
2096 targetlen = len;
2097 if (copy_null)
2098 targetlen++;
2099 if (!target) {
2100 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2101 PyErr_NoMemory();
2102 return NULL;
2103 }
2104 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2105 if (!target) {
2106 PyErr_NoMemory();
2107 return NULL;
2108 }
2109 }
2110 else {
2111 if (targetsize < targetlen) {
2112 PyErr_Format(PyExc_SystemError,
2113 "string is longer than the buffer");
2114 if (copy_null && 0 < targetsize)
2115 target[0] = 0;
2116 return NULL;
2117 }
2118 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002119 if (kind == PyUnicode_1BYTE_KIND) {
2120 Py_UCS1 *start = (Py_UCS1 *) data;
2121 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002122 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002123 else if (kind == PyUnicode_2BYTE_KIND) {
2124 Py_UCS2 *start = (Py_UCS2 *) data;
2125 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2126 }
2127 else {
2128 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002129 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002130 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002131 if (copy_null)
2132 target[len] = 0;
2133 return target;
2134}
2135
2136Py_UCS4*
2137PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2138 int copy_null)
2139{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002140 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002141 PyErr_BadInternalCall();
2142 return NULL;
2143 }
2144 return as_ucs4(string, target, targetsize, copy_null);
2145}
2146
2147Py_UCS4*
2148PyUnicode_AsUCS4Copy(PyObject *string)
2149{
2150 return as_ucs4(string, NULL, 0, 1);
2151}
2152
2153#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002154
Alexander Belopolsky40018472011-02-26 01:02:56 +00002155PyObject *
2156PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002157{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002158 if (w == NULL) {
Victor Stinner382955f2011-12-11 21:44:00 +01002159 if (size == 0) {
2160 Py_INCREF(unicode_empty);
2161 return unicode_empty;
2162 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002163 PyErr_BadInternalCall();
2164 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002165 }
2166
Martin v. Löwis790465f2008-04-05 20:41:37 +00002167 if (size == -1) {
2168 size = wcslen(w);
2169 }
2170
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002171 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002172}
2173
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002174#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002175
Walter Dörwald346737f2007-05-31 10:44:43 +00002176static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002177makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2178 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002179{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002180 *fmt++ = '%';
2181 if (width) {
2182 if (zeropad)
2183 *fmt++ = '0';
2184 fmt += sprintf(fmt, "%d", width);
2185 }
2186 if (precision)
2187 fmt += sprintf(fmt, ".%d", precision);
2188 if (longflag)
2189 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002190 else if (longlongflag) {
2191 /* longlongflag should only ever be nonzero on machines with
2192 HAVE_LONG_LONG defined */
2193#ifdef HAVE_LONG_LONG
2194 char *f = PY_FORMAT_LONG_LONG;
2195 while (*f)
2196 *fmt++ = *f++;
2197#else
2198 /* we shouldn't ever get here */
2199 assert(0);
2200 *fmt++ = 'l';
2201#endif
2202 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002203 else if (size_tflag) {
2204 char *f = PY_FORMAT_SIZE_T;
2205 while (*f)
2206 *fmt++ = *f++;
2207 }
2208 *fmt++ = c;
2209 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002210}
2211
Victor Stinner96865452011-03-01 23:44:09 +00002212/* helper for PyUnicode_FromFormatV() */
2213
2214static const char*
2215parse_format_flags(const char *f,
2216 int *p_width, int *p_precision,
2217 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2218{
2219 int width, precision, longflag, longlongflag, size_tflag;
2220
2221 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2222 f++;
2223 width = 0;
2224 while (Py_ISDIGIT((unsigned)*f))
2225 width = (width*10) + *f++ - '0';
2226 precision = 0;
2227 if (*f == '.') {
2228 f++;
2229 while (Py_ISDIGIT((unsigned)*f))
2230 precision = (precision*10) + *f++ - '0';
2231 if (*f == '%') {
2232 /* "%.3%s" => f points to "3" */
2233 f--;
2234 }
2235 }
2236 if (*f == '\0') {
2237 /* bogus format "%.1" => go backward, f points to "1" */
2238 f--;
2239 }
2240 if (p_width != NULL)
2241 *p_width = width;
2242 if (p_precision != NULL)
2243 *p_precision = precision;
2244
2245 /* Handle %ld, %lu, %lld and %llu. */
2246 longflag = 0;
2247 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002248 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002249
2250 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002251 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002252 longflag = 1;
2253 ++f;
2254 }
2255#ifdef HAVE_LONG_LONG
2256 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002257 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002258 longlongflag = 1;
2259 f += 2;
2260 }
2261#endif
2262 }
2263 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002264 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002265 size_tflag = 1;
2266 ++f;
2267 }
2268 if (p_longflag != NULL)
2269 *p_longflag = longflag;
2270 if (p_longlongflag != NULL)
2271 *p_longlongflag = longlongflag;
2272 if (p_size_tflag != NULL)
2273 *p_size_tflag = size_tflag;
2274 return f;
2275}
2276
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002277/* maximum number of characters required for output of %ld. 21 characters
2278 allows for 64-bit integers (in decimal) and an optional sign. */
2279#define MAX_LONG_CHARS 21
2280/* maximum number of characters required for output of %lld.
2281 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2282 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2283#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2284
Walter Dörwaldd2034312007-05-18 16:29:38 +00002285PyObject *
2286PyUnicode_FromFormatV(const char *format, va_list vargs)
2287{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002288 va_list count;
2289 Py_ssize_t callcount = 0;
2290 PyObject **callresults = NULL;
2291 PyObject **callresult = NULL;
2292 Py_ssize_t n = 0;
2293 int width = 0;
2294 int precision = 0;
2295 int zeropad;
2296 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002297 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002298 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002299 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002300 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2301 Py_UCS4 argmaxchar;
2302 Py_ssize_t numbersize = 0;
2303 char *numberresults = NULL;
2304 char *numberresult = NULL;
2305 Py_ssize_t i;
2306 int kind;
2307 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002308
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002309 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002310 /* step 1: count the number of %S/%R/%A/%s format specifications
2311 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2312 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002313 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002314 * also estimate a upper bound for all the number formats in the string,
2315 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002316 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002317 for (f = format; *f; f++) {
2318 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002319 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002320 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2321 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2322 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2323 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002324
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002325 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002326#ifdef HAVE_LONG_LONG
2327 if (longlongflag) {
2328 if (width < MAX_LONG_LONG_CHARS)
2329 width = MAX_LONG_LONG_CHARS;
2330 }
2331 else
2332#endif
2333 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2334 including sign. Decimal takes the most space. This
2335 isn't enough for octal. If a width is specified we
2336 need more (which we allocate later). */
2337 if (width < MAX_LONG_CHARS)
2338 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002339
2340 /* account for the size + '\0' to separate numbers
2341 inside of the numberresults buffer */
2342 numbersize += (width + 1);
2343 }
2344 }
2345 else if ((unsigned char)*f > 127) {
2346 PyErr_Format(PyExc_ValueError,
2347 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2348 "string, got a non-ASCII byte: 0x%02x",
2349 (unsigned char)*f);
2350 return NULL;
2351 }
2352 }
2353 /* step 2: allocate memory for the results of
2354 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2355 if (callcount) {
2356 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2357 if (!callresults) {
2358 PyErr_NoMemory();
2359 return NULL;
2360 }
2361 callresult = callresults;
2362 }
2363 /* step 2.5: allocate memory for the results of formating numbers */
2364 if (numbersize) {
2365 numberresults = PyObject_Malloc(numbersize);
2366 if (!numberresults) {
2367 PyErr_NoMemory();
2368 goto fail;
2369 }
2370 numberresult = numberresults;
2371 }
2372
2373 /* step 3: format numbers and figure out how large a buffer we need */
2374 for (f = format; *f; f++) {
2375 if (*f == '%') {
2376 const char* p;
2377 int longflag;
2378 int longlongflag;
2379 int size_tflag;
2380 int numprinted;
2381
2382 p = f;
2383 zeropad = (f[1] == '0');
2384 f = parse_format_flags(f, &width, &precision,
2385 &longflag, &longlongflag, &size_tflag);
2386 switch (*f) {
2387 case 'c':
2388 {
2389 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002390 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002391 n++;
2392 break;
2393 }
2394 case '%':
2395 n++;
2396 break;
2397 case 'i':
2398 case 'd':
2399 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2400 width, precision, *f);
2401 if (longflag)
2402 numprinted = sprintf(numberresult, fmt,
2403 va_arg(count, long));
2404#ifdef HAVE_LONG_LONG
2405 else if (longlongflag)
2406 numprinted = sprintf(numberresult, fmt,
2407 va_arg(count, PY_LONG_LONG));
2408#endif
2409 else if (size_tflag)
2410 numprinted = sprintf(numberresult, fmt,
2411 va_arg(count, Py_ssize_t));
2412 else
2413 numprinted = sprintf(numberresult, fmt,
2414 va_arg(count, int));
2415 n += numprinted;
2416 /* advance by +1 to skip over the '\0' */
2417 numberresult += (numprinted + 1);
2418 assert(*(numberresult - 1) == '\0');
2419 assert(*(numberresult - 2) != '\0');
2420 assert(numprinted >= 0);
2421 assert(numberresult <= numberresults + numbersize);
2422 break;
2423 case 'u':
2424 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2425 width, precision, 'u');
2426 if (longflag)
2427 numprinted = sprintf(numberresult, fmt,
2428 va_arg(count, unsigned long));
2429#ifdef HAVE_LONG_LONG
2430 else if (longlongflag)
2431 numprinted = sprintf(numberresult, fmt,
2432 va_arg(count, unsigned PY_LONG_LONG));
2433#endif
2434 else if (size_tflag)
2435 numprinted = sprintf(numberresult, fmt,
2436 va_arg(count, size_t));
2437 else
2438 numprinted = sprintf(numberresult, fmt,
2439 va_arg(count, unsigned int));
2440 n += numprinted;
2441 numberresult += (numprinted + 1);
2442 assert(*(numberresult - 1) == '\0');
2443 assert(*(numberresult - 2) != '\0');
2444 assert(numprinted >= 0);
2445 assert(numberresult <= numberresults + numbersize);
2446 break;
2447 case 'x':
2448 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2449 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2450 n += numprinted;
2451 numberresult += (numprinted + 1);
2452 assert(*(numberresult - 1) == '\0');
2453 assert(*(numberresult - 2) != '\0');
2454 assert(numprinted >= 0);
2455 assert(numberresult <= numberresults + numbersize);
2456 break;
2457 case 'p':
2458 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2459 /* %p is ill-defined: ensure leading 0x. */
2460 if (numberresult[1] == 'X')
2461 numberresult[1] = 'x';
2462 else if (numberresult[1] != 'x') {
2463 memmove(numberresult + 2, numberresult,
2464 strlen(numberresult) + 1);
2465 numberresult[0] = '0';
2466 numberresult[1] = 'x';
2467 numprinted += 2;
2468 }
2469 n += numprinted;
2470 numberresult += (numprinted + 1);
2471 assert(*(numberresult - 1) == '\0');
2472 assert(*(numberresult - 2) != '\0');
2473 assert(numprinted >= 0);
2474 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002475 break;
2476 case 's':
2477 {
2478 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002479 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002480 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002481 if (!str)
2482 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002483 /* since PyUnicode_DecodeUTF8 returns already flexible
2484 unicode objects, there is no need to call ready on them */
2485 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002486 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002488 /* Remember the str and switch to the next slot */
2489 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002490 break;
2491 }
2492 case 'U':
2493 {
2494 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002495 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002496 if (PyUnicode_READY(obj) == -1)
2497 goto fail;
2498 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002499 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002500 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002501 break;
2502 }
2503 case 'V':
2504 {
2505 PyObject *obj = va_arg(count, PyObject *);
2506 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002507 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002508 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002509 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002510 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002511 if (PyUnicode_READY(obj) == -1)
2512 goto fail;
2513 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002514 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002515 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002516 *callresult++ = NULL;
2517 }
2518 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002519 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002520 if (!str_obj)
2521 goto fail;
Benjamin Petersonbac79492012-01-14 13:34:47 -05002522 if (PyUnicode_READY(str_obj) == -1) {
Victor Stinnere1335c72011-10-04 20:53:03 +02002523 Py_DECREF(str_obj);
2524 goto fail;
2525 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002526 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002527 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002528 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002529 *callresult++ = str_obj;
2530 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002531 break;
2532 }
2533 case 'S':
2534 {
2535 PyObject *obj = va_arg(count, PyObject *);
2536 PyObject *str;
2537 assert(obj);
2538 str = PyObject_Str(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002539 if (!str)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002540 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002541 if (PyUnicode_READY(str) == -1) {
2542 Py_DECREF(str);
2543 goto fail;
2544 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002545 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002546 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002547 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002548 /* Remember the str and switch to the next slot */
2549 *callresult++ = str;
2550 break;
2551 }
2552 case 'R':
2553 {
2554 PyObject *obj = va_arg(count, PyObject *);
2555 PyObject *repr;
2556 assert(obj);
2557 repr = PyObject_Repr(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002558 if (!repr)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002559 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002560 if (PyUnicode_READY(repr) == -1) {
2561 Py_DECREF(repr);
2562 goto fail;
2563 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002564 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002565 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002566 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002567 /* Remember the repr and switch to the next slot */
2568 *callresult++ = repr;
2569 break;
2570 }
2571 case 'A':
2572 {
2573 PyObject *obj = va_arg(count, PyObject *);
2574 PyObject *ascii;
2575 assert(obj);
2576 ascii = PyObject_ASCII(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002577 if (!ascii)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002578 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002579 if (PyUnicode_READY(ascii) == -1) {
2580 Py_DECREF(ascii);
2581 goto fail;
2582 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002583 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002584 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002585 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002586 /* Remember the repr and switch to the next slot */
2587 *callresult++ = ascii;
2588 break;
2589 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002590 default:
2591 /* if we stumble upon an unknown
2592 formatting code, copy the rest of
2593 the format string to the output
2594 string. (we cannot just skip the
2595 code, since there's no way to know
2596 what's in the argument list) */
2597 n += strlen(p);
2598 goto expand;
2599 }
2600 } else
2601 n++;
2602 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002603 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002604 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002605 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002606 we don't have to resize the string.
2607 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002608 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002609 if (!string)
2610 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002611 kind = PyUnicode_KIND(string);
2612 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002613 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002614 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002615
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002616 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002617 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002618 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002619
2620 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002621 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2622 /* checking for == because the last argument could be a empty
2623 string, which causes i to point to end, the assert at the end of
2624 the loop */
2625 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002626
Benjamin Peterson14339b62009-01-31 16:36:08 +00002627 switch (*f) {
2628 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002629 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002630 const int ordinal = va_arg(vargs, int);
2631 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002632 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002633 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002634 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002635 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002636 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002637 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002638 case 'p':
Victor Stinnerc5166102012-02-22 13:55:02 +01002639 {
2640 Py_ssize_t written;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002641 /* unused, since we already have the result */
2642 if (*f == 'p')
2643 (void) va_arg(vargs, void *);
2644 else
2645 (void) va_arg(vargs, int);
2646 /* extract the result from numberresults and append. */
Victor Stinnerc5166102012-02-22 13:55:02 +01002647 written = unicode_write_cstr(string, i, numberresult);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002648 /* skip over the separating '\0' */
Victor Stinnerc5166102012-02-22 13:55:02 +01002649 i += written;
2650 numberresult += written;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002651 assert(*numberresult == '\0');
2652 numberresult++;
2653 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002654 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002655 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002656 case 's':
2657 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002658 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002659 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002660 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002661 size = PyUnicode_GET_LENGTH(*callresult);
2662 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002663 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002664 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002665 /* We're done with the unicode()/repr() => forget it */
2666 Py_DECREF(*callresult);
2667 /* switch to next unicode()/repr() result */
2668 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002669 break;
2670 }
2671 case 'U':
2672 {
2673 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002674 Py_ssize_t size;
2675 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2676 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002677 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002678 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002679 break;
2680 }
2681 case 'V':
2682 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002683 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002684 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002685 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002686 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002687 size = PyUnicode_GET_LENGTH(obj);
2688 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002689 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002690 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002691 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002692 size = PyUnicode_GET_LENGTH(*callresult);
2693 assert(PyUnicode_KIND(*callresult) <=
2694 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002695 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002696 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002697 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002698 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002699 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002700 break;
2701 }
2702 case 'S':
2703 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002704 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002705 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002706 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002707 /* unused, since we already have the result */
2708 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002709 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002710 copy_characters(string, i, *callresult, 0, size);
2711 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002712 /* We're done with the unicode()/repr() => forget it */
2713 Py_DECREF(*callresult);
2714 /* switch to next unicode()/repr() result */
2715 ++callresult;
2716 break;
2717 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002718 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002719 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002720 break;
2721 default:
Victor Stinnerc5166102012-02-22 13:55:02 +01002722 i += unicode_write_cstr(string, i, p);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002723 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002724 goto end;
2725 }
Victor Stinner1205f272010-09-11 00:54:47 +00002726 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002727 else {
2728 assert(i < PyUnicode_GET_LENGTH(string));
2729 PyUnicode_WRITE(kind, data, i++, *f);
2730 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002731 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002732 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002733
Benjamin Peterson29060642009-01-31 22:14:21 +00002734 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002735 if (callresults)
2736 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002737 if (numberresults)
2738 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002739 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002740 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002741 if (callresults) {
2742 PyObject **callresult2 = callresults;
2743 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002744 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002745 ++callresult2;
2746 }
2747 PyObject_Free(callresults);
2748 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002749 if (numberresults)
2750 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002751 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002752}
2753
Walter Dörwaldd2034312007-05-18 16:29:38 +00002754PyObject *
2755PyUnicode_FromFormat(const char *format, ...)
2756{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002757 PyObject* ret;
2758 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002759
2760#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002761 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002762#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002763 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002764#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002765 ret = PyUnicode_FromFormatV(format, vargs);
2766 va_end(vargs);
2767 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002768}
2769
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002770#ifdef HAVE_WCHAR_H
2771
Victor Stinner5593d8a2010-10-02 11:11:27 +00002772/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2773 convert a Unicode object to a wide character string.
2774
Victor Stinnerd88d9832011-09-06 02:00:05 +02002775 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002776 character) required to convert the unicode object. Ignore size argument.
2777
Victor Stinnerd88d9832011-09-06 02:00:05 +02002778 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002779 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002780 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002781static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002782unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002783 wchar_t *w,
2784 Py_ssize_t size)
2785{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002786 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002787 const wchar_t *wstr;
2788
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002789 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002790 if (wstr == NULL)
2791 return -1;
2792
Victor Stinner5593d8a2010-10-02 11:11:27 +00002793 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002794 if (size > res)
2795 size = res + 1;
2796 else
2797 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002798 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002799 return res;
2800 }
2801 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002802 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002803}
2804
2805Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002806PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002807 wchar_t *w,
2808 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002809{
2810 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002811 PyErr_BadInternalCall();
2812 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002813 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002814 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002815}
2816
Victor Stinner137c34c2010-09-29 10:25:54 +00002817wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002818PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002819 Py_ssize_t *size)
2820{
2821 wchar_t* buffer;
2822 Py_ssize_t buflen;
2823
2824 if (unicode == NULL) {
2825 PyErr_BadInternalCall();
2826 return NULL;
2827 }
2828
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002829 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002830 if (buflen == -1)
2831 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002832 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002833 PyErr_NoMemory();
2834 return NULL;
2835 }
2836
Victor Stinner137c34c2010-09-29 10:25:54 +00002837 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2838 if (buffer == NULL) {
2839 PyErr_NoMemory();
2840 return NULL;
2841 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002842 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002843 if (buflen == -1)
2844 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002845 if (size != NULL)
2846 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002847 return buffer;
2848}
2849
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002850#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002851
Alexander Belopolsky40018472011-02-26 01:02:56 +00002852PyObject *
2853PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002854{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002855 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002856 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002857 PyErr_SetString(PyExc_ValueError,
2858 "chr() arg not in range(0x110000)");
2859 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002860 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002861
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002862 if (ordinal < 256)
2863 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002864
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002865 v = PyUnicode_New(1, ordinal);
2866 if (v == NULL)
2867 return NULL;
2868 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002869 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002870 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002871}
2872
Alexander Belopolsky40018472011-02-26 01:02:56 +00002873PyObject *
2874PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002875{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002876 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002877 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002878 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002879 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002880 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002881 Py_INCREF(obj);
2882 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002883 }
2884 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002885 /* For a Unicode subtype that's not a Unicode object,
2886 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002887 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002888 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002889 PyErr_Format(PyExc_TypeError,
2890 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002891 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002892 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002893}
2894
Alexander Belopolsky40018472011-02-26 01:02:56 +00002895PyObject *
2896PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002897 const char *encoding,
2898 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002899{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002900 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002901 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002902
Guido van Rossumd57fd912000-03-10 22:53:23 +00002903 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002904 PyErr_BadInternalCall();
2905 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002906 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002907
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002908 /* Decoding bytes objects is the most common case and should be fast */
2909 if (PyBytes_Check(obj)) {
2910 if (PyBytes_GET_SIZE(obj) == 0) {
2911 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002912 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002913 }
2914 else {
2915 v = PyUnicode_Decode(
2916 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2917 encoding, errors);
2918 }
2919 return v;
2920 }
2921
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002922 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002923 PyErr_SetString(PyExc_TypeError,
2924 "decoding str is not supported");
2925 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002926 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002927
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002928 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2929 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2930 PyErr_Format(PyExc_TypeError,
2931 "coercing to str: need bytes, bytearray "
2932 "or buffer-like object, %.80s found",
2933 Py_TYPE(obj)->tp_name);
2934 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002935 }
Tim Petersced69f82003-09-16 20:30:58 +00002936
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002937 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002938 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002939 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002940 }
Tim Petersced69f82003-09-16 20:30:58 +00002941 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002942 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002943
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002944 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002945 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002946}
2947
Victor Stinner600d3be2010-06-10 12:00:55 +00002948/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002949 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2950 1 on success. */
2951static int
2952normalize_encoding(const char *encoding,
2953 char *lower,
2954 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002955{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002956 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002957 char *l;
2958 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002959
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002960 if (encoding == NULL) {
2961 strcpy(lower, "utf-8");
2962 return 1;
2963 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002964 e = encoding;
2965 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002966 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002967 while (*e) {
2968 if (l == l_end)
2969 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002970 if (Py_ISUPPER(*e)) {
2971 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002972 }
2973 else if (*e == '_') {
2974 *l++ = '-';
2975 e++;
2976 }
2977 else {
2978 *l++ = *e++;
2979 }
2980 }
2981 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002982 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002983}
2984
Alexander Belopolsky40018472011-02-26 01:02:56 +00002985PyObject *
2986PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002987 Py_ssize_t size,
2988 const char *encoding,
2989 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002990{
2991 PyObject *buffer = NULL, *unicode;
2992 Py_buffer info;
2993 char lower[11]; /* Enough for any encoding shortcut */
2994
Fred Drakee4315f52000-05-09 19:53:39 +00002995 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002996 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002997 if ((strcmp(lower, "utf-8") == 0) ||
2998 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002999 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003000 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003001 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003002 (strcmp(lower, "iso-8859-1") == 0))
3003 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003004#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003005 else if (strcmp(lower, "mbcs") == 0)
3006 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003007#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003008 else if (strcmp(lower, "ascii") == 0)
3009 return PyUnicode_DecodeASCII(s, size, errors);
3010 else if (strcmp(lower, "utf-16") == 0)
3011 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3012 else if (strcmp(lower, "utf-32") == 0)
3013 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3014 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003015
3016 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003017 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003018 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003019 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003020 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003021 if (buffer == NULL)
3022 goto onError;
3023 unicode = PyCodec_Decode(buffer, encoding, errors);
3024 if (unicode == NULL)
3025 goto onError;
3026 if (!PyUnicode_Check(unicode)) {
3027 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003028 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003029 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003030 Py_DECREF(unicode);
3031 goto onError;
3032 }
3033 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003034 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003035
Benjamin Peterson29060642009-01-31 22:14:21 +00003036 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003037 Py_XDECREF(buffer);
3038 return NULL;
3039}
3040
Alexander Belopolsky40018472011-02-26 01:02:56 +00003041PyObject *
3042PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003043 const char *encoding,
3044 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003045{
3046 PyObject *v;
3047
3048 if (!PyUnicode_Check(unicode)) {
3049 PyErr_BadArgument();
3050 goto onError;
3051 }
3052
3053 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003054 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003055
3056 /* Decode via the codec registry */
3057 v = PyCodec_Decode(unicode, encoding, errors);
3058 if (v == NULL)
3059 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003060 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003061
Benjamin Peterson29060642009-01-31 22:14:21 +00003062 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003063 return NULL;
3064}
3065
Alexander Belopolsky40018472011-02-26 01:02:56 +00003066PyObject *
3067PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003068 const char *encoding,
3069 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003070{
3071 PyObject *v;
3072
3073 if (!PyUnicode_Check(unicode)) {
3074 PyErr_BadArgument();
3075 goto onError;
3076 }
3077
3078 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003079 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003080
3081 /* Decode via the codec registry */
3082 v = PyCodec_Decode(unicode, encoding, errors);
3083 if (v == NULL)
3084 goto onError;
3085 if (!PyUnicode_Check(v)) {
3086 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003087 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003088 Py_TYPE(v)->tp_name);
3089 Py_DECREF(v);
3090 goto onError;
3091 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003092 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003093
Benjamin Peterson29060642009-01-31 22:14:21 +00003094 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003095 return NULL;
3096}
3097
Alexander Belopolsky40018472011-02-26 01:02:56 +00003098PyObject *
3099PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003100 Py_ssize_t size,
3101 const char *encoding,
3102 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003103{
3104 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003105
Guido van Rossumd57fd912000-03-10 22:53:23 +00003106 unicode = PyUnicode_FromUnicode(s, size);
3107 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003108 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003109 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3110 Py_DECREF(unicode);
3111 return v;
3112}
3113
Alexander Belopolsky40018472011-02-26 01:02:56 +00003114PyObject *
3115PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003116 const char *encoding,
3117 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003118{
3119 PyObject *v;
3120
3121 if (!PyUnicode_Check(unicode)) {
3122 PyErr_BadArgument();
3123 goto onError;
3124 }
3125
3126 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003127 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003128
3129 /* Encode via the codec registry */
3130 v = PyCodec_Encode(unicode, encoding, errors);
3131 if (v == NULL)
3132 goto onError;
3133 return v;
3134
Benjamin Peterson29060642009-01-31 22:14:21 +00003135 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003136 return NULL;
3137}
3138
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003139static size_t
3140wcstombs_errorpos(const wchar_t *wstr)
3141{
3142 size_t len;
3143#if SIZEOF_WCHAR_T == 2
3144 wchar_t buf[3];
3145#else
3146 wchar_t buf[2];
3147#endif
3148 char outbuf[MB_LEN_MAX];
3149 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003150
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003151#if SIZEOF_WCHAR_T == 2
3152 buf[2] = 0;
3153#else
3154 buf[1] = 0;
3155#endif
3156 start = wstr;
3157 while (*wstr != L'\0')
3158 {
3159 previous = wstr;
3160#if SIZEOF_WCHAR_T == 2
3161 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3162 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3163 {
3164 buf[0] = wstr[0];
3165 buf[1] = wstr[1];
3166 wstr += 2;
3167 }
3168 else {
3169 buf[0] = *wstr;
3170 buf[1] = 0;
3171 wstr++;
3172 }
3173#else
3174 buf[0] = *wstr;
3175 wstr++;
3176#endif
3177 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003178 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003179 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003180 }
3181
3182 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003183 return 0;
3184}
3185
Victor Stinner1b579672011-12-17 05:47:23 +01003186static int
3187locale_error_handler(const char *errors, int *surrogateescape)
3188{
3189 if (errors == NULL) {
3190 *surrogateescape = 0;
3191 return 0;
3192 }
3193
3194 if (strcmp(errors, "strict") == 0) {
3195 *surrogateescape = 0;
3196 return 0;
3197 }
3198 if (strcmp(errors, "surrogateescape") == 0) {
3199 *surrogateescape = 1;
3200 return 0;
3201 }
3202 PyErr_Format(PyExc_ValueError,
3203 "only 'strict' and 'surrogateescape' error handlers "
3204 "are supported, not '%s'",
3205 errors);
3206 return -1;
3207}
3208
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003209PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003210PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003211{
3212 Py_ssize_t wlen, wlen2;
3213 wchar_t *wstr;
3214 PyObject *bytes = NULL;
3215 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003216 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003217 PyObject *exc;
3218 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003219 int surrogateescape;
3220
3221 if (locale_error_handler(errors, &surrogateescape) < 0)
3222 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003223
3224 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3225 if (wstr == NULL)
3226 return NULL;
3227
3228 wlen2 = wcslen(wstr);
3229 if (wlen2 != wlen) {
3230 PyMem_Free(wstr);
3231 PyErr_SetString(PyExc_TypeError, "embedded null character");
3232 return NULL;
3233 }
3234
3235 if (surrogateescape) {
3236 /* locale encoding with surrogateescape */
3237 char *str;
3238
3239 str = _Py_wchar2char(wstr, &error_pos);
3240 if (str == NULL) {
3241 if (error_pos == (size_t)-1) {
3242 PyErr_NoMemory();
3243 PyMem_Free(wstr);
3244 return NULL;
3245 }
3246 else {
3247 goto encode_error;
3248 }
3249 }
3250 PyMem_Free(wstr);
3251
3252 bytes = PyBytes_FromString(str);
3253 PyMem_Free(str);
3254 }
3255 else {
3256 size_t len, len2;
3257
3258 len = wcstombs(NULL, wstr, 0);
3259 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003260 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003261 goto encode_error;
3262 }
3263
3264 bytes = PyBytes_FromStringAndSize(NULL, len);
3265 if (bytes == NULL) {
3266 PyMem_Free(wstr);
3267 return NULL;
3268 }
3269
3270 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3271 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003272 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003273 goto encode_error;
3274 }
3275 PyMem_Free(wstr);
3276 }
3277 return bytes;
3278
3279encode_error:
3280 errmsg = strerror(errno);
3281 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003282
3283 if (error_pos == (size_t)-1)
3284 error_pos = wcstombs_errorpos(wstr);
3285
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003286 PyMem_Free(wstr);
3287 Py_XDECREF(bytes);
3288
Victor Stinner2f197072011-12-17 07:08:30 +01003289 if (errmsg != NULL) {
3290 size_t errlen;
3291 wstr = _Py_char2wchar(errmsg, &errlen);
3292 if (wstr != NULL) {
3293 reason = PyUnicode_FromWideChar(wstr, errlen);
3294 PyMem_Free(wstr);
3295 } else
3296 errmsg = NULL;
3297 }
3298 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003299 reason = PyUnicode_FromString(
3300 "wcstombs() encountered an unencodable "
3301 "wide character");
3302 if (reason == NULL)
3303 return NULL;
3304
3305 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3306 "locale", unicode,
3307 (Py_ssize_t)error_pos,
3308 (Py_ssize_t)(error_pos+1),
3309 reason);
3310 Py_DECREF(reason);
3311 if (exc != NULL) {
3312 PyCodec_StrictErrors(exc);
3313 Py_XDECREF(exc);
3314 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003315 return NULL;
3316}
3317
Victor Stinnerad158722010-10-27 00:25:46 +00003318PyObject *
3319PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003320{
Victor Stinner99b95382011-07-04 14:23:54 +02003321#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003322 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003323#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003324 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003325#else
Victor Stinner793b5312011-04-27 00:24:21 +02003326 PyInterpreterState *interp = PyThreadState_GET()->interp;
3327 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3328 cannot use it to encode and decode filenames before it is loaded. Load
3329 the Python codec requires to encode at least its own filename. Use the C
3330 version of the locale codec until the codec registry is initialized and
3331 the Python codec is loaded.
3332
3333 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3334 cannot only rely on it: check also interp->fscodec_initialized for
3335 subinterpreters. */
3336 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003337 return PyUnicode_AsEncodedString(unicode,
3338 Py_FileSystemDefaultEncoding,
3339 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003340 }
3341 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003342 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003343 }
Victor Stinnerad158722010-10-27 00:25:46 +00003344#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003345}
3346
Alexander Belopolsky40018472011-02-26 01:02:56 +00003347PyObject *
3348PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003349 const char *encoding,
3350 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003351{
3352 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003353 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003354
Guido van Rossumd57fd912000-03-10 22:53:23 +00003355 if (!PyUnicode_Check(unicode)) {
3356 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003357 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003358 }
Fred Drakee4315f52000-05-09 19:53:39 +00003359
Fred Drakee4315f52000-05-09 19:53:39 +00003360 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003361 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003362 if ((strcmp(lower, "utf-8") == 0) ||
3363 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003364 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003365 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003366 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003367 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003368 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003369 }
Victor Stinner37296e82010-06-10 13:36:23 +00003370 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003371 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003372 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003373 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003374#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003375 else if (strcmp(lower, "mbcs") == 0)
3376 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003377#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003378 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003379 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003380 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003381
3382 /* Encode via the codec registry */
3383 v = PyCodec_Encode(unicode, encoding, errors);
3384 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003385 return NULL;
3386
3387 /* The normal path */
3388 if (PyBytes_Check(v))
3389 return v;
3390
3391 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003392 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003393 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003394 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003395
3396 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3397 "encoder %s returned bytearray instead of bytes",
3398 encoding);
3399 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003400 Py_DECREF(v);
3401 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003402 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003403
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003404 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3405 Py_DECREF(v);
3406 return b;
3407 }
3408
3409 PyErr_Format(PyExc_TypeError,
3410 "encoder did not return a bytes object (type=%.400s)",
3411 Py_TYPE(v)->tp_name);
3412 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003413 return NULL;
3414}
3415
Alexander Belopolsky40018472011-02-26 01:02:56 +00003416PyObject *
3417PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003418 const char *encoding,
3419 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003420{
3421 PyObject *v;
3422
3423 if (!PyUnicode_Check(unicode)) {
3424 PyErr_BadArgument();
3425 goto onError;
3426 }
3427
3428 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003429 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003430
3431 /* Encode via the codec registry */
3432 v = PyCodec_Encode(unicode, encoding, errors);
3433 if (v == NULL)
3434 goto onError;
3435 if (!PyUnicode_Check(v)) {
3436 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003437 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003438 Py_TYPE(v)->tp_name);
3439 Py_DECREF(v);
3440 goto onError;
3441 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003442 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003443
Benjamin Peterson29060642009-01-31 22:14:21 +00003444 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003445 return NULL;
3446}
3447
Victor Stinner2f197072011-12-17 07:08:30 +01003448static size_t
3449mbstowcs_errorpos(const char *str, size_t len)
3450{
3451#ifdef HAVE_MBRTOWC
3452 const char *start = str;
3453 mbstate_t mbs;
3454 size_t converted;
3455 wchar_t ch;
3456
3457 memset(&mbs, 0, sizeof mbs);
3458 while (len)
3459 {
3460 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3461 if (converted == 0)
3462 /* Reached end of string */
3463 break;
3464 if (converted == (size_t)-1 || converted == (size_t)-2) {
3465 /* Conversion error or incomplete character */
3466 return str - start;
3467 }
3468 else {
3469 str += converted;
3470 len -= converted;
3471 }
3472 }
3473 /* failed to find the undecodable byte sequence */
3474 return 0;
3475#endif
3476 return 0;
3477}
3478
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003479PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003480PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003481 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003482{
3483 wchar_t smallbuf[256];
3484 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3485 wchar_t *wstr;
3486 size_t wlen, wlen2;
3487 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003488 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003489 size_t error_pos;
3490 char *errmsg;
3491 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003492
3493 if (locale_error_handler(errors, &surrogateescape) < 0)
3494 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003495
3496 if (str[len] != '\0' || len != strlen(str)) {
3497 PyErr_SetString(PyExc_TypeError, "embedded null character");
3498 return NULL;
3499 }
3500
3501 if (surrogateescape)
3502 {
3503 wstr = _Py_char2wchar(str, &wlen);
3504 if (wstr == NULL) {
3505 if (wlen == (size_t)-1)
3506 PyErr_NoMemory();
3507 else
3508 PyErr_SetFromErrno(PyExc_OSError);
3509 return NULL;
3510 }
3511
3512 unicode = PyUnicode_FromWideChar(wstr, wlen);
3513 PyMem_Free(wstr);
3514 }
3515 else {
3516#ifndef HAVE_BROKEN_MBSTOWCS
3517 wlen = mbstowcs(NULL, str, 0);
3518#else
3519 wlen = len;
3520#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003521 if (wlen == (size_t)-1)
3522 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003523 if (wlen+1 <= smallbuf_len) {
3524 wstr = smallbuf;
3525 }
3526 else {
3527 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3528 return PyErr_NoMemory();
3529
3530 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3531 if (!wstr)
3532 return PyErr_NoMemory();
3533 }
3534
3535 /* This shouldn't fail now */
3536 wlen2 = mbstowcs(wstr, str, wlen+1);
3537 if (wlen2 == (size_t)-1) {
3538 if (wstr != smallbuf)
3539 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003540 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003541 }
3542#ifdef HAVE_BROKEN_MBSTOWCS
3543 assert(wlen2 == wlen);
3544#endif
3545 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3546 if (wstr != smallbuf)
3547 PyMem_Free(wstr);
3548 }
3549 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003550
3551decode_error:
3552 errmsg = strerror(errno);
3553 assert(errmsg != NULL);
3554
3555 error_pos = mbstowcs_errorpos(str, len);
3556 if (errmsg != NULL) {
3557 size_t errlen;
3558 wstr = _Py_char2wchar(errmsg, &errlen);
3559 if (wstr != NULL) {
3560 reason = PyUnicode_FromWideChar(wstr, errlen);
3561 PyMem_Free(wstr);
3562 } else
3563 errmsg = NULL;
3564 }
3565 if (errmsg == NULL)
3566 reason = PyUnicode_FromString(
3567 "mbstowcs() encountered an invalid multibyte sequence");
3568 if (reason == NULL)
3569 return NULL;
3570
3571 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3572 "locale", str, len,
3573 (Py_ssize_t)error_pos,
3574 (Py_ssize_t)(error_pos+1),
3575 reason);
3576 Py_DECREF(reason);
3577 if (exc != NULL) {
3578 PyCodec_StrictErrors(exc);
3579 Py_XDECREF(exc);
3580 }
3581 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003582}
3583
3584PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003585PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003586{
3587 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003588 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003589}
3590
3591
3592PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003593PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003594 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003595 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3596}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003597
Christian Heimes5894ba72007-11-04 11:43:14 +00003598PyObject*
3599PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3600{
Victor Stinner99b95382011-07-04 14:23:54 +02003601#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003602 return PyUnicode_DecodeMBCS(s, size, NULL);
3603#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003604 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003605#else
Victor Stinner793b5312011-04-27 00:24:21 +02003606 PyInterpreterState *interp = PyThreadState_GET()->interp;
3607 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3608 cannot use it to encode and decode filenames before it is loaded. Load
3609 the Python codec requires to encode at least its own filename. Use the C
3610 version of the locale codec until the codec registry is initialized and
3611 the Python codec is loaded.
3612
3613 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3614 cannot only rely on it: check also interp->fscodec_initialized for
3615 subinterpreters. */
3616 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003617 return PyUnicode_Decode(s, size,
3618 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003619 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003620 }
3621 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003622 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003623 }
Victor Stinnerad158722010-10-27 00:25:46 +00003624#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003625}
3626
Martin v. Löwis011e8422009-05-05 04:43:17 +00003627
3628int
Antoine Pitrou13348842012-01-29 18:36:34 +01003629_PyUnicode_HasNULChars(PyObject* s)
3630{
3631 static PyObject *nul = NULL;
3632
3633 if (nul == NULL)
3634 nul = PyUnicode_FromStringAndSize("\0", 1);
3635 if (nul == NULL)
3636 return -1;
3637 return PyUnicode_Contains(s, nul);
3638}
3639
3640
3641int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003642PyUnicode_FSConverter(PyObject* arg, void* addr)
3643{
3644 PyObject *output = NULL;
3645 Py_ssize_t size;
3646 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003647 if (arg == NULL) {
3648 Py_DECREF(*(PyObject**)addr);
3649 return 1;
3650 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003651 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003652 output = arg;
3653 Py_INCREF(output);
3654 }
3655 else {
3656 arg = PyUnicode_FromObject(arg);
3657 if (!arg)
3658 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003659 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003660 Py_DECREF(arg);
3661 if (!output)
3662 return 0;
3663 if (!PyBytes_Check(output)) {
3664 Py_DECREF(output);
3665 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3666 return 0;
3667 }
3668 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003669 size = PyBytes_GET_SIZE(output);
3670 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003671 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003672 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003673 Py_DECREF(output);
3674 return 0;
3675 }
3676 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003677 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003678}
3679
3680
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003681int
3682PyUnicode_FSDecoder(PyObject* arg, void* addr)
3683{
3684 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003685 if (arg == NULL) {
3686 Py_DECREF(*(PyObject**)addr);
3687 return 1;
3688 }
3689 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003690 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003691 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003692 output = arg;
3693 Py_INCREF(output);
3694 }
3695 else {
3696 arg = PyBytes_FromObject(arg);
3697 if (!arg)
3698 return 0;
3699 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3700 PyBytes_GET_SIZE(arg));
3701 Py_DECREF(arg);
3702 if (!output)
3703 return 0;
3704 if (!PyUnicode_Check(output)) {
3705 Py_DECREF(output);
3706 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3707 return 0;
3708 }
3709 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003710 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003711 Py_DECREF(output);
3712 return 0;
3713 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003714 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003715 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003716 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3717 Py_DECREF(output);
3718 return 0;
3719 }
3720 *(PyObject**)addr = output;
3721 return Py_CLEANUP_SUPPORTED;
3722}
3723
3724
Martin v. Löwis5b222132007-06-10 09:51:05 +00003725char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003726PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003727{
Christian Heimesf3863112007-11-22 07:46:41 +00003728 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003729
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003730 if (!PyUnicode_Check(unicode)) {
3731 PyErr_BadArgument();
3732 return NULL;
3733 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003734 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003735 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003736
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003737 if (PyUnicode_UTF8(unicode) == NULL) {
3738 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003739 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3740 if (bytes == NULL)
3741 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003742 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3743 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003744 Py_DECREF(bytes);
3745 return NULL;
3746 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003747 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3748 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3749 PyBytes_AS_STRING(bytes),
3750 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003751 Py_DECREF(bytes);
3752 }
3753
3754 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003755 *psize = PyUnicode_UTF8_LENGTH(unicode);
3756 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003757}
3758
3759char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003760PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003761{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003762 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3763}
3764
3765#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003766static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003767#endif
3768
3769
3770Py_UNICODE *
3771PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3772{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003773 const unsigned char *one_byte;
3774#if SIZEOF_WCHAR_T == 4
3775 const Py_UCS2 *two_bytes;
3776#else
3777 const Py_UCS4 *four_bytes;
3778 const Py_UCS4 *ucs4_end;
3779 Py_ssize_t num_surrogates;
3780#endif
3781 wchar_t *w;
3782 wchar_t *wchar_end;
3783
3784 if (!PyUnicode_Check(unicode)) {
3785 PyErr_BadArgument();
3786 return NULL;
3787 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003788 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003789 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003790 assert(_PyUnicode_KIND(unicode) != 0);
3791 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003792
3793#ifdef Py_DEBUG
3794 ++unicode_as_unicode_calls;
3795#endif
3796
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003797 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003798#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003799 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3800 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003801 num_surrogates = 0;
3802
3803 for (; four_bytes < ucs4_end; ++four_bytes) {
3804 if (*four_bytes > 0xFFFF)
3805 ++num_surrogates;
3806 }
3807
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003808 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3809 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3810 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003811 PyErr_NoMemory();
3812 return NULL;
3813 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003814 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003815
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003816 w = _PyUnicode_WSTR(unicode);
3817 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3818 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003819 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3820 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003821 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003822 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003823 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3824 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003825 }
3826 else
3827 *w = *four_bytes;
3828
3829 if (w > wchar_end) {
3830 assert(0 && "Miscalculated string end");
3831 }
3832 }
3833 *w = 0;
3834#else
3835 /* sizeof(wchar_t) == 4 */
3836 Py_FatalError("Impossible unicode object state, wstr and str "
3837 "should share memory already.");
3838 return NULL;
3839#endif
3840 }
3841 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003842 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3843 (_PyUnicode_LENGTH(unicode) + 1));
3844 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003845 PyErr_NoMemory();
3846 return NULL;
3847 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003848 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3849 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3850 w = _PyUnicode_WSTR(unicode);
3851 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003852
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003853 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3854 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003855 for (; w < wchar_end; ++one_byte, ++w)
3856 *w = *one_byte;
3857 /* null-terminate the wstr */
3858 *w = 0;
3859 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003860 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003861#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003862 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003863 for (; w < wchar_end; ++two_bytes, ++w)
3864 *w = *two_bytes;
3865 /* null-terminate the wstr */
3866 *w = 0;
3867#else
3868 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003869 PyObject_FREE(_PyUnicode_WSTR(unicode));
3870 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003871 Py_FatalError("Impossible unicode object state, wstr "
3872 "and str should share memory already.");
3873 return NULL;
3874#endif
3875 }
3876 else {
3877 assert(0 && "This should never happen.");
3878 }
3879 }
3880 }
3881 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003882 *size = PyUnicode_WSTR_LENGTH(unicode);
3883 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003884}
3885
Alexander Belopolsky40018472011-02-26 01:02:56 +00003886Py_UNICODE *
3887PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003888{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003889 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003890}
3891
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003892
Alexander Belopolsky40018472011-02-26 01:02:56 +00003893Py_ssize_t
3894PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003895{
3896 if (!PyUnicode_Check(unicode)) {
3897 PyErr_BadArgument();
3898 goto onError;
3899 }
3900 return PyUnicode_GET_SIZE(unicode);
3901
Benjamin Peterson29060642009-01-31 22:14:21 +00003902 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003903 return -1;
3904}
3905
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003906Py_ssize_t
3907PyUnicode_GetLength(PyObject *unicode)
3908{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003909 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003910 PyErr_BadArgument();
3911 return -1;
3912 }
3913
3914 return PyUnicode_GET_LENGTH(unicode);
3915}
3916
3917Py_UCS4
3918PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3919{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003920 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3921 PyErr_BadArgument();
3922 return (Py_UCS4)-1;
3923 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003924 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003925 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003926 return (Py_UCS4)-1;
3927 }
3928 return PyUnicode_READ_CHAR(unicode, index);
3929}
3930
3931int
3932PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3933{
3934 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003935 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003936 return -1;
3937 }
Victor Stinner488fa492011-12-12 00:01:39 +01003938 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003939 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003940 PyErr_SetString(PyExc_IndexError, "string index out of range");
3941 return -1;
3942 }
Victor Stinner488fa492011-12-12 00:01:39 +01003943 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003944 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003945 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3946 index, ch);
3947 return 0;
3948}
3949
Alexander Belopolsky40018472011-02-26 01:02:56 +00003950const char *
3951PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003952{
Victor Stinner42cb4622010-09-01 19:39:01 +00003953 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003954}
3955
Victor Stinner554f3f02010-06-16 23:33:54 +00003956/* create or adjust a UnicodeDecodeError */
3957static void
3958make_decode_exception(PyObject **exceptionObject,
3959 const char *encoding,
3960 const char *input, Py_ssize_t length,
3961 Py_ssize_t startpos, Py_ssize_t endpos,
3962 const char *reason)
3963{
3964 if (*exceptionObject == NULL) {
3965 *exceptionObject = PyUnicodeDecodeError_Create(
3966 encoding, input, length, startpos, endpos, reason);
3967 }
3968 else {
3969 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3970 goto onError;
3971 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3972 goto onError;
3973 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3974 goto onError;
3975 }
3976 return;
3977
3978onError:
3979 Py_DECREF(*exceptionObject);
3980 *exceptionObject = NULL;
3981}
3982
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003983/* error handling callback helper:
3984 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003985 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003986 and adjust various state variables.
3987 return 0 on success, -1 on error
3988*/
3989
Alexander Belopolsky40018472011-02-26 01:02:56 +00003990static int
3991unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003992 const char *encoding, const char *reason,
3993 const char **input, const char **inend, Py_ssize_t *startinpos,
3994 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003995 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003996{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003997 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003998
3999 PyObject *restuple = NULL;
4000 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004001 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004002 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004003 Py_ssize_t requiredsize;
4004 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004005 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004006 int res = -1;
4007
Victor Stinner596a6c42011-11-09 00:02:18 +01004008 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4009 outsize = PyUnicode_GET_LENGTH(*output);
4010 else
4011 outsize = _PyUnicode_WSTR_LENGTH(*output);
4012
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004013 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004014 *errorHandler = PyCodec_LookupError(errors);
4015 if (*errorHandler == NULL)
4016 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004017 }
4018
Victor Stinner554f3f02010-06-16 23:33:54 +00004019 make_decode_exception(exceptionObject,
4020 encoding,
4021 *input, *inend - *input,
4022 *startinpos, *endinpos,
4023 reason);
4024 if (*exceptionObject == NULL)
4025 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004026
4027 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4028 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004029 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004030 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004031 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004032 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004033 }
4034 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004035 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004036 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004037 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004038
4039 /* Copy back the bytes variables, which might have been modified by the
4040 callback */
4041 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4042 if (!inputobj)
4043 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004044 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004045 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004046 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004047 *input = PyBytes_AS_STRING(inputobj);
4048 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004049 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004050 /* we can DECREF safely, as the exception has another reference,
4051 so the object won't go away. */
4052 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004053
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004054 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004055 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004056 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004057 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4058 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004059 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004060
Victor Stinner596a6c42011-11-09 00:02:18 +01004061 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4062 /* need more space? (at least enough for what we
4063 have+the replacement+the rest of the string (starting
4064 at the new input position), so we won't have to check space
4065 when there are no errors in the rest of the string) */
4066 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4067 requiredsize = *outpos + replen + insize-newpos;
4068 if (requiredsize > outsize) {
4069 if (requiredsize<2*outsize)
4070 requiredsize = 2*outsize;
4071 if (unicode_resize(output, requiredsize) < 0)
4072 goto onError;
4073 }
4074 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004075 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01004076 copy_characters(*output, *outpos, repunicode, 0, replen);
4077 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004078 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004079 else {
4080 wchar_t *repwstr;
4081 Py_ssize_t repwlen;
4082 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4083 if (repwstr == NULL)
4084 goto onError;
4085 /* need more space? (at least enough for what we
4086 have+the replacement+the rest of the string (starting
4087 at the new input position), so we won't have to check space
4088 when there are no errors in the rest of the string) */
4089 requiredsize = *outpos + repwlen + insize-newpos;
4090 if (requiredsize > outsize) {
4091 if (requiredsize < 2*outsize)
4092 requiredsize = 2*outsize;
4093 if (unicode_resize(output, requiredsize) < 0)
4094 goto onError;
4095 }
4096 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4097 *outpos += repwlen;
4098 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004099 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004100 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004101
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004102 /* we made it! */
4103 res = 0;
4104
Benjamin Peterson29060642009-01-31 22:14:21 +00004105 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004106 Py_XDECREF(restuple);
4107 return res;
4108}
4109
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004110/* --- UTF-7 Codec -------------------------------------------------------- */
4111
Antoine Pitrou244651a2009-05-04 18:56:13 +00004112/* See RFC2152 for details. We encode conservatively and decode liberally. */
4113
4114/* Three simple macros defining base-64. */
4115
4116/* Is c a base-64 character? */
4117
4118#define IS_BASE64(c) \
4119 (((c) >= 'A' && (c) <= 'Z') || \
4120 ((c) >= 'a' && (c) <= 'z') || \
4121 ((c) >= '0' && (c) <= '9') || \
4122 (c) == '+' || (c) == '/')
4123
4124/* given that c is a base-64 character, what is its base-64 value? */
4125
4126#define FROM_BASE64(c) \
4127 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4128 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4129 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4130 (c) == '+' ? 62 : 63)
4131
4132/* What is the base-64 character of the bottom 6 bits of n? */
4133
4134#define TO_BASE64(n) \
4135 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4136
4137/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4138 * decoded as itself. We are permissive on decoding; the only ASCII
4139 * byte not decoding to itself is the + which begins a base64
4140 * string. */
4141
4142#define DECODE_DIRECT(c) \
4143 ((c) <= 127 && (c) != '+')
4144
4145/* The UTF-7 encoder treats ASCII characters differently according to
4146 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4147 * the above). See RFC2152. This array identifies these different
4148 * sets:
4149 * 0 : "Set D"
4150 * alphanumeric and '(),-./:?
4151 * 1 : "Set O"
4152 * !"#$%&*;<=>@[]^_`{|}
4153 * 2 : "whitespace"
4154 * ht nl cr sp
4155 * 3 : special (must be base64 encoded)
4156 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4157 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004158
Tim Petersced69f82003-09-16 20:30:58 +00004159static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004160char utf7_category[128] = {
4161/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4162 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4163/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4164 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4165/* sp ! " # $ % & ' ( ) * + , - . / */
4166 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4167/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4168 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4169/* @ A B C D E F G H I J K L M N O */
4170 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4171/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4172 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4173/* ` a b c d e f g h i j k l m n o */
4174 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4175/* p q r s t u v w x y z { | } ~ del */
4176 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004177};
4178
Antoine Pitrou244651a2009-05-04 18:56:13 +00004179/* ENCODE_DIRECT: this character should be encoded as itself. The
4180 * answer depends on whether we are encoding set O as itself, and also
4181 * on whether we are encoding whitespace as itself. RFC2152 makes it
4182 * clear that the answers to these questions vary between
4183 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004184
Antoine Pitrou244651a2009-05-04 18:56:13 +00004185#define ENCODE_DIRECT(c, directO, directWS) \
4186 ((c) < 128 && (c) > 0 && \
4187 ((utf7_category[(c)] == 0) || \
4188 (directWS && (utf7_category[(c)] == 2)) || \
4189 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004190
Alexander Belopolsky40018472011-02-26 01:02:56 +00004191PyObject *
4192PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004193 Py_ssize_t size,
4194 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004195{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004196 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4197}
4198
Antoine Pitrou244651a2009-05-04 18:56:13 +00004199/* The decoder. The only state we preserve is our read position,
4200 * i.e. how many characters we have consumed. So if we end in the
4201 * middle of a shift sequence we have to back off the read position
4202 * and the output to the beginning of the sequence, otherwise we lose
4203 * all the shift state (seen bits, number of bits seen, high
4204 * surrogate). */
4205
Alexander Belopolsky40018472011-02-26 01:02:56 +00004206PyObject *
4207PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004208 Py_ssize_t size,
4209 const char *errors,
4210 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004211{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004212 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004213 Py_ssize_t startinpos;
4214 Py_ssize_t endinpos;
4215 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004216 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004217 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004218 const char *errmsg = "";
4219 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004220 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004221 unsigned int base64bits = 0;
4222 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004223 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004224 PyObject *errorHandler = NULL;
4225 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004226
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004227 /* Start off assuming it's all ASCII. Widen later as necessary. */
4228 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004229 if (!unicode)
4230 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004231 if (size == 0) {
4232 if (consumed)
4233 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004234 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004235 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004236
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004237 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004238 e = s + size;
4239
4240 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004241 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004242 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004243 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004244
Antoine Pitrou244651a2009-05-04 18:56:13 +00004245 if (inShift) { /* in a base-64 section */
4246 if (IS_BASE64(ch)) { /* consume a base-64 character */
4247 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4248 base64bits += 6;
4249 s++;
4250 if (base64bits >= 16) {
4251 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004252 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004253 base64bits -= 16;
4254 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4255 if (surrogate) {
4256 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004257 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4258 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004259 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4260 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004261 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004262 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004263 }
4264 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004265 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4266 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004267 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004268 }
4269 }
Victor Stinner551ac952011-11-29 22:58:13 +01004270 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004271 /* first surrogate */
4272 surrogate = outCh;
4273 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004274 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004275 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4276 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004277 }
4278 }
4279 }
4280 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004281 inShift = 0;
4282 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004283 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004284 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4285 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004286 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004287 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004288 if (base64bits > 0) { /* left-over bits */
4289 if (base64bits >= 6) {
4290 /* We've seen at least one base-64 character */
4291 errmsg = "partial character in shift sequence";
4292 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004293 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004294 else {
4295 /* Some bits remain; they should be zero */
4296 if (base64buffer != 0) {
4297 errmsg = "non-zero padding bits in shift sequence";
4298 goto utf7Error;
4299 }
4300 }
4301 }
4302 if (ch != '-') {
4303 /* '-' is absorbed; other terminating
4304 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004305 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4306 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004307 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004308 }
4309 }
4310 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004311 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004312 s++; /* consume '+' */
4313 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004314 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004315 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4316 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004317 }
4318 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004319 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004320 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004321 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004322 }
4323 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004324 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004325 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4326 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004327 s++;
4328 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004329 else {
4330 startinpos = s-starts;
4331 s++;
4332 errmsg = "unexpected special character";
4333 goto utf7Error;
4334 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004335 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004336utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004337 endinpos = s-starts;
4338 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004339 errors, &errorHandler,
4340 "utf7", errmsg,
4341 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004342 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004343 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004344 }
4345
Antoine Pitrou244651a2009-05-04 18:56:13 +00004346 /* end of string */
4347
4348 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4349 /* if we're in an inconsistent state, that's an error */
4350 if (surrogate ||
4351 (base64bits >= 6) ||
4352 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004353 endinpos = size;
4354 if (unicode_decode_call_errorhandler(
4355 errors, &errorHandler,
4356 "utf7", "unterminated shift sequence",
4357 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004358 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004359 goto onError;
4360 if (s < e)
4361 goto restart;
4362 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004363 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004364
4365 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004366 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004367 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004368 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004369 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004370 }
4371 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004372 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004373 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004374 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004375
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004376 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004377 goto onError;
4378
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004379 Py_XDECREF(errorHandler);
4380 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004381 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004382
Benjamin Peterson29060642009-01-31 22:14:21 +00004383 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004384 Py_XDECREF(errorHandler);
4385 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004386 Py_DECREF(unicode);
4387 return NULL;
4388}
4389
4390
Alexander Belopolsky40018472011-02-26 01:02:56 +00004391PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004392_PyUnicode_EncodeUTF7(PyObject *str,
4393 int base64SetO,
4394 int base64WhiteSpace,
4395 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004396{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004397 int kind;
4398 void *data;
4399 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004400 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004401 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004402 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004403 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004404 unsigned int base64bits = 0;
4405 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004406 char * out;
4407 char * start;
4408
Benjamin Petersonbac79492012-01-14 13:34:47 -05004409 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004410 return NULL;
4411 kind = PyUnicode_KIND(str);
4412 data = PyUnicode_DATA(str);
4413 len = PyUnicode_GET_LENGTH(str);
4414
4415 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004416 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004417
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004418 /* It might be possible to tighten this worst case */
4419 allocated = 8 * len;
4420 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004421 return PyErr_NoMemory();
4422
Antoine Pitrou244651a2009-05-04 18:56:13 +00004423 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004424 if (v == NULL)
4425 return NULL;
4426
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004427 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004428 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004429 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004430
Antoine Pitrou244651a2009-05-04 18:56:13 +00004431 if (inShift) {
4432 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4433 /* shifting out */
4434 if (base64bits) { /* output remaining bits */
4435 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4436 base64buffer = 0;
4437 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004438 }
4439 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004440 /* Characters not in the BASE64 set implicitly unshift the sequence
4441 so no '-' is required, except if the character is itself a '-' */
4442 if (IS_BASE64(ch) || ch == '-') {
4443 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004444 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004445 *out++ = (char) ch;
4446 }
4447 else {
4448 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004449 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004450 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004451 else { /* not in a shift sequence */
4452 if (ch == '+') {
4453 *out++ = '+';
4454 *out++ = '-';
4455 }
4456 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4457 *out++ = (char) ch;
4458 }
4459 else {
4460 *out++ = '+';
4461 inShift = 1;
4462 goto encode_char;
4463 }
4464 }
4465 continue;
4466encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004467 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004468 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004469
Antoine Pitrou244651a2009-05-04 18:56:13 +00004470 /* code first surrogate */
4471 base64bits += 16;
4472 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4473 while (base64bits >= 6) {
4474 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4475 base64bits -= 6;
4476 }
4477 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004478 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004479 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004480 base64bits += 16;
4481 base64buffer = (base64buffer << 16) | ch;
4482 while (base64bits >= 6) {
4483 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4484 base64bits -= 6;
4485 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004486 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004487 if (base64bits)
4488 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4489 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004490 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004491 if (_PyBytes_Resize(&v, out - start) < 0)
4492 return NULL;
4493 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004494}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004495PyObject *
4496PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4497 Py_ssize_t size,
4498 int base64SetO,
4499 int base64WhiteSpace,
4500 const char *errors)
4501{
4502 PyObject *result;
4503 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4504 if (tmp == NULL)
4505 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004506 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004507 base64WhiteSpace, errors);
4508 Py_DECREF(tmp);
4509 return result;
4510}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004511
Antoine Pitrou244651a2009-05-04 18:56:13 +00004512#undef IS_BASE64
4513#undef FROM_BASE64
4514#undef TO_BASE64
4515#undef DECODE_DIRECT
4516#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004517
Guido van Rossumd57fd912000-03-10 22:53:23 +00004518/* --- UTF-8 Codec -------------------------------------------------------- */
4519
Tim Petersced69f82003-09-16 20:30:58 +00004520static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004521char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004522 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4523 illegal prefix. See RFC 3629 for details */
4524 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4525 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004526 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004527 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4528 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4529 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4530 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004531 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4532 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80-8F */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004533 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4534 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004535 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4536 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4537 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4538 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4539 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0-F4 + F5-FF */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004540};
4541
Alexander Belopolsky40018472011-02-26 01:02:56 +00004542PyObject *
4543PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004544 Py_ssize_t size,
4545 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004546{
Walter Dörwald69652032004-09-07 20:24:22 +00004547 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4548}
4549
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004550#include "stringlib/ucs1lib.h"
4551#include "stringlib/codecs.h"
4552#include "stringlib/undef.h"
4553
4554#include "stringlib/ucs2lib.h"
4555#include "stringlib/codecs.h"
4556#include "stringlib/undef.h"
4557
4558#include "stringlib/ucs4lib.h"
4559#include "stringlib/codecs.h"
4560#include "stringlib/undef.h"
4561
Antoine Pitrouab868312009-01-10 15:40:25 +00004562/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4563#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4564
4565/* Mask to quickly check whether a C 'long' contains a
4566 non-ASCII, UTF8-encoded char. */
4567#if (SIZEOF_LONG == 8)
4568# define ASCII_CHAR_MASK 0x8080808080808080L
4569#elif (SIZEOF_LONG == 4)
4570# define ASCII_CHAR_MASK 0x80808080L
4571#else
4572# error C 'long' size should be either 4 or 8!
4573#endif
4574
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004575/* Scans a UTF-8 string and returns the maximum character to be expected
4576 and the size of the decoded unicode string.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004577
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004578 This function doesn't check for errors, these checks are performed in
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004579 PyUnicode_DecodeUTF8Stateful.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004580 */
4581static Py_UCS4
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004582utf8_scanner(const unsigned char *p, Py_ssize_t string_size, Py_ssize_t *unicode_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004583{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004584 Py_ssize_t char_count = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004585 const unsigned char *end = p + string_size;
4586 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004587
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004588 assert(unicode_size != NULL);
4589
4590 /* By having a cascade of independent loops which fallback onto each
4591 other, we minimize the amount of work done in the average loop
4592 iteration, and we also maximize the CPU's ability to predict
4593 branches correctly (because a given condition will have always the
4594 same boolean outcome except perhaps in the last iteration of the
4595 corresponding loop).
4596 In the general case this brings us rather close to decoding
4597 performance pre-PEP 393, despite the two-pass decoding.
4598
4599 Note that the pure ASCII loop is not duplicated once a non-ASCII
4600 character has been encountered. It is actually a pessimization (by
4601 a significant factor) to use this loop on text with many non-ASCII
4602 characters, and it is important to avoid bad performance on valid
4603 utf-8 data (invalid utf-8 being a different can of worms).
4604 */
4605
4606 /* ASCII */
4607 for (; p < end; ++p) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004608 /* Only check value if it's not a ASCII char... */
4609 if (*p < 0x80) {
4610 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4611 an explanation. */
4612 if (!((size_t) p & LONG_PTR_MASK)) {
4613 /* Help register allocation */
4614 register const unsigned char *_p = p;
4615 while (_p < aligned_end) {
4616 unsigned long value = *(unsigned long *) _p;
4617 if (value & ASCII_CHAR_MASK)
4618 break;
4619 _p += SIZEOF_LONG;
4620 char_count += SIZEOF_LONG;
4621 }
4622 p = _p;
4623 if (p == end)
4624 break;
4625 }
4626 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004627 if (*p < 0x80)
4628 ++char_count;
4629 else
4630 goto _ucs1loop;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004631 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004632 *unicode_size = char_count;
4633 return 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004634
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004635_ucs1loop:
4636 for (; p < end; ++p) {
4637 if (*p < 0xc4)
4638 char_count += ((*p & 0xc0) != 0x80);
4639 else
4640 goto _ucs2loop;
4641 }
4642 *unicode_size = char_count;
4643 return 255;
4644
4645_ucs2loop:
4646 for (; p < end; ++p) {
4647 if (*p < 0xf0)
4648 char_count += ((*p & 0xc0) != 0x80);
4649 else
4650 goto _ucs4loop;
4651 }
4652 *unicode_size = char_count;
4653 return 65535;
4654
4655_ucs4loop:
4656 for (; p < end; ++p) {
4657 char_count += ((*p & 0xc0) != 0x80);
4658 }
4659 *unicode_size = char_count;
4660 return 65537;
4661}
4662
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004663/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
Victor Stinner785938e2011-12-11 20:09:03 +01004664 in case of errors. Implicit parameters: unicode, kind, data, onError.
4665 Potential resizing overallocates, so the result needs to shrink at the end.
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004666*/
Victor Stinner785938e2011-12-11 20:09:03 +01004667#define WRITE_MAYBE_FAIL(index, value) \
4668 do { \
4669 Py_ssize_t pos = index; \
4670 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4671 unicode_resize(&unicode, pos + pos/8) < 0) \
4672 goto onError; \
4673 if (unicode_putchar(&unicode, &pos, value) < 0) \
4674 goto onError; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004675 } while (0)
4676
Victor Stinnerbf6e5602011-12-12 01:53:47 +01004677static PyObject *
Victor Stinner785938e2011-12-11 20:09:03 +01004678decode_utf8_errors(const char *starts,
4679 Py_ssize_t size,
4680 const char *errors,
4681 Py_ssize_t *consumed,
4682 const char *s,
4683 PyObject *unicode,
4684 Py_ssize_t i)
Walter Dörwald69652032004-09-07 20:24:22 +00004685{
Guido van Rossumd57fd912000-03-10 22:53:23 +00004686 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004687 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004688 Py_ssize_t startinpos;
4689 Py_ssize_t endinpos;
Victor Stinner785938e2011-12-11 20:09:03 +01004690 const char *e = starts + size;
4691 const char *aligned_end;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004692 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004693 PyObject *errorHandler = NULL;
4694 PyObject *exc = NULL;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004695
Antoine Pitrouab868312009-01-10 15:40:25 +00004696 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004697
4698 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004699 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004700
4701 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004702 /* Fast path for runs of ASCII characters. Given that common UTF-8
4703 input will consist of an overwhelming majority of ASCII
4704 characters, we try to optimize for this case by checking
4705 as many characters as a C 'long' can contain.
4706 First, check if we can do an aligned read, as most CPUs have
4707 a penalty for unaligned reads.
4708 */
4709 if (!((size_t) s & LONG_PTR_MASK)) {
4710 /* Help register allocation */
4711 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004712 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004713 while (_s < aligned_end) {
4714 /* Read a whole long at a time (either 4 or 8 bytes),
4715 and do a fast unrolled copy if it only contains ASCII
4716 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004717 unsigned long value = *(unsigned long *) _s;
4718 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004719 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004720 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4721 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4722 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4723 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004724#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004725 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4726 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4727 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4728 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004729#endif
4730 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004731 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004732 }
4733 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004734 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004735 if (s == e)
4736 break;
4737 ch = (unsigned char)*s;
4738 }
4739 }
4740
4741 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004742 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004743 s++;
4744 continue;
4745 }
4746
4747 n = utf8_code_length[ch];
4748
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004749 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004750 if (consumed)
4751 break;
4752 else {
4753 errmsg = "unexpected end of data";
4754 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004755 endinpos = startinpos+1;
4756 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4757 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004758 goto utf8Error;
4759 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004760 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004761
4762 switch (n) {
4763
4764 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004765 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004766 startinpos = s-starts;
4767 endinpos = startinpos+1;
4768 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004769
4770 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004771 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004772 startinpos = s-starts;
4773 endinpos = startinpos+1;
4774 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004775
4776 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004777 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004778 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004779 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004780 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004781 goto utf8Error;
4782 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004783 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004784 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004785 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004786 break;
4787
4788 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004789 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4790 will result in surrogates in range d800-dfff. Surrogates are
4791 not valid UTF-8 so they are rejected.
4792 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4793 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004794 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004795 (s[2] & 0xc0) != 0x80 ||
4796 ((unsigned char)s[0] == 0xE0 &&
4797 (unsigned char)s[1] < 0xA0) ||
4798 ((unsigned char)s[0] == 0xED &&
4799 (unsigned char)s[1] > 0x9F)) {
4800 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004801 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004802 endinpos = startinpos + 1;
4803
4804 /* if s[1] first two bits are 1 and 0, then the invalid
4805 continuation byte is s[2], so increment endinpos by 1,
4806 if not, s[1] is invalid and endinpos doesn't need to
4807 be incremented. */
4808 if ((s[1] & 0xC0) == 0x80)
4809 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004810 goto utf8Error;
4811 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004812 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004813 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004814 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004815 break;
4816
4817 case 4:
4818 if ((s[1] & 0xc0) != 0x80 ||
4819 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004820 (s[3] & 0xc0) != 0x80 ||
4821 ((unsigned char)s[0] == 0xF0 &&
4822 (unsigned char)s[1] < 0x90) ||
4823 ((unsigned char)s[0] == 0xF4 &&
4824 (unsigned char)s[1] > 0x8F)) {
4825 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004826 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004827 endinpos = startinpos + 1;
4828 if ((s[1] & 0xC0) == 0x80) {
4829 endinpos++;
4830 if ((s[2] & 0xC0) == 0x80)
4831 endinpos++;
4832 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004833 goto utf8Error;
4834 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004835 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004836 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01004837 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Ezio Melotti57221d02010-07-01 07:32:02 +00004838
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004839 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004840 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004841 }
4842 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004843 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004844
Benjamin Peterson29060642009-01-31 22:14:21 +00004845 utf8Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00004846 if (unicode_decode_call_errorhandler(
4847 errors, &errorHandler,
Victor Stinnercbe01342012-02-14 01:17:45 +01004848 "utf-8", errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00004849 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004850 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004851 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004852 /* Update data because unicode_decode_call_errorhandler might have
4853 re-created or resized the unicode object. */
Benjamin Peterson29060642009-01-31 22:14:21 +00004854 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004855 }
Walter Dörwald69652032004-09-07 20:24:22 +00004856 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004857 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004858
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004859 /* Adjust length and ready string when it contained errors and
4860 is of the old resizable kind. */
Victor Stinner785938e2011-12-11 20:09:03 +01004861 if (unicode_resize(&unicode, i) < 0)
4862 goto onError;
4863 unicode_adjust_maxchar(&unicode);
4864 if (unicode == NULL)
4865 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004866
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004867 Py_XDECREF(errorHandler);
4868 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004869 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004870 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004871
Benjamin Peterson29060642009-01-31 22:14:21 +00004872 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004873 Py_XDECREF(errorHandler);
4874 Py_XDECREF(exc);
Victor Stinner785938e2011-12-11 20:09:03 +01004875 Py_XDECREF(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004876 return NULL;
4877}
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004878#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004879
Victor Stinner785938e2011-12-11 20:09:03 +01004880PyObject *
4881PyUnicode_DecodeUTF8Stateful(const char *s,
4882 Py_ssize_t size,
4883 const char *errors,
4884 Py_ssize_t *consumed)
4885{
4886 Py_UCS4 maxchar = 0;
4887 Py_ssize_t unicode_size;
4888 int has_errors = 0;
4889 PyObject *unicode;
4890 int kind;
4891 void *data;
4892 const char *starts = s;
4893 const char *e;
4894 Py_ssize_t i;
4895
4896 if (size == 0) {
4897 if (consumed)
4898 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004899 Py_INCREF(unicode_empty);
4900 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004901 }
4902
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004903 maxchar = utf8_scanner((const unsigned char *)s, size, &unicode_size);
Victor Stinner785938e2011-12-11 20:09:03 +01004904
4905 /* When the string is ASCII only, just use memcpy and return.
4906 unicode_size may be != size if there is an incomplete UTF-8
4907 sequence at the end of the ASCII block. */
4908 if (maxchar < 128 && size == unicode_size) {
4909 if (consumed)
4910 *consumed = size;
Victor Stinnerab870212011-12-17 22:39:43 +01004911 return unicode_fromascii((const unsigned char *)s, size);
Victor Stinner785938e2011-12-11 20:09:03 +01004912 }
4913
4914 unicode = PyUnicode_New(unicode_size, maxchar);
4915 if (!unicode)
4916 return NULL;
4917 kind = PyUnicode_KIND(unicode);
4918 data = PyUnicode_DATA(unicode);
4919
4920 /* Unpack UTF-8 encoded data */
4921 i = 0;
4922 e = starts + size;
4923 switch (kind) {
4924 case PyUnicode_1BYTE_KIND:
4925 has_errors = ucs1lib_utf8_try_decode(s, e, (Py_UCS1 *) data, &s, &i);
4926 break;
4927 case PyUnicode_2BYTE_KIND:
4928 has_errors = ucs2lib_utf8_try_decode(s, e, (Py_UCS2 *) data, &s, &i);
4929 break;
4930 case PyUnicode_4BYTE_KIND:
4931 has_errors = ucs4lib_utf8_try_decode(s, e, (Py_UCS4 *) data, &s, &i);
4932 break;
4933 }
4934 if (!has_errors) {
4935 /* Ensure the unicode size calculation was correct */
4936 assert(i == unicode_size);
4937 assert(s == e);
4938 if (consumed)
4939 *consumed = size;
4940 return unicode;
4941 }
4942
4943 /* In case of errors, maxchar and size computation might be incorrect;
4944 code below refits and resizes as necessary. */
4945 return decode_utf8_errors(starts, size, errors, consumed, s, unicode, i);
4946}
4947
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004948#ifdef __APPLE__
4949
4950/* Simplified UTF-8 decoder using surrogateescape error handler,
4951 used to decode the command line arguments on Mac OS X. */
4952
4953wchar_t*
4954_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4955{
4956 int n;
4957 const char *e;
4958 wchar_t *unicode, *p;
4959
4960 /* Note: size will always be longer than the resulting Unicode
4961 character count */
4962 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4963 PyErr_NoMemory();
4964 return NULL;
4965 }
4966 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4967 if (!unicode)
4968 return NULL;
4969
4970 /* Unpack UTF-8 encoded data */
4971 p = unicode;
4972 e = s + size;
4973 while (s < e) {
4974 Py_UCS4 ch = (unsigned char)*s;
4975
4976 if (ch < 0x80) {
4977 *p++ = (wchar_t)ch;
4978 s++;
4979 continue;
4980 }
4981
4982 n = utf8_code_length[ch];
4983 if (s + n > e) {
4984 goto surrogateescape;
4985 }
4986
4987 switch (n) {
4988 case 0:
4989 case 1:
4990 goto surrogateescape;
4991
4992 case 2:
4993 if ((s[1] & 0xc0) != 0x80)
4994 goto surrogateescape;
4995 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4996 assert ((ch > 0x007F) && (ch <= 0x07FF));
4997 *p++ = (wchar_t)ch;
4998 break;
4999
5000 case 3:
5001 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
5002 will result in surrogates in range d800-dfff. Surrogates are
5003 not valid UTF-8 so they are rejected.
5004 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
5005 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
5006 if ((s[1] & 0xc0) != 0x80 ||
5007 (s[2] & 0xc0) != 0x80 ||
5008 ((unsigned char)s[0] == 0xE0 &&
5009 (unsigned char)s[1] < 0xA0) ||
5010 ((unsigned char)s[0] == 0xED &&
5011 (unsigned char)s[1] > 0x9F)) {
5012
5013 goto surrogateescape;
5014 }
5015 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
5016 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005017 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005018 break;
5019
5020 case 4:
5021 if ((s[1] & 0xc0) != 0x80 ||
5022 (s[2] & 0xc0) != 0x80 ||
5023 (s[3] & 0xc0) != 0x80 ||
5024 ((unsigned char)s[0] == 0xF0 &&
5025 (unsigned char)s[1] < 0x90) ||
5026 ((unsigned char)s[0] == 0xF4 &&
5027 (unsigned char)s[1] > 0x8F)) {
5028 goto surrogateescape;
5029 }
5030 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
5031 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01005032 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005033
5034#if SIZEOF_WCHAR_T == 4
5035 *p++ = (wchar_t)ch;
5036#else
5037 /* compute and append the two surrogates: */
Victor Stinner551ac952011-11-29 22:58:13 +01005038 *p++ = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5039 *p++ = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005040#endif
5041 break;
5042 }
5043 s += n;
5044 continue;
5045
5046 surrogateescape:
5047 *p++ = 0xDC00 + ch;
5048 s++;
5049 }
5050 *p = L'\0';
5051 return unicode;
5052}
5053
5054#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005055
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005056/* Primary internal function which creates utf8 encoded bytes objects.
5057
5058 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005059 and allocate exactly as much space needed at the end. Else allocate the
5060 maximum possible needed (4 result bytes per Unicode character), and return
5061 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005062*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005063PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005064_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005065{
Victor Stinner6099a032011-12-18 14:22:26 +01005066 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005067 void *data;
5068 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005069
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005070 if (!PyUnicode_Check(unicode)) {
5071 PyErr_BadArgument();
5072 return NULL;
5073 }
5074
5075 if (PyUnicode_READY(unicode) == -1)
5076 return NULL;
5077
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005078 if (PyUnicode_UTF8(unicode))
5079 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5080 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005081
5082 kind = PyUnicode_KIND(unicode);
5083 data = PyUnicode_DATA(unicode);
5084 size = PyUnicode_GET_LENGTH(unicode);
5085
Benjamin Petersonead6b532011-12-20 17:23:42 -06005086 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005087 default:
5088 assert(0);
5089 case PyUnicode_1BYTE_KIND:
5090 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5091 assert(!PyUnicode_IS_ASCII(unicode));
5092 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5093 case PyUnicode_2BYTE_KIND:
5094 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5095 case PyUnicode_4BYTE_KIND:
5096 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005097 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005098}
5099
Alexander Belopolsky40018472011-02-26 01:02:56 +00005100PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005101PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5102 Py_ssize_t size,
5103 const char *errors)
5104{
5105 PyObject *v, *unicode;
5106
5107 unicode = PyUnicode_FromUnicode(s, size);
5108 if (unicode == NULL)
5109 return NULL;
5110 v = _PyUnicode_AsUTF8String(unicode, errors);
5111 Py_DECREF(unicode);
5112 return v;
5113}
5114
5115PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005116PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005117{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005118 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005119}
5120
Walter Dörwald41980ca2007-08-16 21:55:45 +00005121/* --- UTF-32 Codec ------------------------------------------------------- */
5122
5123PyObject *
5124PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005125 Py_ssize_t size,
5126 const char *errors,
5127 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005128{
5129 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5130}
5131
5132PyObject *
5133PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005134 Py_ssize_t size,
5135 const char *errors,
5136 int *byteorder,
5137 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005138{
5139 const char *starts = s;
5140 Py_ssize_t startinpos;
5141 Py_ssize_t endinpos;
5142 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005143 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005144 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005145 int bo = 0; /* assume native ordering by default */
5146 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005147 /* Offsets from q for retrieving bytes in the right order. */
5148#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5149 int iorder[] = {0, 1, 2, 3};
5150#else
5151 int iorder[] = {3, 2, 1, 0};
5152#endif
5153 PyObject *errorHandler = NULL;
5154 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005155
Walter Dörwald41980ca2007-08-16 21:55:45 +00005156 q = (unsigned char *)s;
5157 e = q + size;
5158
5159 if (byteorder)
5160 bo = *byteorder;
5161
5162 /* Check for BOM marks (U+FEFF) in the input and adjust current
5163 byte order setting accordingly. In native mode, the leading BOM
5164 mark is skipped, in all other modes, it is copied to the output
5165 stream as-is (giving a ZWNBSP character). */
5166 if (bo == 0) {
5167 if (size >= 4) {
5168 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00005169 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005170#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005171 if (bom == 0x0000FEFF) {
5172 q += 4;
5173 bo = -1;
5174 }
5175 else if (bom == 0xFFFE0000) {
5176 q += 4;
5177 bo = 1;
5178 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005179#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005180 if (bom == 0x0000FEFF) {
5181 q += 4;
5182 bo = 1;
5183 }
5184 else if (bom == 0xFFFE0000) {
5185 q += 4;
5186 bo = -1;
5187 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005188#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005189 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005190 }
5191
5192 if (bo == -1) {
5193 /* force LE */
5194 iorder[0] = 0;
5195 iorder[1] = 1;
5196 iorder[2] = 2;
5197 iorder[3] = 3;
5198 }
5199 else if (bo == 1) {
5200 /* force BE */
5201 iorder[0] = 3;
5202 iorder[1] = 2;
5203 iorder[2] = 1;
5204 iorder[3] = 0;
5205 }
5206
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005207 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005208 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005209 if (!unicode)
5210 return NULL;
5211 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005212 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005213 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005214
Walter Dörwald41980ca2007-08-16 21:55:45 +00005215 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005216 Py_UCS4 ch;
5217 /* remaining bytes at the end? (size should be divisible by 4) */
5218 if (e-q<4) {
5219 if (consumed)
5220 break;
5221 errmsg = "truncated data";
5222 startinpos = ((const char *)q)-starts;
5223 endinpos = ((const char *)e)-starts;
5224 goto utf32Error;
5225 /* The remaining input chars are ignored if the callback
5226 chooses to skip the input */
5227 }
5228 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5229 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005230
Benjamin Peterson29060642009-01-31 22:14:21 +00005231 if (ch >= 0x110000)
5232 {
5233 errmsg = "codepoint not in range(0x110000)";
5234 startinpos = ((const char *)q)-starts;
5235 endinpos = startinpos+4;
5236 goto utf32Error;
5237 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005238 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5239 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005240 q += 4;
5241 continue;
5242 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005243 if (unicode_decode_call_errorhandler(
5244 errors, &errorHandler,
5245 "utf32", errmsg,
5246 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005247 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005248 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005249 }
5250
5251 if (byteorder)
5252 *byteorder = bo;
5253
5254 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005255 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005256
5257 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005258 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005259 goto onError;
5260
5261 Py_XDECREF(errorHandler);
5262 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005263 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005264
Benjamin Peterson29060642009-01-31 22:14:21 +00005265 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005266 Py_DECREF(unicode);
5267 Py_XDECREF(errorHandler);
5268 Py_XDECREF(exc);
5269 return NULL;
5270}
5271
5272PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005273_PyUnicode_EncodeUTF32(PyObject *str,
5274 const char *errors,
5275 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005276{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005277 int kind;
5278 void *data;
5279 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005280 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005281 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005282 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005283 /* Offsets from p for storing byte pairs in the right order. */
5284#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5285 int iorder[] = {0, 1, 2, 3};
5286#else
5287 int iorder[] = {3, 2, 1, 0};
5288#endif
5289
Benjamin Peterson29060642009-01-31 22:14:21 +00005290#define STORECHAR(CH) \
5291 do { \
5292 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5293 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5294 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5295 p[iorder[0]] = (CH) & 0xff; \
5296 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005297 } while(0)
5298
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005299 if (!PyUnicode_Check(str)) {
5300 PyErr_BadArgument();
5301 return NULL;
5302 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005303 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005304 return NULL;
5305 kind = PyUnicode_KIND(str);
5306 data = PyUnicode_DATA(str);
5307 len = PyUnicode_GET_LENGTH(str);
5308
5309 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005310 bytesize = nsize * 4;
5311 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005312 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005313 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005314 if (v == NULL)
5315 return NULL;
5316
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005317 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005318 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005319 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005320 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005321 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005322
5323 if (byteorder == -1) {
5324 /* force LE */
5325 iorder[0] = 0;
5326 iorder[1] = 1;
5327 iorder[2] = 2;
5328 iorder[3] = 3;
5329 }
5330 else if (byteorder == 1) {
5331 /* force BE */
5332 iorder[0] = 3;
5333 iorder[1] = 2;
5334 iorder[2] = 1;
5335 iorder[3] = 0;
5336 }
5337
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005338 for (i = 0; i < len; i++)
5339 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005340
5341 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005342 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005343#undef STORECHAR
5344}
5345
Alexander Belopolsky40018472011-02-26 01:02:56 +00005346PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005347PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5348 Py_ssize_t size,
5349 const char *errors,
5350 int byteorder)
5351{
5352 PyObject *result;
5353 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5354 if (tmp == NULL)
5355 return NULL;
5356 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5357 Py_DECREF(tmp);
5358 return result;
5359}
5360
5361PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005362PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005363{
Victor Stinnerb960b342011-11-20 19:12:52 +01005364 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005365}
5366
Guido van Rossumd57fd912000-03-10 22:53:23 +00005367/* --- UTF-16 Codec ------------------------------------------------------- */
5368
Tim Peters772747b2001-08-09 22:21:55 +00005369PyObject *
5370PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005371 Py_ssize_t size,
5372 const char *errors,
5373 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005374{
Walter Dörwald69652032004-09-07 20:24:22 +00005375 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5376}
5377
Antoine Pitrouab868312009-01-10 15:40:25 +00005378/* Two masks for fast checking of whether a C 'long' may contain
5379 UTF16-encoded surrogate characters. This is an efficient heuristic,
5380 assuming that non-surrogate characters with a code point >= 0x8000 are
5381 rare in most input.
5382 FAST_CHAR_MASK is used when the input is in native byte ordering,
5383 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005384*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005385#if (SIZEOF_LONG == 8)
5386# define FAST_CHAR_MASK 0x8000800080008000L
5387# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5388#elif (SIZEOF_LONG == 4)
5389# define FAST_CHAR_MASK 0x80008000L
5390# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5391#else
5392# error C 'long' size should be either 4 or 8!
5393#endif
5394
Walter Dörwald69652032004-09-07 20:24:22 +00005395PyObject *
5396PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005397 Py_ssize_t size,
5398 const char *errors,
5399 int *byteorder,
5400 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005401{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005402 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005403 Py_ssize_t startinpos;
5404 Py_ssize_t endinpos;
5405 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005406 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005407 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005408 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005409 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005410 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005411 /* Offsets from q for retrieving byte pairs in the right order. */
5412#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5413 int ihi = 1, ilo = 0;
5414#else
5415 int ihi = 0, ilo = 1;
5416#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005417 PyObject *errorHandler = NULL;
5418 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005419
5420 /* Note: size will always be longer than the resulting Unicode
5421 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005422 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005423 if (!unicode)
5424 return NULL;
5425 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005426 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005427 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428
Tim Peters772747b2001-08-09 22:21:55 +00005429 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005430 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005431
5432 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005433 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005434
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005435 /* Check for BOM marks (U+FEFF) in the input and adjust current
5436 byte order setting accordingly. In native mode, the leading BOM
5437 mark is skipped, in all other modes, it is copied to the output
5438 stream as-is (giving a ZWNBSP character). */
5439 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005440 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005441 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005442#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005443 if (bom == 0xFEFF) {
5444 q += 2;
5445 bo = -1;
5446 }
5447 else if (bom == 0xFFFE) {
5448 q += 2;
5449 bo = 1;
5450 }
Tim Petersced69f82003-09-16 20:30:58 +00005451#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005452 if (bom == 0xFEFF) {
5453 q += 2;
5454 bo = 1;
5455 }
5456 else if (bom == 0xFFFE) {
5457 q += 2;
5458 bo = -1;
5459 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005460#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005461 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005462 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005463
Tim Peters772747b2001-08-09 22:21:55 +00005464 if (bo == -1) {
5465 /* force LE */
5466 ihi = 1;
5467 ilo = 0;
5468 }
5469 else if (bo == 1) {
5470 /* force BE */
5471 ihi = 0;
5472 ilo = 1;
5473 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005474#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5475 native_ordering = ilo < ihi;
5476#else
5477 native_ordering = ilo > ihi;
5478#endif
Tim Peters772747b2001-08-09 22:21:55 +00005479
Antoine Pitrouab868312009-01-10 15:40:25 +00005480 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005481 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005482 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005483 /* First check for possible aligned read of a C 'long'. Unaligned
5484 reads are more expensive, better to defer to another iteration. */
5485 if (!((size_t) q & LONG_PTR_MASK)) {
5486 /* Fast path for runs of non-surrogate chars. */
5487 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005488 int kind = PyUnicode_KIND(unicode);
5489 void *data = PyUnicode_DATA(unicode);
5490 while (_q < aligned_end) {
5491 unsigned long block = * (unsigned long *) _q;
5492 unsigned short *pblock = (unsigned short*)&block;
5493 Py_UCS4 maxch;
5494 if (native_ordering) {
5495 /* Can use buffer directly */
5496 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005497 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005498 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005499 else {
5500 /* Need to byte-swap */
5501 unsigned char *_p = (unsigned char*)pblock;
5502 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005503 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005504 _p[0] = _q[1];
5505 _p[1] = _q[0];
5506 _p[2] = _q[3];
5507 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005508#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005509 _p[4] = _q[5];
5510 _p[5] = _q[4];
5511 _p[6] = _q[7];
5512 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005513#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005514 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005515 maxch = Py_MAX(pblock[0], pblock[1]);
5516#if SIZEOF_LONG == 8
5517 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5518#endif
5519 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5520 if (unicode_widen(&unicode, maxch) < 0)
5521 goto onError;
5522 kind = PyUnicode_KIND(unicode);
5523 data = PyUnicode_DATA(unicode);
5524 }
5525 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5526 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5527#if SIZEOF_LONG == 8
5528 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5529 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5530#endif
5531 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005532 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005533 q = _q;
5534 if (q >= e)
5535 break;
5536 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005537 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005538
Benjamin Peterson14339b62009-01-31 16:36:08 +00005539 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005540
Victor Stinner551ac952011-11-29 22:58:13 +01005541 if (!Py_UNICODE_IS_SURROGATE(ch)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005542 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5543 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005544 continue;
5545 }
5546
5547 /* UTF-16 code pair: */
5548 if (q > e) {
5549 errmsg = "unexpected end of data";
5550 startinpos = (((const char *)q) - 2) - starts;
5551 endinpos = ((const char *)e) + 1 - starts;
5552 goto utf16Error;
5553 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005554 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5555 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005556 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005557 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005558 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005559 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005560 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005561 continue;
5562 }
5563 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005564 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005565 startinpos = (((const char *)q)-4)-starts;
5566 endinpos = startinpos+2;
5567 goto utf16Error;
5568 }
5569
Benjamin Peterson14339b62009-01-31 16:36:08 +00005570 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005571 errmsg = "illegal encoding";
5572 startinpos = (((const char *)q)-2)-starts;
5573 endinpos = startinpos+2;
5574 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005575
Benjamin Peterson29060642009-01-31 22:14:21 +00005576 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005577 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005578 errors,
5579 &errorHandler,
5580 "utf16", errmsg,
5581 &starts,
5582 (const char **)&e,
5583 &startinpos,
5584 &endinpos,
5585 &exc,
5586 (const char **)&q,
5587 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005588 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005589 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005590 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005591 /* remaining byte at the end? (size should be even) */
5592 if (e == q) {
5593 if (!consumed) {
5594 errmsg = "truncated data";
5595 startinpos = ((const char *)q) - starts;
5596 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005597 if (unicode_decode_call_errorhandler(
5598 errors,
5599 &errorHandler,
5600 "utf16", errmsg,
5601 &starts,
5602 (const char **)&e,
5603 &startinpos,
5604 &endinpos,
5605 &exc,
5606 (const char **)&q,
5607 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005608 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005609 goto onError;
5610 /* The remaining input chars are ignored if the callback
5611 chooses to skip the input */
5612 }
5613 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005614
5615 if (byteorder)
5616 *byteorder = bo;
5617
Walter Dörwald69652032004-09-07 20:24:22 +00005618 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005619 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005620
Guido van Rossumd57fd912000-03-10 22:53:23 +00005621 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005622 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005623 goto onError;
5624
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005625 Py_XDECREF(errorHandler);
5626 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005627 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005628
Benjamin Peterson29060642009-01-31 22:14:21 +00005629 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005630 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005631 Py_XDECREF(errorHandler);
5632 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005633 return NULL;
5634}
5635
Antoine Pitrouab868312009-01-10 15:40:25 +00005636#undef FAST_CHAR_MASK
5637#undef SWAPPED_FAST_CHAR_MASK
5638
Tim Peters772747b2001-08-09 22:21:55 +00005639PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005640_PyUnicode_EncodeUTF16(PyObject *str,
5641 const char *errors,
5642 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005643{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005644 int kind;
5645 void *data;
5646 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005647 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005648 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005649 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005650 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005651 /* Offsets from p for storing byte pairs in the right order. */
5652#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5653 int ihi = 1, ilo = 0;
5654#else
5655 int ihi = 0, ilo = 1;
5656#endif
5657
Benjamin Peterson29060642009-01-31 22:14:21 +00005658#define STORECHAR(CH) \
5659 do { \
5660 p[ihi] = ((CH) >> 8) & 0xff; \
5661 p[ilo] = (CH) & 0xff; \
5662 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005663 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005664
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005665 if (!PyUnicode_Check(str)) {
5666 PyErr_BadArgument();
5667 return NULL;
5668 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005669 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005670 return NULL;
5671 kind = PyUnicode_KIND(str);
5672 data = PyUnicode_DATA(str);
5673 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005674
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005675 pairs = 0;
5676 if (kind == PyUnicode_4BYTE_KIND)
5677 for (i = 0; i < len; i++)
5678 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5679 pairs++;
5680 /* 2 * (len + pairs + (byteorder == 0)) */
5681 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005682 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005683 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005684 bytesize = nsize * 2;
5685 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005686 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005687 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005688 if (v == NULL)
5689 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005690
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005691 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005692 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005693 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005694 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005695 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005696
5697 if (byteorder == -1) {
5698 /* force LE */
5699 ihi = 1;
5700 ilo = 0;
5701 }
5702 else if (byteorder == 1) {
5703 /* force BE */
5704 ihi = 0;
5705 ilo = 1;
5706 }
5707
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005708 for (i = 0; i < len; i++) {
5709 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5710 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005711 if (ch >= 0x10000) {
Victor Stinner551ac952011-11-29 22:58:13 +01005712 ch2 = Py_UNICODE_LOW_SURROGATE(ch);
5713 ch = Py_UNICODE_HIGH_SURROGATE(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00005714 }
Tim Peters772747b2001-08-09 22:21:55 +00005715 STORECHAR(ch);
5716 if (ch2)
5717 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005718 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005719
5720 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005721 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005722#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005723}
5724
Alexander Belopolsky40018472011-02-26 01:02:56 +00005725PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005726PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5727 Py_ssize_t size,
5728 const char *errors,
5729 int byteorder)
5730{
5731 PyObject *result;
5732 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5733 if (tmp == NULL)
5734 return NULL;
5735 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5736 Py_DECREF(tmp);
5737 return result;
5738}
5739
5740PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005741PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005742{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005743 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005744}
5745
5746/* --- Unicode Escape Codec ----------------------------------------------- */
5747
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005748/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5749 if all the escapes in the string make it still a valid ASCII string.
5750 Returns -1 if any escapes were found which cause the string to
5751 pop out of ASCII range. Otherwise returns the length of the
5752 required buffer to hold the string.
5753 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005754static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005755length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5756{
5757 const unsigned char *p = (const unsigned char *)s;
5758 const unsigned char *end = p + size;
5759 Py_ssize_t length = 0;
5760
5761 if (size < 0)
5762 return -1;
5763
5764 for (; p < end; ++p) {
5765 if (*p > 127) {
5766 /* Non-ASCII */
5767 return -1;
5768 }
5769 else if (*p != '\\') {
5770 /* Normal character */
5771 ++length;
5772 }
5773 else {
5774 /* Backslash-escape, check next char */
5775 ++p;
5776 /* Escape sequence reaches till end of string or
5777 non-ASCII follow-up. */
5778 if (p >= end || *p > 127)
5779 return -1;
5780 switch (*p) {
5781 case '\n':
5782 /* backslash + \n result in zero characters */
5783 break;
5784 case '\\': case '\'': case '\"':
5785 case 'b': case 'f': case 't':
5786 case 'n': case 'r': case 'v': case 'a':
5787 ++length;
5788 break;
5789 case '0': case '1': case '2': case '3':
5790 case '4': case '5': case '6': case '7':
5791 case 'x': case 'u': case 'U': case 'N':
5792 /* these do not guarantee ASCII characters */
5793 return -1;
5794 default:
5795 /* count the backslash + the other character */
5796 length += 2;
5797 }
5798 }
5799 }
5800 return length;
5801}
5802
Fredrik Lundh06d12682001-01-24 07:59:11 +00005803static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005804
Alexander Belopolsky40018472011-02-26 01:02:56 +00005805PyObject *
5806PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005807 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005808 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005809{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005810 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005811 Py_ssize_t startinpos;
5812 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005813 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005814 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005815 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005816 char* message;
5817 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005818 PyObject *errorHandler = NULL;
5819 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005820 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005821 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005822
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005823 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005824
5825 /* After length_of_escaped_ascii_string() there are two alternatives,
5826 either the string is pure ASCII with named escapes like \n, etc.
5827 and we determined it's exact size (common case)
5828 or it contains \x, \u, ... escape sequences. then we create a
5829 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005830 if (len >= 0) {
5831 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005832 if (!v)
5833 goto onError;
5834 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005835 }
5836 else {
5837 /* Escaped strings will always be longer than the resulting
5838 Unicode string, so we start with size here and then reduce the
5839 length after conversion to the true value.
5840 (but if the error callback returns a long replacement string
5841 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005842 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005843 if (!v)
5844 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005845 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005846 }
5847
Guido van Rossumd57fd912000-03-10 22:53:23 +00005848 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005849 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005850 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005851 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005852
Guido van Rossumd57fd912000-03-10 22:53:23 +00005853 while (s < end) {
5854 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005855 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005856 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005857
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005858 /* The only case in which i == ascii_length is a backslash
5859 followed by a newline. */
5860 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005861
Guido van Rossumd57fd912000-03-10 22:53:23 +00005862 /* Non-escape characters are interpreted as Unicode ordinals */
5863 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005864 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5865 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005866 continue;
5867 }
5868
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005869 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005870 /* \ - Escapes */
5871 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005872 c = *s++;
5873 if (s > end)
5874 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005875
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005876 /* The only case in which i == ascii_length is a backslash
5877 followed by a newline. */
5878 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005879
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005880 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005881
Benjamin Peterson29060642009-01-31 22:14:21 +00005882 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005883#define WRITECHAR(ch) \
5884 do { \
5885 if (unicode_putchar(&v, &i, ch) < 0) \
5886 goto onError; \
5887 }while(0)
5888
Guido van Rossumd57fd912000-03-10 22:53:23 +00005889 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005890 case '\\': WRITECHAR('\\'); break;
5891 case '\'': WRITECHAR('\''); break;
5892 case '\"': WRITECHAR('\"'); break;
5893 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005894 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005895 case 'f': WRITECHAR('\014'); break;
5896 case 't': WRITECHAR('\t'); break;
5897 case 'n': WRITECHAR('\n'); break;
5898 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005899 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005900 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005901 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005902 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005903
Benjamin Peterson29060642009-01-31 22:14:21 +00005904 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005905 case '0': case '1': case '2': case '3':
5906 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005907 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005908 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005909 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005910 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005911 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005912 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005913 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914 break;
5915
Benjamin Peterson29060642009-01-31 22:14:21 +00005916 /* hex escapes */
5917 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005918 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005919 digits = 2;
5920 message = "truncated \\xXX escape";
5921 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005922
Benjamin Peterson29060642009-01-31 22:14:21 +00005923 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005924 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005925 digits = 4;
5926 message = "truncated \\uXXXX escape";
5927 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005928
Benjamin Peterson29060642009-01-31 22:14:21 +00005929 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005930 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005931 digits = 8;
5932 message = "truncated \\UXXXXXXXX escape";
5933 hexescape:
5934 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005935 if (s+digits>end) {
5936 endinpos = size;
5937 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005938 errors, &errorHandler,
5939 "unicodeescape", "end of string in escape sequence",
5940 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005941 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005942 goto onError;
5943 goto nextByte;
5944 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005945 for (j = 0; j < digits; ++j) {
5946 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005947 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005948 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005949 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005950 errors, &errorHandler,
5951 "unicodeescape", message,
5952 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005953 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005954 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005955 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005956 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005957 }
5958 chr = (chr<<4) & ~0xF;
5959 if (c >= '0' && c <= '9')
5960 chr += c - '0';
5961 else if (c >= 'a' && c <= 'f')
5962 chr += 10 + c - 'a';
5963 else
5964 chr += 10 + c - 'A';
5965 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005966 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005967 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005968 /* _decoding_error will have already written into the
5969 target buffer. */
5970 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005971 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005972 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005973 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005974 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005975 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005976 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005977 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005978 errors, &errorHandler,
5979 "unicodeescape", "illegal Unicode character",
5980 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005981 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005982 goto onError;
5983 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005984 break;
5985
Benjamin Peterson29060642009-01-31 22:14:21 +00005986 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005987 case 'N':
5988 message = "malformed \\N character escape";
5989 if (ucnhash_CAPI == NULL) {
5990 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005991 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5992 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005993 if (ucnhash_CAPI == NULL)
5994 goto ucnhashError;
5995 }
5996 if (*s == '{') {
5997 const char *start = s+1;
5998 /* look for the closing brace */
5999 while (*s != '}' && s < end)
6000 s++;
6001 if (s > start && s < end && *s == '}') {
6002 /* found a name. look it up in the unicode database */
6003 message = "unknown Unicode character name";
6004 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006005 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03006006 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00006007 goto store;
6008 }
6009 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006010 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006011 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006012 errors, &errorHandler,
6013 "unicodeescape", message,
6014 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006015 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00006016 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006017 break;
6018
6019 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00006020 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006021 message = "\\ at end of string";
6022 s--;
6023 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006024 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006025 errors, &errorHandler,
6026 "unicodeescape", message,
6027 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006028 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00006029 goto onError;
6030 }
6031 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006032 WRITECHAR('\\');
6033 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00006034 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006035 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006036 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006037 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006038 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006040#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006041
Victor Stinner16e6a802011-12-12 13:24:15 +01006042 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006043 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006044 Py_XDECREF(errorHandler);
6045 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006046 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00006047
Benjamin Peterson29060642009-01-31 22:14:21 +00006048 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00006049 PyErr_SetString(
6050 PyExc_UnicodeError,
6051 "\\N escapes not supported (can't load unicodedata module)"
6052 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00006053 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006054 Py_XDECREF(errorHandler);
6055 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00006056 return NULL;
6057
Benjamin Peterson29060642009-01-31 22:14:21 +00006058 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006059 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006060 Py_XDECREF(errorHandler);
6061 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006062 return NULL;
6063}
6064
6065/* Return a Unicode-Escape string version of the Unicode object.
6066
6067 If quotes is true, the string is enclosed in u"" or u'' quotes as
6068 appropriate.
6069
6070*/
6071
Alexander Belopolsky40018472011-02-26 01:02:56 +00006072PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006073PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006074{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006075 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006076 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006077 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006078 int kind;
6079 void *data;
6080 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006081
Thomas Wouters89f507f2006-12-13 04:49:30 +00006082 /* Initial allocation is based on the longest-possible unichr
6083 escape.
6084
6085 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
6086 unichr, so in this case it's the longest unichr escape. In
6087 narrow (UTF-16) builds this is five chars per source unichr
6088 since there are two unichrs in the surrogate pair, so in narrow
6089 (UTF-16) builds it's not the longest unichr escape.
6090
6091 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
6092 so in the narrow (UTF-16) build case it's the longest unichr
6093 escape.
6094 */
6095
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006096 if (!PyUnicode_Check(unicode)) {
6097 PyErr_BadArgument();
6098 return NULL;
6099 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006100 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006101 return NULL;
6102 len = PyUnicode_GET_LENGTH(unicode);
6103 kind = PyUnicode_KIND(unicode);
6104 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06006105 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006106 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6107 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6108 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6109 }
6110
6111 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006112 return PyBytes_FromStringAndSize(NULL, 0);
6113
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006114 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006115 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006116
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006117 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00006118 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006119 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00006120 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006121 if (repr == NULL)
6122 return NULL;
6123
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006124 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006125
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006126 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006127 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006128
Walter Dörwald79e913e2007-05-12 11:08:06 +00006129 /* Escape backslashes */
6130 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006131 *p++ = '\\';
6132 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00006133 continue;
Tim Petersced69f82003-09-16 20:30:58 +00006134 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006135
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006136 /* Map 21-bit characters to '\U00xxxxxx' */
6137 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006138 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006139 *p++ = '\\';
6140 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006141 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
6142 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
6143 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6144 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6145 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6146 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6147 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6148 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006149 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006150 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006151
Guido van Rossumd57fd912000-03-10 22:53:23 +00006152 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006153 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006154 *p++ = '\\';
6155 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006156 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6157 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6158 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6159 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006160 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006161
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006162 /* Map special whitespace to '\t', \n', '\r' */
6163 else if (ch == '\t') {
6164 *p++ = '\\';
6165 *p++ = 't';
6166 }
6167 else if (ch == '\n') {
6168 *p++ = '\\';
6169 *p++ = 'n';
6170 }
6171 else if (ch == '\r') {
6172 *p++ = '\\';
6173 *p++ = 'r';
6174 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006175
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006176 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006177 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006178 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006179 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006180 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6181 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006182 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006183
Guido van Rossumd57fd912000-03-10 22:53:23 +00006184 /* Copy everything else as-is */
6185 else
6186 *p++ = (char) ch;
6187 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006188
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006189 assert(p - PyBytes_AS_STRING(repr) > 0);
6190 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6191 return NULL;
6192 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006193}
6194
Alexander Belopolsky40018472011-02-26 01:02:56 +00006195PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006196PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6197 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006198{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006199 PyObject *result;
6200 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6201 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006202 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006203 result = PyUnicode_AsUnicodeEscapeString(tmp);
6204 Py_DECREF(tmp);
6205 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006206}
6207
6208/* --- Raw Unicode Escape Codec ------------------------------------------- */
6209
Alexander Belopolsky40018472011-02-26 01:02:56 +00006210PyObject *
6211PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006212 Py_ssize_t size,
6213 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006214{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006215 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006216 Py_ssize_t startinpos;
6217 Py_ssize_t endinpos;
6218 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006219 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006220 const char *end;
6221 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006222 PyObject *errorHandler = NULL;
6223 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006224
Guido van Rossumd57fd912000-03-10 22:53:23 +00006225 /* Escaped strings will always be longer than the resulting
6226 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006227 length after conversion to the true value. (But decoding error
6228 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006229 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006230 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006231 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006232 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006233 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006234 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006235 end = s + size;
6236 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006237 unsigned char c;
6238 Py_UCS4 x;
6239 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006240 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006241
Benjamin Peterson29060642009-01-31 22:14:21 +00006242 /* Non-escape characters are interpreted as Unicode ordinals */
6243 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006244 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6245 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006246 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006247 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006248 startinpos = s-starts;
6249
6250 /* \u-escapes are only interpreted iff the number of leading
6251 backslashes if odd */
6252 bs = s;
6253 for (;s < end;) {
6254 if (*s != '\\')
6255 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006256 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6257 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006258 }
6259 if (((s - bs) & 1) == 0 ||
6260 s >= end ||
6261 (*s != 'u' && *s != 'U')) {
6262 continue;
6263 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006264 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006265 count = *s=='u' ? 4 : 8;
6266 s++;
6267
6268 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006269 for (x = 0, i = 0; i < count; ++i, ++s) {
6270 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006271 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006272 endinpos = s-starts;
6273 if (unicode_decode_call_errorhandler(
6274 errors, &errorHandler,
6275 "rawunicodeescape", "truncated \\uXXXX",
6276 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006277 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006278 goto onError;
6279 goto nextByte;
6280 }
6281 x = (x<<4) & ~0xF;
6282 if (c >= '0' && c <= '9')
6283 x += c - '0';
6284 else if (c >= 'a' && c <= 'f')
6285 x += 10 + c - 'a';
6286 else
6287 x += 10 + c - 'A';
6288 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006289 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006290 if (unicode_putchar(&v, &outpos, x) < 0)
6291 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006292 } else {
6293 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006294 if (unicode_decode_call_errorhandler(
6295 errors, &errorHandler,
6296 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006297 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006298 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006299 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006300 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006301 nextByte:
6302 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006303 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006304 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006305 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006306 Py_XDECREF(errorHandler);
6307 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006308 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006309
Benjamin Peterson29060642009-01-31 22:14:21 +00006310 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006311 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006312 Py_XDECREF(errorHandler);
6313 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006314 return NULL;
6315}
6316
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006317
Alexander Belopolsky40018472011-02-26 01:02:56 +00006318PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006319PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006320{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006321 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006322 char *p;
6323 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006324 Py_ssize_t expandsize, pos;
6325 int kind;
6326 void *data;
6327 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006328
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006329 if (!PyUnicode_Check(unicode)) {
6330 PyErr_BadArgument();
6331 return NULL;
6332 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006333 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006334 return NULL;
6335 kind = PyUnicode_KIND(unicode);
6336 data = PyUnicode_DATA(unicode);
6337 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006338 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6339 bytes, and 1 byte characters 4. */
6340 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006341
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006342 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006343 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006344
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006345 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006346 if (repr == NULL)
6347 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006348 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006349 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006350
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006351 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006352 for (pos = 0; pos < len; pos++) {
6353 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006354 /* Map 32-bit characters to '\Uxxxxxxxx' */
6355 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006356 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006357 *p++ = '\\';
6358 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006359 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6360 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6361 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6362 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6363 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6364 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6365 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6366 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006367 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006368 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006369 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006370 *p++ = '\\';
6371 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006372 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6373 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6374 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6375 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006376 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006377 /* Copy everything else as-is */
6378 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006379 *p++ = (char) ch;
6380 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006381
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006382 assert(p > q);
6383 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006384 return NULL;
6385 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006386}
6387
Alexander Belopolsky40018472011-02-26 01:02:56 +00006388PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006389PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6390 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006391{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006392 PyObject *result;
6393 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6394 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006395 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006396 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6397 Py_DECREF(tmp);
6398 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006399}
6400
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006401/* --- Unicode Internal Codec ------------------------------------------- */
6402
Alexander Belopolsky40018472011-02-26 01:02:56 +00006403PyObject *
6404_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006405 Py_ssize_t size,
6406 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006407{
6408 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006409 Py_ssize_t startinpos;
6410 Py_ssize_t endinpos;
6411 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006412 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006413 const char *end;
6414 const char *reason;
6415 PyObject *errorHandler = NULL;
6416 PyObject *exc = NULL;
6417
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006418 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006419 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006420 1))
6421 return NULL;
6422
Thomas Wouters89f507f2006-12-13 04:49:30 +00006423 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006424 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006425 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006426 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006427 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006428 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006429 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006430 end = s + size;
6431
6432 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006433 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006434 Py_UCS4 ch;
6435 /* We copy the raw representation one byte at a time because the
6436 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006437 ((char *) &uch)[0] = s[0];
6438 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006439#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006440 ((char *) &uch)[2] = s[2];
6441 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006442#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006443 ch = uch;
6444
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006445 /* We have to sanity check the raw data, otherwise doom looms for
6446 some malformed UCS-4 data. */
6447 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006448#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006449 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006450#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006451 end-s < Py_UNICODE_SIZE
6452 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006453 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006454 startinpos = s - starts;
6455 if (end-s < Py_UNICODE_SIZE) {
6456 endinpos = end-starts;
6457 reason = "truncated input";
6458 }
6459 else {
6460 endinpos = s - starts + Py_UNICODE_SIZE;
6461 reason = "illegal code point (> 0x10FFFF)";
6462 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006463 if (unicode_decode_call_errorhandler(
6464 errors, &errorHandler,
6465 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006466 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006467 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006468 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006469 continue;
6470 }
6471
6472 s += Py_UNICODE_SIZE;
6473#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006474 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006475 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006476 Py_UNICODE uch2;
6477 ((char *) &uch2)[0] = s[0];
6478 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006479 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006480 {
Victor Stinner551ac952011-11-29 22:58:13 +01006481 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006482 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006483 }
6484 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006485#endif
6486
6487 if (unicode_putchar(&v, &outpos, ch) < 0)
6488 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006489 }
6490
Victor Stinner16e6a802011-12-12 13:24:15 +01006491 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006492 goto onError;
6493 Py_XDECREF(errorHandler);
6494 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006495 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006496
Benjamin Peterson29060642009-01-31 22:14:21 +00006497 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006498 Py_XDECREF(v);
6499 Py_XDECREF(errorHandler);
6500 Py_XDECREF(exc);
6501 return NULL;
6502}
6503
Guido van Rossumd57fd912000-03-10 22:53:23 +00006504/* --- Latin-1 Codec ------------------------------------------------------ */
6505
Alexander Belopolsky40018472011-02-26 01:02:56 +00006506PyObject *
6507PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006508 Py_ssize_t size,
6509 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006510{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006511 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006512 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006513}
6514
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006515/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006516static void
6517make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006518 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006519 PyObject *unicode,
6520 Py_ssize_t startpos, Py_ssize_t endpos,
6521 const char *reason)
6522{
6523 if (*exceptionObject == NULL) {
6524 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006525 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006526 encoding, unicode, startpos, endpos, reason);
6527 }
6528 else {
6529 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6530 goto onError;
6531 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6532 goto onError;
6533 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6534 goto onError;
6535 return;
6536 onError:
6537 Py_DECREF(*exceptionObject);
6538 *exceptionObject = NULL;
6539 }
6540}
6541
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006542/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006543static void
6544raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006545 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006546 PyObject *unicode,
6547 Py_ssize_t startpos, Py_ssize_t endpos,
6548 const char *reason)
6549{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006550 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006551 encoding, unicode, startpos, endpos, reason);
6552 if (*exceptionObject != NULL)
6553 PyCodec_StrictErrors(*exceptionObject);
6554}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006555
6556/* error handling callback helper:
6557 build arguments, call the callback and check the arguments,
6558 put the result into newpos and return the replacement string, which
6559 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006560static PyObject *
6561unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006562 PyObject **errorHandler,
6563 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006564 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006565 Py_ssize_t startpos, Py_ssize_t endpos,
6566 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006567{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006568 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006569 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006570 PyObject *restuple;
6571 PyObject *resunicode;
6572
6573 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006574 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006575 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006576 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006577 }
6578
Benjamin Petersonbac79492012-01-14 13:34:47 -05006579 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006580 return NULL;
6581 len = PyUnicode_GET_LENGTH(unicode);
6582
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006583 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006584 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006585 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006586 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006587
6588 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006589 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006590 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006591 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006592 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006593 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006594 Py_DECREF(restuple);
6595 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006596 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006597 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006598 &resunicode, newpos)) {
6599 Py_DECREF(restuple);
6600 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006601 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006602 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6603 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6604 Py_DECREF(restuple);
6605 return NULL;
6606 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006607 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006608 *newpos = len + *newpos;
6609 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006610 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6611 Py_DECREF(restuple);
6612 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006613 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006614 Py_INCREF(resunicode);
6615 Py_DECREF(restuple);
6616 return resunicode;
6617}
6618
Alexander Belopolsky40018472011-02-26 01:02:56 +00006619static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006620unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006621 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006622 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006623{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006624 /* input state */
6625 Py_ssize_t pos=0, size;
6626 int kind;
6627 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006628 /* output object */
6629 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006630 /* pointer into the output */
6631 char *str;
6632 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006633 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006634 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6635 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006636 PyObject *errorHandler = NULL;
6637 PyObject *exc = NULL;
6638 /* the following variable is used for caching string comparisons
6639 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6640 int known_errorHandler = -1;
6641
Benjamin Petersonbac79492012-01-14 13:34:47 -05006642 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006643 return NULL;
6644 size = PyUnicode_GET_LENGTH(unicode);
6645 kind = PyUnicode_KIND(unicode);
6646 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006647 /* allocate enough for a simple encoding without
6648 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006649 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006650 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006651 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006652 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006653 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006654 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006655 ressize = size;
6656
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006657 while (pos < size) {
6658 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006659
Benjamin Peterson29060642009-01-31 22:14:21 +00006660 /* can we encode this? */
6661 if (c<limit) {
6662 /* no overflow check, because we know that the space is enough */
6663 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006664 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006665 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006666 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006667 Py_ssize_t requiredsize;
6668 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006669 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006670 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006671 Py_ssize_t collstart = pos;
6672 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006673 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006674 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006675 ++collend;
6676 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6677 if (known_errorHandler==-1) {
6678 if ((errors==NULL) || (!strcmp(errors, "strict")))
6679 known_errorHandler = 1;
6680 else if (!strcmp(errors, "replace"))
6681 known_errorHandler = 2;
6682 else if (!strcmp(errors, "ignore"))
6683 known_errorHandler = 3;
6684 else if (!strcmp(errors, "xmlcharrefreplace"))
6685 known_errorHandler = 4;
6686 else
6687 known_errorHandler = 0;
6688 }
6689 switch (known_errorHandler) {
6690 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006691 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006692 goto onError;
6693 case 2: /* replace */
6694 while (collstart++<collend)
6695 *str++ = '?'; /* fall through */
6696 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006697 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006698 break;
6699 case 4: /* xmlcharrefreplace */
6700 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006701 /* determine replacement size */
6702 for (i = collstart, repsize = 0; i < collend; ++i) {
6703 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6704 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006705 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006706 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006707 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006708 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006709 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006710 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006711 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006712 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006713 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006714 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006715 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006716 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006717 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006718 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006719 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006720 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006721 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006722 if (requiredsize > ressize) {
6723 if (requiredsize<2*ressize)
6724 requiredsize = 2*ressize;
6725 if (_PyBytes_Resize(&res, requiredsize))
6726 goto onError;
6727 str = PyBytes_AS_STRING(res) + respos;
6728 ressize = requiredsize;
6729 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006730 /* generate replacement */
6731 for (i = collstart; i < collend; ++i) {
6732 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006733 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006734 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006735 break;
6736 default:
6737 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006738 encoding, reason, unicode, &exc,
6739 collstart, collend, &newpos);
6740 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006741 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006742 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006743 if (PyBytes_Check(repunicode)) {
6744 /* Directly copy bytes result to output. */
6745 repsize = PyBytes_Size(repunicode);
6746 if (repsize > 1) {
6747 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006748 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006749 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6750 Py_DECREF(repunicode);
6751 goto onError;
6752 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006753 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006754 ressize += repsize-1;
6755 }
6756 memcpy(str, PyBytes_AsString(repunicode), repsize);
6757 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006758 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006759 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006760 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006761 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006762 /* need more space? (at least enough for what we
6763 have+the replacement+the rest of the string, so
6764 we won't have to check space for encodable characters) */
6765 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006766 repsize = PyUnicode_GET_LENGTH(repunicode);
6767 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006768 if (requiredsize > ressize) {
6769 if (requiredsize<2*ressize)
6770 requiredsize = 2*ressize;
6771 if (_PyBytes_Resize(&res, requiredsize)) {
6772 Py_DECREF(repunicode);
6773 goto onError;
6774 }
6775 str = PyBytes_AS_STRING(res) + respos;
6776 ressize = requiredsize;
6777 }
6778 /* check if there is anything unencodable in the replacement
6779 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006780 for (i = 0; repsize-->0; ++i, ++str) {
6781 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006782 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006783 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006784 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006785 Py_DECREF(repunicode);
6786 goto onError;
6787 }
6788 *str = (char)c;
6789 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006790 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006791 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006792 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006793 }
6794 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006795 /* Resize if we allocated to much */
6796 size = str - PyBytes_AS_STRING(res);
6797 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006798 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006799 if (_PyBytes_Resize(&res, size) < 0)
6800 goto onError;
6801 }
6802
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006803 Py_XDECREF(errorHandler);
6804 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006805 return res;
6806
6807 onError:
6808 Py_XDECREF(res);
6809 Py_XDECREF(errorHandler);
6810 Py_XDECREF(exc);
6811 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006812}
6813
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006814/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006815PyObject *
6816PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006817 Py_ssize_t size,
6818 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006819{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006820 PyObject *result;
6821 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6822 if (unicode == NULL)
6823 return NULL;
6824 result = unicode_encode_ucs1(unicode, errors, 256);
6825 Py_DECREF(unicode);
6826 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006827}
6828
Alexander Belopolsky40018472011-02-26 01:02:56 +00006829PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006830_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006831{
6832 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006833 PyErr_BadArgument();
6834 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006835 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006836 if (PyUnicode_READY(unicode) == -1)
6837 return NULL;
6838 /* Fast path: if it is a one-byte string, construct
6839 bytes object directly. */
6840 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6841 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6842 PyUnicode_GET_LENGTH(unicode));
6843 /* Non-Latin-1 characters present. Defer to above function to
6844 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006845 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006846}
6847
6848PyObject*
6849PyUnicode_AsLatin1String(PyObject *unicode)
6850{
6851 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006852}
6853
6854/* --- 7-bit ASCII Codec -------------------------------------------------- */
6855
Alexander Belopolsky40018472011-02-26 01:02:56 +00006856PyObject *
6857PyUnicode_DecodeASCII(const char *s,
6858 Py_ssize_t size,
6859 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006860{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006861 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006862 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006863 int kind;
6864 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006865 Py_ssize_t startinpos;
6866 Py_ssize_t endinpos;
6867 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006868 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006869 int has_error;
6870 const unsigned char *p = (const unsigned char *)s;
6871 const unsigned char *end = p + size;
6872 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006873 PyObject *errorHandler = NULL;
6874 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006875
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006876 if (size == 0) {
6877 Py_INCREF(unicode_empty);
6878 return unicode_empty;
6879 }
6880
Guido van Rossumd57fd912000-03-10 22:53:23 +00006881 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006882 if (size == 1 && (unsigned char)s[0] < 128)
6883 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006884
Victor Stinner702c7342011-10-05 13:50:52 +02006885 has_error = 0;
6886 while (p < end && !has_error) {
6887 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6888 an explanation. */
6889 if (!((size_t) p & LONG_PTR_MASK)) {
6890 /* Help register allocation */
6891 register const unsigned char *_p = p;
6892 while (_p < aligned_end) {
6893 unsigned long value = *(unsigned long *) _p;
6894 if (value & ASCII_CHAR_MASK) {
6895 has_error = 1;
6896 break;
6897 }
6898 _p += SIZEOF_LONG;
6899 }
6900 if (_p == end)
6901 break;
6902 if (has_error)
6903 break;
6904 p = _p;
6905 }
6906 if (*p & 0x80) {
6907 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006908 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006909 }
6910 else {
6911 ++p;
6912 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006913 }
Victor Stinner702c7342011-10-05 13:50:52 +02006914 if (!has_error)
6915 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006916
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006917 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006918 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006919 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006920 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006921 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006922 kind = PyUnicode_KIND(v);
6923 data = PyUnicode_DATA(v);
6924 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006925 e = s + size;
6926 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006927 register unsigned char c = (unsigned char)*s;
6928 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006929 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006930 ++s;
6931 }
6932 else {
6933 startinpos = s-starts;
6934 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006935 if (unicode_decode_call_errorhandler(
6936 errors, &errorHandler,
6937 "ascii", "ordinal not in range(128)",
6938 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006939 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006940 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006941 kind = PyUnicode_KIND(v);
6942 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006943 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006944 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006945 if (unicode_resize(&v, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006946 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006947 Py_XDECREF(errorHandler);
6948 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006949 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006950 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006951
Benjamin Peterson29060642009-01-31 22:14:21 +00006952 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006953 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006954 Py_XDECREF(errorHandler);
6955 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006956 return NULL;
6957}
6958
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006959/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006960PyObject *
6961PyUnicode_EncodeASCII(const Py_UNICODE *p,
6962 Py_ssize_t size,
6963 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006964{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006965 PyObject *result;
6966 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6967 if (unicode == NULL)
6968 return NULL;
6969 result = unicode_encode_ucs1(unicode, errors, 128);
6970 Py_DECREF(unicode);
6971 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006972}
6973
Alexander Belopolsky40018472011-02-26 01:02:56 +00006974PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006975_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006976{
6977 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006978 PyErr_BadArgument();
6979 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006980 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006981 if (PyUnicode_READY(unicode) == -1)
6982 return NULL;
6983 /* Fast path: if it is an ASCII-only string, construct bytes object
6984 directly. Else defer to above function to raise the exception. */
6985 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6986 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6987 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006988 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006989}
6990
6991PyObject *
6992PyUnicode_AsASCIIString(PyObject *unicode)
6993{
6994 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006995}
6996
Victor Stinner99b95382011-07-04 14:23:54 +02006997#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006998
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006999/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007000
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007001#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007002#define NEED_RETRY
7003#endif
7004
Victor Stinner3a50e702011-10-18 21:21:00 +02007005#ifndef WC_ERR_INVALID_CHARS
7006# define WC_ERR_INVALID_CHARS 0x0080
7007#endif
7008
7009static char*
7010code_page_name(UINT code_page, PyObject **obj)
7011{
7012 *obj = NULL;
7013 if (code_page == CP_ACP)
7014 return "mbcs";
7015 if (code_page == CP_UTF7)
7016 return "CP_UTF7";
7017 if (code_page == CP_UTF8)
7018 return "CP_UTF8";
7019
7020 *obj = PyBytes_FromFormat("cp%u", code_page);
7021 if (*obj == NULL)
7022 return NULL;
7023 return PyBytes_AS_STRING(*obj);
7024}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007025
Alexander Belopolsky40018472011-02-26 01:02:56 +00007026static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007027is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007028{
7029 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02007030 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007031
Victor Stinner3a50e702011-10-18 21:21:00 +02007032 if (!IsDBCSLeadByteEx(code_page, *curr))
7033 return 0;
7034
7035 prev = CharPrevExA(code_page, s, curr, 0);
7036 if (prev == curr)
7037 return 1;
7038 /* FIXME: This code is limited to "true" double-byte encodings,
7039 as it assumes an incomplete character consists of a single
7040 byte. */
7041 if (curr - prev == 2)
7042 return 1;
7043 if (!IsDBCSLeadByteEx(code_page, *prev))
7044 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007045 return 0;
7046}
7047
Victor Stinner3a50e702011-10-18 21:21:00 +02007048static DWORD
7049decode_code_page_flags(UINT code_page)
7050{
7051 if (code_page == CP_UTF7) {
7052 /* The CP_UTF7 decoder only supports flags=0 */
7053 return 0;
7054 }
7055 else
7056 return MB_ERR_INVALID_CHARS;
7057}
7058
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007059/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007060 * Decode a byte string from a Windows code page into unicode object in strict
7061 * mode.
7062 *
7063 * Returns consumed size if succeed, returns -2 on decode error, or raise a
7064 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007065 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007066static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007067decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007068 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007069 const char *in,
7070 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007071{
Victor Stinner3a50e702011-10-18 21:21:00 +02007072 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007073 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007074 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007075
7076 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007077 assert(insize > 0);
7078 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7079 if (outsize <= 0)
7080 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081
7082 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007083 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007084 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007085 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007086 if (*v == NULL)
7087 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007088 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007089 }
7090 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007091 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007092 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007093 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007094 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007095 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007096 }
7097
7098 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007099 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7100 if (outsize <= 0)
7101 goto error;
7102 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007103
Victor Stinner3a50e702011-10-18 21:21:00 +02007104error:
7105 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7106 return -2;
7107 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007108 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007109}
7110
Victor Stinner3a50e702011-10-18 21:21:00 +02007111/*
7112 * Decode a byte string from a code page into unicode object with an error
7113 * handler.
7114 *
7115 * Returns consumed size if succeed, or raise a WindowsError or
7116 * UnicodeDecodeError exception and returns -1 on error.
7117 */
7118static int
7119decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007120 PyObject **v,
7121 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007122 const char *errors)
7123{
7124 const char *startin = in;
7125 const char *endin = in + size;
7126 const DWORD flags = decode_code_page_flags(code_page);
7127 /* Ideally, we should get reason from FormatMessage. This is the Windows
7128 2000 English version of the message. */
7129 const char *reason = "No mapping for the Unicode character exists "
7130 "in the target code page.";
7131 /* each step cannot decode more than 1 character, but a character can be
7132 represented as a surrogate pair */
7133 wchar_t buffer[2], *startout, *out;
7134 int insize, outsize;
7135 PyObject *errorHandler = NULL;
7136 PyObject *exc = NULL;
7137 PyObject *encoding_obj = NULL;
7138 char *encoding;
7139 DWORD err;
7140 int ret = -1;
7141
7142 assert(size > 0);
7143
7144 encoding = code_page_name(code_page, &encoding_obj);
7145 if (encoding == NULL)
7146 return -1;
7147
7148 if (errors == NULL || strcmp(errors, "strict") == 0) {
7149 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7150 UnicodeDecodeError. */
7151 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7152 if (exc != NULL) {
7153 PyCodec_StrictErrors(exc);
7154 Py_CLEAR(exc);
7155 }
7156 goto error;
7157 }
7158
7159 if (*v == NULL) {
7160 /* Create unicode object */
7161 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7162 PyErr_NoMemory();
7163 goto error;
7164 }
Victor Stinnerab595942011-12-17 04:59:06 +01007165 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007166 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007167 if (*v == NULL)
7168 goto error;
7169 startout = PyUnicode_AS_UNICODE(*v);
7170 }
7171 else {
7172 /* Extend unicode object */
7173 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7174 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7175 PyErr_NoMemory();
7176 goto error;
7177 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007178 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007179 goto error;
7180 startout = PyUnicode_AS_UNICODE(*v) + n;
7181 }
7182
7183 /* Decode the byte string character per character */
7184 out = startout;
7185 while (in < endin)
7186 {
7187 /* Decode a character */
7188 insize = 1;
7189 do
7190 {
7191 outsize = MultiByteToWideChar(code_page, flags,
7192 in, insize,
7193 buffer, Py_ARRAY_LENGTH(buffer));
7194 if (outsize > 0)
7195 break;
7196 err = GetLastError();
7197 if (err != ERROR_NO_UNICODE_TRANSLATION
7198 && err != ERROR_INSUFFICIENT_BUFFER)
7199 {
7200 PyErr_SetFromWindowsErr(0);
7201 goto error;
7202 }
7203 insize++;
7204 }
7205 /* 4=maximum length of a UTF-8 sequence */
7206 while (insize <= 4 && (in + insize) <= endin);
7207
7208 if (outsize <= 0) {
7209 Py_ssize_t startinpos, endinpos, outpos;
7210
7211 startinpos = in - startin;
7212 endinpos = startinpos + 1;
7213 outpos = out - PyUnicode_AS_UNICODE(*v);
7214 if (unicode_decode_call_errorhandler(
7215 errors, &errorHandler,
7216 encoding, reason,
7217 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007218 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 {
7220 goto error;
7221 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007222 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007223 }
7224 else {
7225 in += insize;
7226 memcpy(out, buffer, outsize * sizeof(wchar_t));
7227 out += outsize;
7228 }
7229 }
7230
7231 /* write a NUL character at the end */
7232 *out = 0;
7233
7234 /* Extend unicode object */
7235 outsize = out - startout;
7236 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007237 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007238 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007239 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007240
7241error:
7242 Py_XDECREF(encoding_obj);
7243 Py_XDECREF(errorHandler);
7244 Py_XDECREF(exc);
7245 return ret;
7246}
7247
Victor Stinner3a50e702011-10-18 21:21:00 +02007248static PyObject *
7249decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007250 const char *s, Py_ssize_t size,
7251 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007252{
Victor Stinner76a31a62011-11-04 00:05:13 +01007253 PyObject *v = NULL;
7254 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007255
Victor Stinner3a50e702011-10-18 21:21:00 +02007256 if (code_page < 0) {
7257 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7258 return NULL;
7259 }
7260
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007261 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007262 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007263
Victor Stinner76a31a62011-11-04 00:05:13 +01007264 do
7265 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007266#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007267 if (size > INT_MAX) {
7268 chunk_size = INT_MAX;
7269 final = 0;
7270 done = 0;
7271 }
7272 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007273#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007274 {
7275 chunk_size = (int)size;
7276 final = (consumed == NULL);
7277 done = 1;
7278 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007279
Victor Stinner76a31a62011-11-04 00:05:13 +01007280 /* Skip trailing lead-byte unless 'final' is set */
7281 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7282 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007283
Victor Stinner76a31a62011-11-04 00:05:13 +01007284 if (chunk_size == 0 && done) {
7285 if (v != NULL)
7286 break;
7287 Py_INCREF(unicode_empty);
7288 return unicode_empty;
7289 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007290
Victor Stinner76a31a62011-11-04 00:05:13 +01007291
7292 converted = decode_code_page_strict(code_page, &v,
7293 s, chunk_size);
7294 if (converted == -2)
7295 converted = decode_code_page_errors(code_page, &v,
7296 s, chunk_size,
7297 errors);
7298 assert(converted != 0);
7299
7300 if (converted < 0) {
7301 Py_XDECREF(v);
7302 return NULL;
7303 }
7304
7305 if (consumed)
7306 *consumed += converted;
7307
7308 s += converted;
7309 size -= converted;
7310 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007311
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007312 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007313}
7314
Alexander Belopolsky40018472011-02-26 01:02:56 +00007315PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007316PyUnicode_DecodeCodePageStateful(int code_page,
7317 const char *s,
7318 Py_ssize_t size,
7319 const char *errors,
7320 Py_ssize_t *consumed)
7321{
7322 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7323}
7324
7325PyObject *
7326PyUnicode_DecodeMBCSStateful(const char *s,
7327 Py_ssize_t size,
7328 const char *errors,
7329 Py_ssize_t *consumed)
7330{
7331 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7332}
7333
7334PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007335PyUnicode_DecodeMBCS(const char *s,
7336 Py_ssize_t size,
7337 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007338{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007339 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7340}
7341
Victor Stinner3a50e702011-10-18 21:21:00 +02007342static DWORD
7343encode_code_page_flags(UINT code_page, const char *errors)
7344{
7345 if (code_page == CP_UTF8) {
7346 if (winver.dwMajorVersion >= 6)
7347 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7348 and later */
7349 return WC_ERR_INVALID_CHARS;
7350 else
7351 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7352 return 0;
7353 }
7354 else if (code_page == CP_UTF7) {
7355 /* CP_UTF7 only supports flags=0 */
7356 return 0;
7357 }
7358 else {
7359 if (errors != NULL && strcmp(errors, "replace") == 0)
7360 return 0;
7361 else
7362 return WC_NO_BEST_FIT_CHARS;
7363 }
7364}
7365
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007366/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007367 * Encode a Unicode string to a Windows code page into a byte string in strict
7368 * mode.
7369 *
7370 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7371 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007372 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007373static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007374encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007375 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007376 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007377{
Victor Stinner554f3f02010-06-16 23:33:54 +00007378 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007379 BOOL *pusedDefaultChar = &usedDefaultChar;
7380 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007381 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007382 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007383 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007384 const DWORD flags = encode_code_page_flags(code_page, NULL);
7385 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007386 /* Create a substring so that we can get the UTF-16 representation
7387 of just the slice under consideration. */
7388 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007389
Martin v. Löwis3d325192011-11-04 18:23:06 +01007390 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007391
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007393 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007394 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007395 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007396
Victor Stinner2fc507f2011-11-04 20:06:39 +01007397 substring = PyUnicode_Substring(unicode, offset, offset+len);
7398 if (substring == NULL)
7399 return -1;
7400 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7401 if (p == NULL) {
7402 Py_DECREF(substring);
7403 return -1;
7404 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007405
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007406 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007407 outsize = WideCharToMultiByte(code_page, flags,
7408 p, size,
7409 NULL, 0,
7410 NULL, pusedDefaultChar);
7411 if (outsize <= 0)
7412 goto error;
7413 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007414 if (pusedDefaultChar && *pusedDefaultChar) {
7415 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007416 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007417 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007418
Victor Stinner3a50e702011-10-18 21:21:00 +02007419 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007420 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007421 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007422 if (*outbytes == NULL) {
7423 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007424 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007425 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007426 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007427 }
7428 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007429 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007430 const Py_ssize_t n = PyBytes_Size(*outbytes);
7431 if (outsize > PY_SSIZE_T_MAX - n) {
7432 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007433 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007434 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007435 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007436 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7437 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007438 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007439 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007440 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007441 }
7442
7443 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007444 outsize = WideCharToMultiByte(code_page, flags,
7445 p, size,
7446 out, outsize,
7447 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007448 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007449 if (outsize <= 0)
7450 goto error;
7451 if (pusedDefaultChar && *pusedDefaultChar)
7452 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007453 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007454
Victor Stinner3a50e702011-10-18 21:21:00 +02007455error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007456 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007457 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7458 return -2;
7459 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007460 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007461}
7462
Victor Stinner3a50e702011-10-18 21:21:00 +02007463/*
7464 * Encode a Unicode string to a Windows code page into a byte string using a
7465 * error handler.
7466 *
7467 * Returns consumed characters if succeed, or raise a WindowsError and returns
7468 * -1 on other error.
7469 */
7470static int
7471encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007472 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007473 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007474{
Victor Stinner3a50e702011-10-18 21:21:00 +02007475 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007476 Py_ssize_t pos = unicode_offset;
7477 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007478 /* Ideally, we should get reason from FormatMessage. This is the Windows
7479 2000 English version of the message. */
7480 const char *reason = "invalid character";
7481 /* 4=maximum length of a UTF-8 sequence */
7482 char buffer[4];
7483 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7484 Py_ssize_t outsize;
7485 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007486 PyObject *errorHandler = NULL;
7487 PyObject *exc = NULL;
7488 PyObject *encoding_obj = NULL;
7489 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007490 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007491 PyObject *rep;
7492 int ret = -1;
7493
7494 assert(insize > 0);
7495
7496 encoding = code_page_name(code_page, &encoding_obj);
7497 if (encoding == NULL)
7498 return -1;
7499
7500 if (errors == NULL || strcmp(errors, "strict") == 0) {
7501 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7502 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007503 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007504 if (exc != NULL) {
7505 PyCodec_StrictErrors(exc);
7506 Py_DECREF(exc);
7507 }
7508 Py_XDECREF(encoding_obj);
7509 return -1;
7510 }
7511
7512 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7513 pusedDefaultChar = &usedDefaultChar;
7514 else
7515 pusedDefaultChar = NULL;
7516
7517 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7518 PyErr_NoMemory();
7519 goto error;
7520 }
7521 outsize = insize * Py_ARRAY_LENGTH(buffer);
7522
7523 if (*outbytes == NULL) {
7524 /* Create string object */
7525 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7526 if (*outbytes == NULL)
7527 goto error;
7528 out = PyBytes_AS_STRING(*outbytes);
7529 }
7530 else {
7531 /* Extend string object */
7532 Py_ssize_t n = PyBytes_Size(*outbytes);
7533 if (n > PY_SSIZE_T_MAX - outsize) {
7534 PyErr_NoMemory();
7535 goto error;
7536 }
7537 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7538 goto error;
7539 out = PyBytes_AS_STRING(*outbytes) + n;
7540 }
7541
7542 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007543 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007544 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007545 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7546 wchar_t chars[2];
7547 int charsize;
7548 if (ch < 0x10000) {
7549 chars[0] = (wchar_t)ch;
7550 charsize = 1;
7551 }
7552 else {
7553 ch -= 0x10000;
7554 chars[0] = 0xd800 + (ch >> 10);
7555 chars[1] = 0xdc00 + (ch & 0x3ff);
7556 charsize = 2;
7557 }
7558
Victor Stinner3a50e702011-10-18 21:21:00 +02007559 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007560 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007561 buffer, Py_ARRAY_LENGTH(buffer),
7562 NULL, pusedDefaultChar);
7563 if (outsize > 0) {
7564 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7565 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007566 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007567 memcpy(out, buffer, outsize);
7568 out += outsize;
7569 continue;
7570 }
7571 }
7572 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7573 PyErr_SetFromWindowsErr(0);
7574 goto error;
7575 }
7576
Victor Stinner3a50e702011-10-18 21:21:00 +02007577 rep = unicode_encode_call_errorhandler(
7578 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007579 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007580 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007581 if (rep == NULL)
7582 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007583 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007584
7585 if (PyBytes_Check(rep)) {
7586 outsize = PyBytes_GET_SIZE(rep);
7587 if (outsize != 1) {
7588 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7589 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7590 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7591 Py_DECREF(rep);
7592 goto error;
7593 }
7594 out = PyBytes_AS_STRING(*outbytes) + offset;
7595 }
7596 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7597 out += outsize;
7598 }
7599 else {
7600 Py_ssize_t i;
7601 enum PyUnicode_Kind kind;
7602 void *data;
7603
Benjamin Petersonbac79492012-01-14 13:34:47 -05007604 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007605 Py_DECREF(rep);
7606 goto error;
7607 }
7608
7609 outsize = PyUnicode_GET_LENGTH(rep);
7610 if (outsize != 1) {
7611 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7612 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7613 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7614 Py_DECREF(rep);
7615 goto error;
7616 }
7617 out = PyBytes_AS_STRING(*outbytes) + offset;
7618 }
7619 kind = PyUnicode_KIND(rep);
7620 data = PyUnicode_DATA(rep);
7621 for (i=0; i < outsize; i++) {
7622 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7623 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007624 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007625 encoding, unicode,
7626 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007627 "unable to encode error handler result to ASCII");
7628 Py_DECREF(rep);
7629 goto error;
7630 }
7631 *out = (unsigned char)ch;
7632 out++;
7633 }
7634 }
7635 Py_DECREF(rep);
7636 }
7637 /* write a NUL byte */
7638 *out = 0;
7639 outsize = out - PyBytes_AS_STRING(*outbytes);
7640 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7641 if (_PyBytes_Resize(outbytes, outsize) < 0)
7642 goto error;
7643 ret = 0;
7644
7645error:
7646 Py_XDECREF(encoding_obj);
7647 Py_XDECREF(errorHandler);
7648 Py_XDECREF(exc);
7649 return ret;
7650}
7651
Victor Stinner3a50e702011-10-18 21:21:00 +02007652static PyObject *
7653encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007654 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007655 const char *errors)
7656{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007657 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007658 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007659 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007660 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007661
Benjamin Petersonbac79492012-01-14 13:34:47 -05007662 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007663 return NULL;
7664 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007665
Victor Stinner3a50e702011-10-18 21:21:00 +02007666 if (code_page < 0) {
7667 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7668 return NULL;
7669 }
7670
Martin v. Löwis3d325192011-11-04 18:23:06 +01007671 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007672 return PyBytes_FromStringAndSize(NULL, 0);
7673
Victor Stinner7581cef2011-11-03 22:32:33 +01007674 offset = 0;
7675 do
7676 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007677#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007678 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007679 chunks. */
7680 if (len > INT_MAX/2) {
7681 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007682 done = 0;
7683 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007684 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007685#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007686 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007687 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007688 done = 1;
7689 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007690
Victor Stinner76a31a62011-11-04 00:05:13 +01007691 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007692 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007693 errors);
7694 if (ret == -2)
7695 ret = encode_code_page_errors(code_page, &outbytes,
7696 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007697 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007698 if (ret < 0) {
7699 Py_XDECREF(outbytes);
7700 return NULL;
7701 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007702
Victor Stinner7581cef2011-11-03 22:32:33 +01007703 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007704 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007705 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007706
Victor Stinner3a50e702011-10-18 21:21:00 +02007707 return outbytes;
7708}
7709
7710PyObject *
7711PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7712 Py_ssize_t size,
7713 const char *errors)
7714{
Victor Stinner7581cef2011-11-03 22:32:33 +01007715 PyObject *unicode, *res;
7716 unicode = PyUnicode_FromUnicode(p, size);
7717 if (unicode == NULL)
7718 return NULL;
7719 res = encode_code_page(CP_ACP, unicode, errors);
7720 Py_DECREF(unicode);
7721 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007722}
7723
7724PyObject *
7725PyUnicode_EncodeCodePage(int code_page,
7726 PyObject *unicode,
7727 const char *errors)
7728{
Victor Stinner7581cef2011-11-03 22:32:33 +01007729 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007730}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007731
Alexander Belopolsky40018472011-02-26 01:02:56 +00007732PyObject *
7733PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007734{
7735 if (!PyUnicode_Check(unicode)) {
7736 PyErr_BadArgument();
7737 return NULL;
7738 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007739 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007740}
7741
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007742#undef NEED_RETRY
7743
Victor Stinner99b95382011-07-04 14:23:54 +02007744#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007745
Guido van Rossumd57fd912000-03-10 22:53:23 +00007746/* --- Character Mapping Codec -------------------------------------------- */
7747
Alexander Belopolsky40018472011-02-26 01:02:56 +00007748PyObject *
7749PyUnicode_DecodeCharmap(const char *s,
7750 Py_ssize_t size,
7751 PyObject *mapping,
7752 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007753{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007754 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007755 Py_ssize_t startinpos;
7756 Py_ssize_t endinpos;
7757 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007758 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007759 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007760 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007761 PyObject *errorHandler = NULL;
7762 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007763
Guido van Rossumd57fd912000-03-10 22:53:23 +00007764 /* Default to Latin-1 */
7765 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007766 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007767
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007768 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007769 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007770 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007771 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007772 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007773 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007774 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007775 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007776 Py_ssize_t maplen;
7777 enum PyUnicode_Kind kind;
7778 void *data;
7779 Py_UCS4 x;
7780
Benjamin Petersonbac79492012-01-14 13:34:47 -05007781 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007782 return NULL;
7783
7784 maplen = PyUnicode_GET_LENGTH(mapping);
7785 data = PyUnicode_DATA(mapping);
7786 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007787 while (s < e) {
7788 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007789
Benjamin Peterson29060642009-01-31 22:14:21 +00007790 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007791 x = PyUnicode_READ(kind, data, ch);
7792 else
7793 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007794
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007795 if (x == 0xfffe)
7796 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007797 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007798 startinpos = s-starts;
7799 endinpos = startinpos+1;
7800 if (unicode_decode_call_errorhandler(
7801 errors, &errorHandler,
7802 "charmap", "character maps to <undefined>",
7803 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007804 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007805 goto onError;
7806 }
7807 continue;
7808 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007809
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007810 if (unicode_putchar(&v, &outpos, x) < 0)
7811 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007812 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007813 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007814 }
7815 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007816 while (s < e) {
7817 unsigned char ch = *s;
7818 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007819
Benjamin Peterson29060642009-01-31 22:14:21 +00007820 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7821 w = PyLong_FromLong((long)ch);
7822 if (w == NULL)
7823 goto onError;
7824 x = PyObject_GetItem(mapping, w);
7825 Py_DECREF(w);
7826 if (x == NULL) {
7827 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7828 /* No mapping found means: mapping is undefined. */
7829 PyErr_Clear();
7830 x = Py_None;
7831 Py_INCREF(x);
7832 } else
7833 goto onError;
7834 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007835
Benjamin Peterson29060642009-01-31 22:14:21 +00007836 /* Apply mapping */
7837 if (PyLong_Check(x)) {
7838 long value = PyLong_AS_LONG(x);
7839 if (value < 0 || value > 65535) {
7840 PyErr_SetString(PyExc_TypeError,
7841 "character mapping must be in range(65536)");
7842 Py_DECREF(x);
7843 goto onError;
7844 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007845 if (unicode_putchar(&v, &outpos, value) < 0)
7846 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007847 }
7848 else if (x == Py_None) {
7849 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007850 startinpos = s-starts;
7851 endinpos = startinpos+1;
7852 if (unicode_decode_call_errorhandler(
7853 errors, &errorHandler,
7854 "charmap", "character maps to <undefined>",
7855 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007856 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007857 Py_DECREF(x);
7858 goto onError;
7859 }
7860 Py_DECREF(x);
7861 continue;
7862 }
7863 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007864 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007865
Benjamin Petersonbac79492012-01-14 13:34:47 -05007866 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007867 goto onError;
7868 targetsize = PyUnicode_GET_LENGTH(x);
7869
7870 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007871 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007872 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007873 PyUnicode_READ_CHAR(x, 0)) < 0)
7874 goto onError;
7875 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007876 else if (targetsize > 1) {
7877 /* 1-n mapping */
7878 if (targetsize > extrachars) {
7879 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007880 Py_ssize_t needed = (targetsize - extrachars) + \
7881 (targetsize << 2);
7882 extrachars += needed;
7883 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007884 if (unicode_resize(&v,
7885 PyUnicode_GET_LENGTH(v) + needed) < 0)
7886 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007887 Py_DECREF(x);
7888 goto onError;
7889 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007890 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007891 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7892 goto onError;
7893 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7894 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007895 extrachars -= targetsize;
7896 }
7897 /* 1-0 mapping: skip the character */
7898 }
7899 else {
7900 /* wrong return value */
7901 PyErr_SetString(PyExc_TypeError,
7902 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007903 Py_DECREF(x);
7904 goto onError;
7905 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007906 Py_DECREF(x);
7907 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007908 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007909 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007910 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007911 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007912 Py_XDECREF(errorHandler);
7913 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007914 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007915
Benjamin Peterson29060642009-01-31 22:14:21 +00007916 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007917 Py_XDECREF(errorHandler);
7918 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007919 Py_XDECREF(v);
7920 return NULL;
7921}
7922
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007923/* Charmap encoding: the lookup table */
7924
Alexander Belopolsky40018472011-02-26 01:02:56 +00007925struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007926 PyObject_HEAD
7927 unsigned char level1[32];
7928 int count2, count3;
7929 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007930};
7931
7932static PyObject*
7933encoding_map_size(PyObject *obj, PyObject* args)
7934{
7935 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007936 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007937 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007938}
7939
7940static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007941 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007942 PyDoc_STR("Return the size (in bytes) of this object") },
7943 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007944};
7945
7946static void
7947encoding_map_dealloc(PyObject* o)
7948{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007949 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007950}
7951
7952static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007953 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007954 "EncodingMap", /*tp_name*/
7955 sizeof(struct encoding_map), /*tp_basicsize*/
7956 0, /*tp_itemsize*/
7957 /* methods */
7958 encoding_map_dealloc, /*tp_dealloc*/
7959 0, /*tp_print*/
7960 0, /*tp_getattr*/
7961 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007962 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007963 0, /*tp_repr*/
7964 0, /*tp_as_number*/
7965 0, /*tp_as_sequence*/
7966 0, /*tp_as_mapping*/
7967 0, /*tp_hash*/
7968 0, /*tp_call*/
7969 0, /*tp_str*/
7970 0, /*tp_getattro*/
7971 0, /*tp_setattro*/
7972 0, /*tp_as_buffer*/
7973 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7974 0, /*tp_doc*/
7975 0, /*tp_traverse*/
7976 0, /*tp_clear*/
7977 0, /*tp_richcompare*/
7978 0, /*tp_weaklistoffset*/
7979 0, /*tp_iter*/
7980 0, /*tp_iternext*/
7981 encoding_map_methods, /*tp_methods*/
7982 0, /*tp_members*/
7983 0, /*tp_getset*/
7984 0, /*tp_base*/
7985 0, /*tp_dict*/
7986 0, /*tp_descr_get*/
7987 0, /*tp_descr_set*/
7988 0, /*tp_dictoffset*/
7989 0, /*tp_init*/
7990 0, /*tp_alloc*/
7991 0, /*tp_new*/
7992 0, /*tp_free*/
7993 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007994};
7995
7996PyObject*
7997PyUnicode_BuildEncodingMap(PyObject* string)
7998{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007999 PyObject *result;
8000 struct encoding_map *mresult;
8001 int i;
8002 int need_dict = 0;
8003 unsigned char level1[32];
8004 unsigned char level2[512];
8005 unsigned char *mlevel1, *mlevel2, *mlevel3;
8006 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008007 int kind;
8008 void *data;
8009 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008011 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008012 PyErr_BadArgument();
8013 return NULL;
8014 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008015 kind = PyUnicode_KIND(string);
8016 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008017 memset(level1, 0xFF, sizeof level1);
8018 memset(level2, 0xFF, sizeof level2);
8019
8020 /* If there isn't a one-to-one mapping of NULL to \0,
8021 or if there are non-BMP characters, we need to use
8022 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008023 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008024 need_dict = 1;
8025 for (i = 1; i < 256; i++) {
8026 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008027 ch = PyUnicode_READ(kind, data, i);
8028 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008029 need_dict = 1;
8030 break;
8031 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008032 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008033 /* unmapped character */
8034 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008035 l1 = ch >> 11;
8036 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008037 if (level1[l1] == 0xFF)
8038 level1[l1] = count2++;
8039 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008040 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008041 }
8042
8043 if (count2 >= 0xFF || count3 >= 0xFF)
8044 need_dict = 1;
8045
8046 if (need_dict) {
8047 PyObject *result = PyDict_New();
8048 PyObject *key, *value;
8049 if (!result)
8050 return NULL;
8051 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008052 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008053 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008054 if (!key || !value)
8055 goto failed1;
8056 if (PyDict_SetItem(result, key, value) == -1)
8057 goto failed1;
8058 Py_DECREF(key);
8059 Py_DECREF(value);
8060 }
8061 return result;
8062 failed1:
8063 Py_XDECREF(key);
8064 Py_XDECREF(value);
8065 Py_DECREF(result);
8066 return NULL;
8067 }
8068
8069 /* Create a three-level trie */
8070 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8071 16*count2 + 128*count3 - 1);
8072 if (!result)
8073 return PyErr_NoMemory();
8074 PyObject_Init(result, &EncodingMapType);
8075 mresult = (struct encoding_map*)result;
8076 mresult->count2 = count2;
8077 mresult->count3 = count3;
8078 mlevel1 = mresult->level1;
8079 mlevel2 = mresult->level23;
8080 mlevel3 = mresult->level23 + 16*count2;
8081 memcpy(mlevel1, level1, 32);
8082 memset(mlevel2, 0xFF, 16*count2);
8083 memset(mlevel3, 0, 128*count3);
8084 count3 = 0;
8085 for (i = 1; i < 256; i++) {
8086 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008087 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008088 /* unmapped character */
8089 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008090 o1 = PyUnicode_READ(kind, data, i)>>11;
8091 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008092 i2 = 16*mlevel1[o1] + o2;
8093 if (mlevel2[i2] == 0xFF)
8094 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008095 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008096 i3 = 128*mlevel2[i2] + o3;
8097 mlevel3[i3] = i;
8098 }
8099 return result;
8100}
8101
8102static int
Victor Stinner22168992011-11-20 17:09:18 +01008103encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008104{
8105 struct encoding_map *map = (struct encoding_map*)mapping;
8106 int l1 = c>>11;
8107 int l2 = (c>>7) & 0xF;
8108 int l3 = c & 0x7F;
8109 int i;
8110
Victor Stinner22168992011-11-20 17:09:18 +01008111 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008112 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008113 if (c == 0)
8114 return 0;
8115 /* level 1*/
8116 i = map->level1[l1];
8117 if (i == 0xFF) {
8118 return -1;
8119 }
8120 /* level 2*/
8121 i = map->level23[16*i+l2];
8122 if (i == 0xFF) {
8123 return -1;
8124 }
8125 /* level 3 */
8126 i = map->level23[16*map->count2 + 128*i + l3];
8127 if (i == 0) {
8128 return -1;
8129 }
8130 return i;
8131}
8132
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008133/* Lookup the character ch in the mapping. If the character
8134 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008135 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008136static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008137charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008138{
Christian Heimes217cfd12007-12-02 14:31:20 +00008139 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008140 PyObject *x;
8141
8142 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008143 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008144 x = PyObject_GetItem(mapping, w);
8145 Py_DECREF(w);
8146 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008147 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8148 /* No mapping found means: mapping is undefined. */
8149 PyErr_Clear();
8150 x = Py_None;
8151 Py_INCREF(x);
8152 return x;
8153 } else
8154 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008155 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008156 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008157 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008158 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008159 long value = PyLong_AS_LONG(x);
8160 if (value < 0 || value > 255) {
8161 PyErr_SetString(PyExc_TypeError,
8162 "character mapping must be in range(256)");
8163 Py_DECREF(x);
8164 return NULL;
8165 }
8166 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008167 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008168 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008169 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008170 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008171 /* wrong return value */
8172 PyErr_Format(PyExc_TypeError,
8173 "character mapping must return integer, bytes or None, not %.400s",
8174 x->ob_type->tp_name);
8175 Py_DECREF(x);
8176 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008177 }
8178}
8179
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008180static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008181charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008182{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008183 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8184 /* exponentially overallocate to minimize reallocations */
8185 if (requiredsize < 2*outsize)
8186 requiredsize = 2*outsize;
8187 if (_PyBytes_Resize(outobj, requiredsize))
8188 return -1;
8189 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008190}
8191
Benjamin Peterson14339b62009-01-31 16:36:08 +00008192typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008193 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008194} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008195/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008196 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008197 space is available. Return a new reference to the object that
8198 was put in the output buffer, or Py_None, if the mapping was undefined
8199 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008200 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008201static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008202charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008203 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008204{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008205 PyObject *rep;
8206 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008207 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008208
Christian Heimes90aa7642007-12-19 02:45:37 +00008209 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008210 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008211 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008212 if (res == -1)
8213 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008214 if (outsize<requiredsize)
8215 if (charmapencode_resize(outobj, outpos, requiredsize))
8216 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008217 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008218 outstart[(*outpos)++] = (char)res;
8219 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008220 }
8221
8222 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008223 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008224 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008225 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008226 Py_DECREF(rep);
8227 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008228 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008229 if (PyLong_Check(rep)) {
8230 Py_ssize_t requiredsize = *outpos+1;
8231 if (outsize<requiredsize)
8232 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8233 Py_DECREF(rep);
8234 return enc_EXCEPTION;
8235 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008236 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008237 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008238 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008239 else {
8240 const char *repchars = PyBytes_AS_STRING(rep);
8241 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8242 Py_ssize_t requiredsize = *outpos+repsize;
8243 if (outsize<requiredsize)
8244 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8245 Py_DECREF(rep);
8246 return enc_EXCEPTION;
8247 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008248 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008249 memcpy(outstart + *outpos, repchars, repsize);
8250 *outpos += repsize;
8251 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008252 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008253 Py_DECREF(rep);
8254 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008255}
8256
8257/* handle an error in PyUnicode_EncodeCharmap
8258 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008259static int
8260charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008261 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008262 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008263 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008264 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008265{
8266 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008267 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008268 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008269 enum PyUnicode_Kind kind;
8270 void *data;
8271 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008272 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008273 Py_ssize_t collstartpos = *inpos;
8274 Py_ssize_t collendpos = *inpos+1;
8275 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008276 char *encoding = "charmap";
8277 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008278 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008279 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008280 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008281
Benjamin Petersonbac79492012-01-14 13:34:47 -05008282 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008283 return -1;
8284 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008285 /* find all unencodable characters */
8286 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008287 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008288 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008289 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008290 val = encoding_map_lookup(ch, mapping);
8291 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008292 break;
8293 ++collendpos;
8294 continue;
8295 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008296
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008297 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8298 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008299 if (rep==NULL)
8300 return -1;
8301 else if (rep!=Py_None) {
8302 Py_DECREF(rep);
8303 break;
8304 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008305 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008306 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008307 }
8308 /* cache callback name lookup
8309 * (if not done yet, i.e. it's the first error) */
8310 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008311 if ((errors==NULL) || (!strcmp(errors, "strict")))
8312 *known_errorHandler = 1;
8313 else if (!strcmp(errors, "replace"))
8314 *known_errorHandler = 2;
8315 else if (!strcmp(errors, "ignore"))
8316 *known_errorHandler = 3;
8317 else if (!strcmp(errors, "xmlcharrefreplace"))
8318 *known_errorHandler = 4;
8319 else
8320 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008321 }
8322 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008323 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008324 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008325 return -1;
8326 case 2: /* replace */
8327 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008328 x = charmapencode_output('?', mapping, res, respos);
8329 if (x==enc_EXCEPTION) {
8330 return -1;
8331 }
8332 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008333 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008334 return -1;
8335 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008336 }
8337 /* fall through */
8338 case 3: /* ignore */
8339 *inpos = collendpos;
8340 break;
8341 case 4: /* xmlcharrefreplace */
8342 /* generate replacement (temporarily (mis)uses p) */
8343 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008344 char buffer[2+29+1+1];
8345 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008346 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008347 for (cp = buffer; *cp; ++cp) {
8348 x = charmapencode_output(*cp, mapping, res, respos);
8349 if (x==enc_EXCEPTION)
8350 return -1;
8351 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008352 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008353 return -1;
8354 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008355 }
8356 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008357 *inpos = collendpos;
8358 break;
8359 default:
8360 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008361 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008362 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008363 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008364 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008365 if (PyBytes_Check(repunicode)) {
8366 /* Directly copy bytes result to output. */
8367 Py_ssize_t outsize = PyBytes_Size(*res);
8368 Py_ssize_t requiredsize;
8369 repsize = PyBytes_Size(repunicode);
8370 requiredsize = *respos + repsize;
8371 if (requiredsize > outsize)
8372 /* Make room for all additional bytes. */
8373 if (charmapencode_resize(res, respos, requiredsize)) {
8374 Py_DECREF(repunicode);
8375 return -1;
8376 }
8377 memcpy(PyBytes_AsString(*res) + *respos,
8378 PyBytes_AsString(repunicode), repsize);
8379 *respos += repsize;
8380 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008381 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008382 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008383 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008384 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008385 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008386 Py_DECREF(repunicode);
8387 return -1;
8388 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008389 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008390 data = PyUnicode_DATA(repunicode);
8391 kind = PyUnicode_KIND(repunicode);
8392 for (index = 0; index < repsize; index++) {
8393 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8394 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008395 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008396 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008397 return -1;
8398 }
8399 else if (x==enc_FAILED) {
8400 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008401 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008402 return -1;
8403 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008404 }
8405 *inpos = newpos;
8406 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008407 }
8408 return 0;
8409}
8410
Alexander Belopolsky40018472011-02-26 01:02:56 +00008411PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008412_PyUnicode_EncodeCharmap(PyObject *unicode,
8413 PyObject *mapping,
8414 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008415{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008416 /* output object */
8417 PyObject *res = NULL;
8418 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008419 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008420 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008421 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008422 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008423 PyObject *errorHandler = NULL;
8424 PyObject *exc = NULL;
8425 /* the following variable is used for caching string comparisons
8426 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8427 * 3=ignore, 4=xmlcharrefreplace */
8428 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008429
Benjamin Petersonbac79492012-01-14 13:34:47 -05008430 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008431 return NULL;
8432 size = PyUnicode_GET_LENGTH(unicode);
8433
Guido van Rossumd57fd912000-03-10 22:53:23 +00008434 /* Default to Latin-1 */
8435 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008436 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008437
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008438 /* allocate enough for a simple encoding without
8439 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008440 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008441 if (res == NULL)
8442 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008443 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008444 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008445
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008446 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008447 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008448 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008449 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008450 if (x==enc_EXCEPTION) /* error */
8451 goto onError;
8452 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008453 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008454 &exc,
8455 &known_errorHandler, &errorHandler, errors,
8456 &res, &respos)) {
8457 goto onError;
8458 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008459 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008460 else
8461 /* done with this character => adjust input position */
8462 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008463 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008464
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008465 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008466 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008467 if (_PyBytes_Resize(&res, respos) < 0)
8468 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008469
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008470 Py_XDECREF(exc);
8471 Py_XDECREF(errorHandler);
8472 return res;
8473
Benjamin Peterson29060642009-01-31 22:14:21 +00008474 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008475 Py_XDECREF(res);
8476 Py_XDECREF(exc);
8477 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008478 return NULL;
8479}
8480
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008481/* Deprecated */
8482PyObject *
8483PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8484 Py_ssize_t size,
8485 PyObject *mapping,
8486 const char *errors)
8487{
8488 PyObject *result;
8489 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8490 if (unicode == NULL)
8491 return NULL;
8492 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8493 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008494 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008495}
8496
Alexander Belopolsky40018472011-02-26 01:02:56 +00008497PyObject *
8498PyUnicode_AsCharmapString(PyObject *unicode,
8499 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008500{
8501 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 PyErr_BadArgument();
8503 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008504 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008505 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008506}
8507
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008508/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008509static void
8510make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008511 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008512 Py_ssize_t startpos, Py_ssize_t endpos,
8513 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008514{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008515 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008516 *exceptionObject = _PyUnicodeTranslateError_Create(
8517 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008518 }
8519 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008520 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8521 goto onError;
8522 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8523 goto onError;
8524 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8525 goto onError;
8526 return;
8527 onError:
8528 Py_DECREF(*exceptionObject);
8529 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008530 }
8531}
8532
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008533/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008534static void
8535raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008536 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008537 Py_ssize_t startpos, Py_ssize_t endpos,
8538 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008539{
8540 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008541 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008542 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008543 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008544}
8545
8546/* error handling callback helper:
8547 build arguments, call the callback and check the arguments,
8548 put the result into newpos and return the replacement string, which
8549 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008550static PyObject *
8551unicode_translate_call_errorhandler(const char *errors,
8552 PyObject **errorHandler,
8553 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008554 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008555 Py_ssize_t startpos, Py_ssize_t endpos,
8556 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008557{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008558 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008559
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008560 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008561 PyObject *restuple;
8562 PyObject *resunicode;
8563
8564 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008565 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008566 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008567 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008568 }
8569
8570 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008571 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008572 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008573 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008574
8575 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008576 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008577 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008578 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008579 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008580 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008581 Py_DECREF(restuple);
8582 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008583 }
8584 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008585 &resunicode, &i_newpos)) {
8586 Py_DECREF(restuple);
8587 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008588 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008589 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008590 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008591 else
8592 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008593 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008594 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8595 Py_DECREF(restuple);
8596 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008597 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008598 Py_INCREF(resunicode);
8599 Py_DECREF(restuple);
8600 return resunicode;
8601}
8602
8603/* Lookup the character ch in the mapping and put the result in result,
8604 which must be decrefed by the caller.
8605 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008606static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008607charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008608{
Christian Heimes217cfd12007-12-02 14:31:20 +00008609 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008610 PyObject *x;
8611
8612 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008613 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008614 x = PyObject_GetItem(mapping, w);
8615 Py_DECREF(w);
8616 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008617 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8618 /* No mapping found means: use 1:1 mapping. */
8619 PyErr_Clear();
8620 *result = NULL;
8621 return 0;
8622 } else
8623 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008624 }
8625 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008626 *result = x;
8627 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008628 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008629 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008630 long value = PyLong_AS_LONG(x);
8631 long max = PyUnicode_GetMax();
8632 if (value < 0 || value > max) {
8633 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008634 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008635 Py_DECREF(x);
8636 return -1;
8637 }
8638 *result = x;
8639 return 0;
8640 }
8641 else if (PyUnicode_Check(x)) {
8642 *result = x;
8643 return 0;
8644 }
8645 else {
8646 /* wrong return value */
8647 PyErr_SetString(PyExc_TypeError,
8648 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008649 Py_DECREF(x);
8650 return -1;
8651 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008652}
8653/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008654 if not reallocate and adjust various state variables.
8655 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008656static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008657charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008658 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008659{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008660 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008661 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008662 /* exponentially overallocate to minimize reallocations */
8663 if (requiredsize < 2 * oldsize)
8664 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008665 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8666 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008667 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008668 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008669 }
8670 return 0;
8671}
8672/* lookup the character, put the result in the output string and adjust
8673 various state variables. Return a new reference to the object that
8674 was put in the output buffer in *result, or Py_None, if the mapping was
8675 undefined (in which case no character was written).
8676 The called must decref result.
8677 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008678static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008679charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8680 PyObject *mapping, Py_UCS4 **output,
8681 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008682 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008683{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008684 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8685 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008686 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008687 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008688 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008689 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008690 }
8691 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008692 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008693 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008694 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008695 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008696 }
8697 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008698 Py_ssize_t repsize;
8699 if (PyUnicode_READY(*res) == -1)
8700 return -1;
8701 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 if (repsize==1) {
8703 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008704 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008705 }
8706 else if (repsize!=0) {
8707 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008708 Py_ssize_t requiredsize = *opos +
8709 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008710 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008711 Py_ssize_t i;
8712 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008713 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008714 for(i = 0; i < repsize; i++)
8715 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008716 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008717 }
8718 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008719 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008720 return 0;
8721}
8722
Alexander Belopolsky40018472011-02-26 01:02:56 +00008723PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008724_PyUnicode_TranslateCharmap(PyObject *input,
8725 PyObject *mapping,
8726 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008727{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008728 /* input object */
8729 char *idata;
8730 Py_ssize_t size, i;
8731 int kind;
8732 /* output buffer */
8733 Py_UCS4 *output = NULL;
8734 Py_ssize_t osize;
8735 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008736 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008737 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008738 char *reason = "character maps to <undefined>";
8739 PyObject *errorHandler = NULL;
8740 PyObject *exc = NULL;
8741 /* the following variable is used for caching string comparisons
8742 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8743 * 3=ignore, 4=xmlcharrefreplace */
8744 int known_errorHandler = -1;
8745
Guido van Rossumd57fd912000-03-10 22:53:23 +00008746 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008747 PyErr_BadArgument();
8748 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008749 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008750
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008751 if (PyUnicode_READY(input) == -1)
8752 return NULL;
8753 idata = (char*)PyUnicode_DATA(input);
8754 kind = PyUnicode_KIND(input);
8755 size = PyUnicode_GET_LENGTH(input);
8756 i = 0;
8757
8758 if (size == 0) {
8759 Py_INCREF(input);
8760 return input;
8761 }
8762
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008763 /* allocate enough for a simple 1:1 translation without
8764 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008765 osize = size;
8766 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8767 opos = 0;
8768 if (output == NULL) {
8769 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008770 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008771 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008772
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008773 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008774 /* try to encode it */
8775 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008776 if (charmaptranslate_output(input, i, mapping,
8777 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008778 Py_XDECREF(x);
8779 goto onError;
8780 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008781 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008782 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008783 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008784 else { /* untranslatable character */
8785 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8786 Py_ssize_t repsize;
8787 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008788 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008789 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008790 Py_ssize_t collstart = i;
8791 Py_ssize_t collend = i+1;
8792 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008793
Benjamin Peterson29060642009-01-31 22:14:21 +00008794 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008795 while (collend < size) {
8796 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008797 goto onError;
8798 Py_XDECREF(x);
8799 if (x!=Py_None)
8800 break;
8801 ++collend;
8802 }
8803 /* cache callback name lookup
8804 * (if not done yet, i.e. it's the first error) */
8805 if (known_errorHandler==-1) {
8806 if ((errors==NULL) || (!strcmp(errors, "strict")))
8807 known_errorHandler = 1;
8808 else if (!strcmp(errors, "replace"))
8809 known_errorHandler = 2;
8810 else if (!strcmp(errors, "ignore"))
8811 known_errorHandler = 3;
8812 else if (!strcmp(errors, "xmlcharrefreplace"))
8813 known_errorHandler = 4;
8814 else
8815 known_errorHandler = 0;
8816 }
8817 switch (known_errorHandler) {
8818 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008819 raise_translate_exception(&exc, input, collstart,
8820 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008821 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008822 case 2: /* replace */
8823 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008824 for (coll = collstart; coll<collend; coll++)
8825 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008826 /* fall through */
8827 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008828 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008829 break;
8830 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008831 /* generate replacement (temporarily (mis)uses i) */
8832 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008833 char buffer[2+29+1+1];
8834 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008835 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8836 if (charmaptranslate_makespace(&output, &osize,
8837 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008838 goto onError;
8839 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008840 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008841 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008842 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008843 break;
8844 default:
8845 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008846 reason, input, &exc,
8847 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008848 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008849 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008850 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008851 Py_DECREF(repunicode);
8852 goto onError;
8853 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008854 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008855 repsize = PyUnicode_GET_LENGTH(repunicode);
8856 if (charmaptranslate_makespace(&output, &osize,
8857 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008858 Py_DECREF(repunicode);
8859 goto onError;
8860 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008861 for (uni2 = 0; repsize-->0; ++uni2)
8862 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8863 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008864 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008865 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008866 }
8867 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008868 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8869 if (!res)
8870 goto onError;
8871 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008872 Py_XDECREF(exc);
8873 Py_XDECREF(errorHandler);
8874 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008875
Benjamin Peterson29060642009-01-31 22:14:21 +00008876 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008877 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008878 Py_XDECREF(exc);
8879 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008880 return NULL;
8881}
8882
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008883/* Deprecated. Use PyUnicode_Translate instead. */
8884PyObject *
8885PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8886 Py_ssize_t size,
8887 PyObject *mapping,
8888 const char *errors)
8889{
8890 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8891 if (!unicode)
8892 return NULL;
8893 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8894}
8895
Alexander Belopolsky40018472011-02-26 01:02:56 +00008896PyObject *
8897PyUnicode_Translate(PyObject *str,
8898 PyObject *mapping,
8899 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008900{
8901 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008902
Guido van Rossumd57fd912000-03-10 22:53:23 +00008903 str = PyUnicode_FromObject(str);
8904 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008905 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008906 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008907 Py_DECREF(str);
8908 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008909
Benjamin Peterson29060642009-01-31 22:14:21 +00008910 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008911 Py_XDECREF(str);
8912 return NULL;
8913}
Tim Petersced69f82003-09-16 20:30:58 +00008914
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008915static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008916fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008917{
8918 /* No need to call PyUnicode_READY(self) because this function is only
8919 called as a callback from fixup() which does it already. */
8920 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8921 const int kind = PyUnicode_KIND(self);
8922 void *data = PyUnicode_DATA(self);
8923 Py_UCS4 maxchar = 0, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008924 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008925 Py_ssize_t i;
8926
8927 for (i = 0; i < len; ++i) {
8928 ch = PyUnicode_READ(kind, data, i);
8929 fixed = 0;
8930 if (ch > 127) {
8931 if (Py_UNICODE_ISSPACE(ch))
8932 fixed = ' ';
8933 else {
8934 const int decimal = Py_UNICODE_TODECIMAL(ch);
8935 if (decimal >= 0)
8936 fixed = '0' + decimal;
8937 }
8938 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008939 modified = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008940 if (fixed > maxchar)
8941 maxchar = fixed;
8942 PyUnicode_WRITE(kind, data, i, fixed);
8943 }
8944 else if (ch > maxchar)
8945 maxchar = ch;
8946 }
8947 else if (ch > maxchar)
8948 maxchar = ch;
8949 }
8950
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008951 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008952}
8953
8954PyObject *
8955_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8956{
8957 if (!PyUnicode_Check(unicode)) {
8958 PyErr_BadInternalCall();
8959 return NULL;
8960 }
8961 if (PyUnicode_READY(unicode) == -1)
8962 return NULL;
8963 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8964 /* If the string is already ASCII, just return the same string */
8965 Py_INCREF(unicode);
8966 return unicode;
8967 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008968 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008969}
8970
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008971PyObject *
8972PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8973 Py_ssize_t length)
8974{
Victor Stinnerf0124502011-11-21 23:12:56 +01008975 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008976 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008977 Py_UCS4 maxchar;
8978 enum PyUnicode_Kind kind;
8979 void *data;
8980
Victor Stinner99d7ad02012-02-22 13:37:39 +01008981 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008982 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008983 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008984 if (ch > 127) {
8985 int decimal = Py_UNICODE_TODECIMAL(ch);
8986 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008987 ch = '0' + decimal;
Victor Stinner99d7ad02012-02-22 13:37:39 +01008988 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008989 }
8990 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008991
8992 /* Copy to a new string */
8993 decimal = PyUnicode_New(length, maxchar);
8994 if (decimal == NULL)
8995 return decimal;
8996 kind = PyUnicode_KIND(decimal);
8997 data = PyUnicode_DATA(decimal);
8998 /* Iterate over code points */
8999 for (i = 0; i < length; i++) {
9000 Py_UNICODE ch = s[i];
9001 if (ch > 127) {
9002 int decimal = Py_UNICODE_TODECIMAL(ch);
9003 if (decimal >= 0)
9004 ch = '0' + decimal;
9005 }
9006 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009007 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009008 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009009}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009010/* --- Decimal Encoder ---------------------------------------------------- */
9011
Alexander Belopolsky40018472011-02-26 01:02:56 +00009012int
9013PyUnicode_EncodeDecimal(Py_UNICODE *s,
9014 Py_ssize_t length,
9015 char *output,
9016 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009017{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009018 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009019 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009020 enum PyUnicode_Kind kind;
9021 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009022
9023 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009024 PyErr_BadArgument();
9025 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009026 }
9027
Victor Stinner42bf7752011-11-21 22:52:58 +01009028 unicode = PyUnicode_FromUnicode(s, length);
9029 if (unicode == NULL)
9030 return -1;
9031
Benjamin Petersonbac79492012-01-14 13:34:47 -05009032 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009033 Py_DECREF(unicode);
9034 return -1;
9035 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009036 kind = PyUnicode_KIND(unicode);
9037 data = PyUnicode_DATA(unicode);
9038
Victor Stinnerb84d7232011-11-22 01:50:07 +01009039 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009040 PyObject *exc;
9041 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009042 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009043 Py_ssize_t startpos;
9044
9045 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009046
Benjamin Peterson29060642009-01-31 22:14:21 +00009047 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009048 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009049 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009050 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009051 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009052 decimal = Py_UNICODE_TODECIMAL(ch);
9053 if (decimal >= 0) {
9054 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009055 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009056 continue;
9057 }
9058 if (0 < ch && ch < 256) {
9059 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009060 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009061 continue;
9062 }
Victor Stinner6345be92011-11-25 20:09:01 +01009063
Victor Stinner42bf7752011-11-21 22:52:58 +01009064 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009065 exc = NULL;
9066 raise_encode_exception(&exc, "decimal", unicode,
9067 startpos, startpos+1,
9068 "invalid decimal Unicode string");
9069 Py_XDECREF(exc);
9070 Py_DECREF(unicode);
9071 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009072 }
9073 /* 0-terminate the output string */
9074 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009075 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009076 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009077}
9078
Guido van Rossumd57fd912000-03-10 22:53:23 +00009079/* --- Helpers ------------------------------------------------------------ */
9080
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009081static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009082any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009083 Py_ssize_t start,
9084 Py_ssize_t end)
9085{
9086 int kind1, kind2, kind;
9087 void *buf1, *buf2;
9088 Py_ssize_t len1, len2, result;
9089
9090 kind1 = PyUnicode_KIND(s1);
9091 kind2 = PyUnicode_KIND(s2);
9092 kind = kind1 > kind2 ? kind1 : kind2;
9093 buf1 = PyUnicode_DATA(s1);
9094 buf2 = PyUnicode_DATA(s2);
9095 if (kind1 != kind)
9096 buf1 = _PyUnicode_AsKind(s1, kind);
9097 if (!buf1)
9098 return -2;
9099 if (kind2 != kind)
9100 buf2 = _PyUnicode_AsKind(s2, kind);
9101 if (!buf2) {
9102 if (kind1 != kind) PyMem_Free(buf1);
9103 return -2;
9104 }
9105 len1 = PyUnicode_GET_LENGTH(s1);
9106 len2 = PyUnicode_GET_LENGTH(s2);
9107
Victor Stinner794d5672011-10-10 03:21:36 +02009108 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009109 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009110 case PyUnicode_1BYTE_KIND:
9111 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9112 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9113 else
9114 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9115 break;
9116 case PyUnicode_2BYTE_KIND:
9117 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9118 break;
9119 case PyUnicode_4BYTE_KIND:
9120 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9121 break;
9122 default:
9123 assert(0); result = -2;
9124 }
9125 }
9126 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009127 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009128 case PyUnicode_1BYTE_KIND:
9129 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9130 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9131 else
9132 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9133 break;
9134 case PyUnicode_2BYTE_KIND:
9135 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9136 break;
9137 case PyUnicode_4BYTE_KIND:
9138 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9139 break;
9140 default:
9141 assert(0); result = -2;
9142 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009143 }
9144
9145 if (kind1 != kind)
9146 PyMem_Free(buf1);
9147 if (kind2 != kind)
9148 PyMem_Free(buf2);
9149
9150 return result;
9151}
9152
9153Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009154_PyUnicode_InsertThousandsGrouping(
9155 PyObject *unicode, Py_ssize_t index,
9156 Py_ssize_t n_buffer,
9157 void *digits, Py_ssize_t n_digits,
9158 Py_ssize_t min_width,
9159 const char *grouping, PyObject *thousands_sep,
9160 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009161{
Victor Stinner41a863c2012-02-24 00:37:51 +01009162 unsigned int kind, thousands_sep_kind;
9163 void *data, *thousands_sep_data;
9164 Py_ssize_t thousands_sep_len;
9165 Py_ssize_t len;
9166
9167 if (unicode != NULL) {
9168 kind = PyUnicode_KIND(unicode);
9169 data = PyUnicode_DATA(unicode) + index * kind;
9170 }
9171 else {
9172 kind = PyUnicode_1BYTE_KIND;
9173 data = NULL;
9174 }
9175 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9176 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9177 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9178 if (unicode != NULL && thousands_sep_kind != kind) {
9179 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9180 if (!thousands_sep_data)
9181 return -1;
9182 }
9183
Benjamin Petersonead6b532011-12-20 17:23:42 -06009184 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009185 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009186 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009187 len = asciilib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009188 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009189 min_width, grouping,
9190 thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009191 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009192 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009193 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009194 min_width, grouping,
9195 thousands_sep_data, thousands_sep_len);
9196 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009197 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009198 len = ucs2lib_InsertThousandsGrouping(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009199 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009200 min_width, grouping,
9201 thousands_sep_data, thousands_sep_len);
9202 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009203 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009204 len = ucs4lib_InsertThousandsGrouping(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009205 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009206 min_width, grouping,
9207 thousands_sep_data, thousands_sep_len);
9208 break;
9209 default:
9210 assert(0);
9211 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009212 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009213 if (unicode != NULL && thousands_sep_kind != kind)
9214 PyMem_Free(thousands_sep_data);
9215 if (unicode == NULL) {
9216 *maxchar = 127;
9217 if (len != n_digits) {
9218 *maxchar = Py_MAX(*maxchar,
9219 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
9220 }
9221 }
9222 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009223}
9224
9225
Thomas Wouters477c8d52006-05-27 19:21:47 +00009226/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009227#define ADJUST_INDICES(start, end, len) \
9228 if (end > len) \
9229 end = len; \
9230 else if (end < 0) { \
9231 end += len; \
9232 if (end < 0) \
9233 end = 0; \
9234 } \
9235 if (start < 0) { \
9236 start += len; \
9237 if (start < 0) \
9238 start = 0; \
9239 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009240
Alexander Belopolsky40018472011-02-26 01:02:56 +00009241Py_ssize_t
9242PyUnicode_Count(PyObject *str,
9243 PyObject *substr,
9244 Py_ssize_t start,
9245 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009246{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009247 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009248 PyObject* str_obj;
9249 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009250 int kind1, kind2, kind;
9251 void *buf1 = NULL, *buf2 = NULL;
9252 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009253
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009254 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009255 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009256 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009257 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009258 if (!sub_obj) {
9259 Py_DECREF(str_obj);
9260 return -1;
9261 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009262 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009263 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009264 Py_DECREF(str_obj);
9265 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009266 }
Tim Petersced69f82003-09-16 20:30:58 +00009267
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009268 kind1 = PyUnicode_KIND(str_obj);
9269 kind2 = PyUnicode_KIND(sub_obj);
9270 kind = kind1 > kind2 ? kind1 : kind2;
9271 buf1 = PyUnicode_DATA(str_obj);
9272 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009273 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009274 if (!buf1)
9275 goto onError;
9276 buf2 = PyUnicode_DATA(sub_obj);
9277 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009278 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009279 if (!buf2)
9280 goto onError;
9281 len1 = PyUnicode_GET_LENGTH(str_obj);
9282 len2 = PyUnicode_GET_LENGTH(sub_obj);
9283
9284 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009285 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009286 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009287 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9288 result = asciilib_count(
9289 ((Py_UCS1*)buf1) + start, end - start,
9290 buf2, len2, PY_SSIZE_T_MAX
9291 );
9292 else
9293 result = ucs1lib_count(
9294 ((Py_UCS1*)buf1) + start, end - start,
9295 buf2, len2, PY_SSIZE_T_MAX
9296 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009297 break;
9298 case PyUnicode_2BYTE_KIND:
9299 result = ucs2lib_count(
9300 ((Py_UCS2*)buf1) + start, end - start,
9301 buf2, len2, PY_SSIZE_T_MAX
9302 );
9303 break;
9304 case PyUnicode_4BYTE_KIND:
9305 result = ucs4lib_count(
9306 ((Py_UCS4*)buf1) + start, end - start,
9307 buf2, len2, PY_SSIZE_T_MAX
9308 );
9309 break;
9310 default:
9311 assert(0); result = 0;
9312 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009313
9314 Py_DECREF(sub_obj);
9315 Py_DECREF(str_obj);
9316
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009317 if (kind1 != kind)
9318 PyMem_Free(buf1);
9319 if (kind2 != kind)
9320 PyMem_Free(buf2);
9321
Guido van Rossumd57fd912000-03-10 22:53:23 +00009322 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009323 onError:
9324 Py_DECREF(sub_obj);
9325 Py_DECREF(str_obj);
9326 if (kind1 != kind && buf1)
9327 PyMem_Free(buf1);
9328 if (kind2 != kind && buf2)
9329 PyMem_Free(buf2);
9330 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009331}
9332
Alexander Belopolsky40018472011-02-26 01:02:56 +00009333Py_ssize_t
9334PyUnicode_Find(PyObject *str,
9335 PyObject *sub,
9336 Py_ssize_t start,
9337 Py_ssize_t end,
9338 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009339{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009340 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009341
Guido van Rossumd57fd912000-03-10 22:53:23 +00009342 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009343 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009344 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009345 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009346 if (!sub) {
9347 Py_DECREF(str);
9348 return -2;
9349 }
9350 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9351 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009352 Py_DECREF(str);
9353 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009354 }
Tim Petersced69f82003-09-16 20:30:58 +00009355
Victor Stinner794d5672011-10-10 03:21:36 +02009356 result = any_find_slice(direction,
9357 str, sub, start, end
9358 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009359
Guido van Rossumd57fd912000-03-10 22:53:23 +00009360 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009361 Py_DECREF(sub);
9362
Guido van Rossumd57fd912000-03-10 22:53:23 +00009363 return result;
9364}
9365
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009366Py_ssize_t
9367PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9368 Py_ssize_t start, Py_ssize_t end,
9369 int direction)
9370{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009371 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009372 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009373 if (PyUnicode_READY(str) == -1)
9374 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009375 if (start < 0 || end < 0) {
9376 PyErr_SetString(PyExc_IndexError, "string index out of range");
9377 return -2;
9378 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009379 if (end > PyUnicode_GET_LENGTH(str))
9380 end = PyUnicode_GET_LENGTH(str);
9381 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009382 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9383 kind, end-start, ch, direction);
9384 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009385 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009386 else
9387 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009388}
9389
Alexander Belopolsky40018472011-02-26 01:02:56 +00009390static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009391tailmatch(PyObject *self,
9392 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009393 Py_ssize_t start,
9394 Py_ssize_t end,
9395 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009396{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009397 int kind_self;
9398 int kind_sub;
9399 void *data_self;
9400 void *data_sub;
9401 Py_ssize_t offset;
9402 Py_ssize_t i;
9403 Py_ssize_t end_sub;
9404
9405 if (PyUnicode_READY(self) == -1 ||
9406 PyUnicode_READY(substring) == -1)
9407 return 0;
9408
9409 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009410 return 1;
9411
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009412 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9413 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009414 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009415 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009416
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009417 kind_self = PyUnicode_KIND(self);
9418 data_self = PyUnicode_DATA(self);
9419 kind_sub = PyUnicode_KIND(substring);
9420 data_sub = PyUnicode_DATA(substring);
9421 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9422
9423 if (direction > 0)
9424 offset = end;
9425 else
9426 offset = start;
9427
9428 if (PyUnicode_READ(kind_self, data_self, offset) ==
9429 PyUnicode_READ(kind_sub, data_sub, 0) &&
9430 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9431 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9432 /* If both are of the same kind, memcmp is sufficient */
9433 if (kind_self == kind_sub) {
9434 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009435 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009436 data_sub,
9437 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009438 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009439 }
9440 /* otherwise we have to compare each character by first accesing it */
9441 else {
9442 /* We do not need to compare 0 and len(substring)-1 because
9443 the if statement above ensured already that they are equal
9444 when we end up here. */
9445 // TODO: honor direction and do a forward or backwards search
9446 for (i = 1; i < end_sub; ++i) {
9447 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9448 PyUnicode_READ(kind_sub, data_sub, i))
9449 return 0;
9450 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009451 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009452 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009453 }
9454
9455 return 0;
9456}
9457
Alexander Belopolsky40018472011-02-26 01:02:56 +00009458Py_ssize_t
9459PyUnicode_Tailmatch(PyObject *str,
9460 PyObject *substr,
9461 Py_ssize_t start,
9462 Py_ssize_t end,
9463 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009465 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009466
Guido van Rossumd57fd912000-03-10 22:53:23 +00009467 str = PyUnicode_FromObject(str);
9468 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009469 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009470 substr = PyUnicode_FromObject(substr);
9471 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009472 Py_DECREF(str);
9473 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009474 }
Tim Petersced69f82003-09-16 20:30:58 +00009475
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009476 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009477 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009478 Py_DECREF(str);
9479 Py_DECREF(substr);
9480 return result;
9481}
9482
Guido van Rossumd57fd912000-03-10 22:53:23 +00009483/* Apply fixfct filter to the Unicode object self and return a
9484 reference to the modified object */
9485
Alexander Belopolsky40018472011-02-26 01:02:56 +00009486static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009487fixup(PyObject *self,
9488 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009489{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009490 PyObject *u;
9491 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009492 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009493
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009494 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009495 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009496 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009497 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009498
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009499 /* fix functions return the new maximum character in a string,
9500 if the kind of the resulting unicode object does not change,
9501 everything is fine. Otherwise we need to change the string kind
9502 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009503 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009504
9505 if (maxchar_new == 0) {
9506 /* no changes */;
9507 if (PyUnicode_CheckExact(self)) {
9508 Py_DECREF(u);
9509 Py_INCREF(self);
9510 return self;
9511 }
9512 else
9513 return u;
9514 }
9515
9516 if (maxchar_new <= 127)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009517 maxchar_new = 127;
9518 else if (maxchar_new <= 255)
9519 maxchar_new = 255;
9520 else if (maxchar_new <= 65535)
9521 maxchar_new = 65535;
9522 else
Victor Stinner8faf8212011-12-08 22:14:11 +01009523 maxchar_new = MAX_UNICODE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009524
Victor Stinnereaab6042011-12-11 22:22:39 +01009525 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009526 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009527
9528 /* In case the maximum character changed, we need to
9529 convert the string to the new category. */
9530 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9531 if (v == NULL) {
9532 Py_DECREF(u);
9533 return NULL;
9534 }
9535 if (maxchar_new > maxchar_old) {
9536 /* If the maxchar increased so that the kind changed, not all
9537 characters are representable anymore and we need to fix the
9538 string again. This only happens in very few cases. */
9539 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
9540 maxchar_old = fixfct(v);
9541 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009542 }
9543 else {
Victor Stinnereaab6042011-12-11 22:22:39 +01009544 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009545 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009546 Py_DECREF(u);
9547 assert(_PyUnicode_CheckConsistency(v, 1));
9548 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009549}
9550
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009551static PyObject *
9552ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009553{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009554 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9555 char *resdata, *data = PyUnicode_DATA(self);
9556 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009557
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009558 res = PyUnicode_New(len, 127);
9559 if (res == NULL)
9560 return NULL;
9561 resdata = PyUnicode_DATA(res);
9562 if (lower)
9563 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009564 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009565 _Py_bytes_upper(resdata, data, len);
9566 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009567}
9568
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009569static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009570handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009571{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009572 Py_ssize_t j;
9573 int final_sigma;
9574 Py_UCS4 c;
9575 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009576
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009577 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9578
9579 where ! is a negation and \p{xxx} is a character with property xxx.
9580 */
9581 for (j = i - 1; j >= 0; j--) {
9582 c = PyUnicode_READ(kind, data, j);
9583 if (!_PyUnicode_IsCaseIgnorable(c))
9584 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009585 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009586 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9587 if (final_sigma) {
9588 for (j = i + 1; j < length; j++) {
9589 c = PyUnicode_READ(kind, data, j);
9590 if (!_PyUnicode_IsCaseIgnorable(c))
9591 break;
9592 }
9593 final_sigma = j == length || !_PyUnicode_IsCased(c);
9594 }
9595 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009596}
9597
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009598static int
9599lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9600 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009601{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009602 /* Obscure special case. */
9603 if (c == 0x3A3) {
9604 mapped[0] = handle_capital_sigma(kind, data, length, i);
9605 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009606 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009607 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009608}
9609
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009610static Py_ssize_t
9611do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009612{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009613 Py_ssize_t i, k = 0;
9614 int n_res, j;
9615 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009616
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009617 c = PyUnicode_READ(kind, data, 0);
9618 n_res = _PyUnicode_ToUpperFull(c, mapped);
9619 for (j = 0; j < n_res; j++) {
9620 if (mapped[j] > *maxchar)
9621 *maxchar = mapped[j];
9622 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009623 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009624 for (i = 1; i < length; i++) {
9625 c = PyUnicode_READ(kind, data, i);
9626 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9627 for (j = 0; j < n_res; j++) {
9628 if (mapped[j] > *maxchar)
9629 *maxchar = mapped[j];
9630 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009631 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009632 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009633 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009634}
9635
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009636static Py_ssize_t
9637do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9638 Py_ssize_t i, k = 0;
9639
9640 for (i = 0; i < length; i++) {
9641 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9642 int n_res, j;
9643 if (Py_UNICODE_ISUPPER(c)) {
9644 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9645 }
9646 else if (Py_UNICODE_ISLOWER(c)) {
9647 n_res = _PyUnicode_ToUpperFull(c, mapped);
9648 }
9649 else {
9650 n_res = 1;
9651 mapped[0] = c;
9652 }
9653 for (j = 0; j < n_res; j++) {
9654 if (mapped[j] > *maxchar)
9655 *maxchar = mapped[j];
9656 res[k++] = mapped[j];
9657 }
9658 }
9659 return k;
9660}
9661
9662static Py_ssize_t
9663do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9664 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009665{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009666 Py_ssize_t i, k = 0;
9667
9668 for (i = 0; i < length; i++) {
9669 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9670 int n_res, j;
9671 if (lower)
9672 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9673 else
9674 n_res = _PyUnicode_ToUpperFull(c, mapped);
9675 for (j = 0; j < n_res; j++) {
9676 if (mapped[j] > *maxchar)
9677 *maxchar = mapped[j];
9678 res[k++] = mapped[j];
9679 }
9680 }
9681 return k;
9682}
9683
9684static Py_ssize_t
9685do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9686{
9687 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9688}
9689
9690static Py_ssize_t
9691do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9692{
9693 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9694}
9695
Benjamin Petersone51757f2012-01-12 21:10:29 -05009696static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009697do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9698{
9699 Py_ssize_t i, k = 0;
9700
9701 for (i = 0; i < length; i++) {
9702 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9703 Py_UCS4 mapped[3];
9704 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9705 for (j = 0; j < n_res; j++) {
9706 if (mapped[j] > *maxchar)
9707 *maxchar = mapped[j];
9708 res[k++] = mapped[j];
9709 }
9710 }
9711 return k;
9712}
9713
9714static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009715do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9716{
9717 Py_ssize_t i, k = 0;
9718 int previous_is_cased;
9719
9720 previous_is_cased = 0;
9721 for (i = 0; i < length; i++) {
9722 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9723 Py_UCS4 mapped[3];
9724 int n_res, j;
9725
9726 if (previous_is_cased)
9727 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9728 else
9729 n_res = _PyUnicode_ToTitleFull(c, mapped);
9730
9731 for (j = 0; j < n_res; j++) {
9732 if (mapped[j] > *maxchar)
9733 *maxchar = mapped[j];
9734 res[k++] = mapped[j];
9735 }
9736
9737 previous_is_cased = _PyUnicode_IsCased(c);
9738 }
9739 return k;
9740}
9741
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009742static PyObject *
9743case_operation(PyObject *self,
9744 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9745{
9746 PyObject *res = NULL;
9747 Py_ssize_t length, newlength = 0;
9748 int kind, outkind;
9749 void *data, *outdata;
9750 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9751
Benjamin Petersoneea48462012-01-16 14:28:50 -05009752 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009753
9754 kind = PyUnicode_KIND(self);
9755 data = PyUnicode_DATA(self);
9756 length = PyUnicode_GET_LENGTH(self);
9757 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9758 if (tmp == NULL)
9759 return PyErr_NoMemory();
9760 newlength = perform(kind, data, length, tmp, &maxchar);
9761 res = PyUnicode_New(newlength, maxchar);
9762 if (res == NULL)
9763 goto leave;
9764 tmpend = tmp + newlength;
9765 outdata = PyUnicode_DATA(res);
9766 outkind = PyUnicode_KIND(res);
9767 switch (outkind) {
9768 case PyUnicode_1BYTE_KIND:
9769 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9770 break;
9771 case PyUnicode_2BYTE_KIND:
9772 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9773 break;
9774 case PyUnicode_4BYTE_KIND:
9775 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9776 break;
9777 default:
9778 assert(0);
9779 break;
9780 }
9781 leave:
9782 PyMem_FREE(tmp);
9783 return res;
9784}
9785
Tim Peters8ce9f162004-08-27 01:49:32 +00009786PyObject *
9787PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009788{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009789 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009790 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009791 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009792 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009793 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9794 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009795 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009796 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009797 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009798 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009799 int use_memcpy;
9800 unsigned char *res_data = NULL, *sep_data = NULL;
9801 PyObject *last_obj;
9802 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009803
Tim Peters05eba1f2004-08-27 21:32:02 +00009804 fseq = PySequence_Fast(seq, "");
9805 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009806 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009807 }
9808
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009809 /* NOTE: the following code can't call back into Python code,
9810 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009811 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009812
Tim Peters05eba1f2004-08-27 21:32:02 +00009813 seqlen = PySequence_Fast_GET_SIZE(fseq);
9814 /* If empty sequence, return u"". */
9815 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009816 Py_DECREF(fseq);
9817 Py_INCREF(unicode_empty);
9818 res = unicode_empty;
9819 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009820 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009821
Tim Peters05eba1f2004-08-27 21:32:02 +00009822 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009823 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009824 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009825 if (seqlen == 1) {
9826 if (PyUnicode_CheckExact(items[0])) {
9827 res = items[0];
9828 Py_INCREF(res);
9829 Py_DECREF(fseq);
9830 return res;
9831 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009832 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009833 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009834 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009835 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009836 /* Set up sep and seplen */
9837 if (separator == NULL) {
9838 /* fall back to a blank space separator */
9839 sep = PyUnicode_FromOrdinal(' ');
9840 if (!sep)
9841 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009842 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009843 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009844 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009845 else {
9846 if (!PyUnicode_Check(separator)) {
9847 PyErr_Format(PyExc_TypeError,
9848 "separator: expected str instance,"
9849 " %.80s found",
9850 Py_TYPE(separator)->tp_name);
9851 goto onError;
9852 }
9853 if (PyUnicode_READY(separator))
9854 goto onError;
9855 sep = separator;
9856 seplen = PyUnicode_GET_LENGTH(separator);
9857 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9858 /* inc refcount to keep this code path symmetric with the
9859 above case of a blank separator */
9860 Py_INCREF(sep);
9861 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009862 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009863 }
9864
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009865 /* There are at least two things to join, or else we have a subclass
9866 * of str in the sequence.
9867 * Do a pre-pass to figure out the total amount of space we'll
9868 * need (sz), and see whether all argument are strings.
9869 */
9870 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009871#ifdef Py_DEBUG
9872 use_memcpy = 0;
9873#else
9874 use_memcpy = 1;
9875#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009876 for (i = 0; i < seqlen; i++) {
9877 const Py_ssize_t old_sz = sz;
9878 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009879 if (!PyUnicode_Check(item)) {
9880 PyErr_Format(PyExc_TypeError,
9881 "sequence item %zd: expected str instance,"
9882 " %.80s found",
9883 i, Py_TYPE(item)->tp_name);
9884 goto onError;
9885 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009886 if (PyUnicode_READY(item) == -1)
9887 goto onError;
9888 sz += PyUnicode_GET_LENGTH(item);
9889 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009890 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009891 if (i != 0)
9892 sz += seplen;
9893 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9894 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009895 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009896 goto onError;
9897 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009898 if (use_memcpy && last_obj != NULL) {
9899 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9900 use_memcpy = 0;
9901 }
9902 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009903 }
Tim Petersced69f82003-09-16 20:30:58 +00009904
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009905 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009906 if (res == NULL)
9907 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009908
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009909 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009910#ifdef Py_DEBUG
9911 use_memcpy = 0;
9912#else
9913 if (use_memcpy) {
9914 res_data = PyUnicode_1BYTE_DATA(res);
9915 kind = PyUnicode_KIND(res);
9916 if (seplen != 0)
9917 sep_data = PyUnicode_1BYTE_DATA(sep);
9918 }
9919#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009920 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009921 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009922 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009923 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009924 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009925 if (use_memcpy) {
9926 Py_MEMCPY(res_data,
9927 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009928 kind * seplen);
9929 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009930 }
9931 else {
9932 copy_characters(res, res_offset, sep, 0, seplen);
9933 res_offset += seplen;
9934 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009935 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009936 itemlen = PyUnicode_GET_LENGTH(item);
9937 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009938 if (use_memcpy) {
9939 Py_MEMCPY(res_data,
9940 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009941 kind * itemlen);
9942 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009943 }
9944 else {
9945 copy_characters(res, res_offset, item, 0, itemlen);
9946 res_offset += itemlen;
9947 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009948 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009949 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009950 if (use_memcpy)
9951 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009952 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009953 else
9954 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009955
Tim Peters05eba1f2004-08-27 21:32:02 +00009956 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009957 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009958 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009959 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009960
Benjamin Peterson29060642009-01-31 22:14:21 +00009961 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009962 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009963 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009964 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009965 return NULL;
9966}
9967
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009968#define FILL(kind, data, value, start, length) \
9969 do { \
9970 Py_ssize_t i_ = 0; \
9971 assert(kind != PyUnicode_WCHAR_KIND); \
9972 switch ((kind)) { \
9973 case PyUnicode_1BYTE_KIND: { \
9974 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9975 memset(to_, (unsigned char)value, length); \
9976 break; \
9977 } \
9978 case PyUnicode_2BYTE_KIND: { \
9979 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9980 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9981 break; \
9982 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009983 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009984 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9985 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9986 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009987 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009988 } \
9989 } \
9990 } while (0)
9991
Victor Stinner3fe55312012-01-04 00:33:50 +01009992Py_ssize_t
9993PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9994 Py_UCS4 fill_char)
9995{
9996 Py_ssize_t maxlen;
9997 enum PyUnicode_Kind kind;
9998 void *data;
9999
10000 if (!PyUnicode_Check(unicode)) {
10001 PyErr_BadInternalCall();
10002 return -1;
10003 }
10004 if (PyUnicode_READY(unicode) == -1)
10005 return -1;
10006 if (unicode_check_modifiable(unicode))
10007 return -1;
10008
10009 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10010 PyErr_SetString(PyExc_ValueError,
10011 "fill character is bigger than "
10012 "the string maximum character");
10013 return -1;
10014 }
10015
10016 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10017 length = Py_MIN(maxlen, length);
10018 if (length <= 0)
10019 return 0;
10020
10021 kind = PyUnicode_KIND(unicode);
10022 data = PyUnicode_DATA(unicode);
10023 FILL(kind, data, fill_char, start, length);
10024 return length;
10025}
10026
Victor Stinner9310abb2011-10-05 00:59:23 +020010027static PyObject *
10028pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010029 Py_ssize_t left,
10030 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010031 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010032{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010033 PyObject *u;
10034 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010035 int kind;
10036 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010037
10038 if (left < 0)
10039 left = 0;
10040 if (right < 0)
10041 right = 0;
10042
Victor Stinnerc4b49542011-12-11 22:44:26 +010010043 if (left == 0 && right == 0)
10044 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010045
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010046 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10047 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010048 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10049 return NULL;
10050 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010051 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10052 if (fill > maxchar)
10053 maxchar = fill;
10054 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010055 if (!u)
10056 return NULL;
10057
10058 kind = PyUnicode_KIND(u);
10059 data = PyUnicode_DATA(u);
10060 if (left)
10061 FILL(kind, data, fill, 0, left);
10062 if (right)
10063 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010064 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010065 assert(_PyUnicode_CheckConsistency(u, 1));
10066 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010067}
10068
Alexander Belopolsky40018472011-02-26 01:02:56 +000010069PyObject *
10070PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010071{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010072 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010073
10074 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010075 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010076 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060010077 if (PyUnicode_READY(string) == -1) {
10078 Py_DECREF(string);
10079 return NULL;
10080 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010081
Benjamin Petersonead6b532011-12-20 17:23:42 -060010082 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010083 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010084 if (PyUnicode_IS_ASCII(string))
10085 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010086 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010087 PyUnicode_GET_LENGTH(string), keepends);
10088 else
10089 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010090 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010091 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010092 break;
10093 case PyUnicode_2BYTE_KIND:
10094 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010095 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010096 PyUnicode_GET_LENGTH(string), keepends);
10097 break;
10098 case PyUnicode_4BYTE_KIND:
10099 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010100 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010101 PyUnicode_GET_LENGTH(string), keepends);
10102 break;
10103 default:
10104 assert(0);
10105 list = 0;
10106 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010107 Py_DECREF(string);
10108 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010109}
10110
Alexander Belopolsky40018472011-02-26 01:02:56 +000010111static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010112split(PyObject *self,
10113 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010114 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010115{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010116 int kind1, kind2, kind;
10117 void *buf1, *buf2;
10118 Py_ssize_t len1, len2;
10119 PyObject* out;
10120
Guido van Rossumd57fd912000-03-10 22:53:23 +000010121 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010122 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010123
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010124 if (PyUnicode_READY(self) == -1)
10125 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010126
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010127 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010128 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010129 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010130 if (PyUnicode_IS_ASCII(self))
10131 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010132 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010133 PyUnicode_GET_LENGTH(self), maxcount
10134 );
10135 else
10136 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010137 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010138 PyUnicode_GET_LENGTH(self), maxcount
10139 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 case PyUnicode_2BYTE_KIND:
10141 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010142 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010143 PyUnicode_GET_LENGTH(self), maxcount
10144 );
10145 case PyUnicode_4BYTE_KIND:
10146 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010147 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010148 PyUnicode_GET_LENGTH(self), maxcount
10149 );
10150 default:
10151 assert(0);
10152 return NULL;
10153 }
10154
10155 if (PyUnicode_READY(substring) == -1)
10156 return NULL;
10157
10158 kind1 = PyUnicode_KIND(self);
10159 kind2 = PyUnicode_KIND(substring);
10160 kind = kind1 > kind2 ? kind1 : kind2;
10161 buf1 = PyUnicode_DATA(self);
10162 buf2 = PyUnicode_DATA(substring);
10163 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010164 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010165 if (!buf1)
10166 return NULL;
10167 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010168 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010169 if (!buf2) {
10170 if (kind1 != kind) PyMem_Free(buf1);
10171 return NULL;
10172 }
10173 len1 = PyUnicode_GET_LENGTH(self);
10174 len2 = PyUnicode_GET_LENGTH(substring);
10175
Benjamin Petersonead6b532011-12-20 17:23:42 -060010176 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010178 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10179 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010180 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010181 else
10182 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010183 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010184 break;
10185 case PyUnicode_2BYTE_KIND:
10186 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010187 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 break;
10189 case PyUnicode_4BYTE_KIND:
10190 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010191 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010192 break;
10193 default:
10194 out = NULL;
10195 }
10196 if (kind1 != kind)
10197 PyMem_Free(buf1);
10198 if (kind2 != kind)
10199 PyMem_Free(buf2);
10200 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010201}
10202
Alexander Belopolsky40018472011-02-26 01:02:56 +000010203static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010204rsplit(PyObject *self,
10205 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010206 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010207{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208 int kind1, kind2, kind;
10209 void *buf1, *buf2;
10210 Py_ssize_t len1, len2;
10211 PyObject* out;
10212
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010213 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010214 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010215
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010216 if (PyUnicode_READY(self) == -1)
10217 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010218
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010219 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010220 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010221 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010222 if (PyUnicode_IS_ASCII(self))
10223 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010224 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010225 PyUnicode_GET_LENGTH(self), maxcount
10226 );
10227 else
10228 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010229 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010230 PyUnicode_GET_LENGTH(self), maxcount
10231 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 case PyUnicode_2BYTE_KIND:
10233 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010234 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010235 PyUnicode_GET_LENGTH(self), maxcount
10236 );
10237 case PyUnicode_4BYTE_KIND:
10238 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010239 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 PyUnicode_GET_LENGTH(self), maxcount
10241 );
10242 default:
10243 assert(0);
10244 return NULL;
10245 }
10246
10247 if (PyUnicode_READY(substring) == -1)
10248 return NULL;
10249
10250 kind1 = PyUnicode_KIND(self);
10251 kind2 = PyUnicode_KIND(substring);
10252 kind = kind1 > kind2 ? kind1 : kind2;
10253 buf1 = PyUnicode_DATA(self);
10254 buf2 = PyUnicode_DATA(substring);
10255 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010256 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010257 if (!buf1)
10258 return NULL;
10259 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010260 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010261 if (!buf2) {
10262 if (kind1 != kind) PyMem_Free(buf1);
10263 return NULL;
10264 }
10265 len1 = PyUnicode_GET_LENGTH(self);
10266 len2 = PyUnicode_GET_LENGTH(substring);
10267
Benjamin Petersonead6b532011-12-20 17:23:42 -060010268 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010270 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10271 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010272 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010273 else
10274 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010275 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010276 break;
10277 case PyUnicode_2BYTE_KIND:
10278 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010279 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010280 break;
10281 case PyUnicode_4BYTE_KIND:
10282 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010283 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284 break;
10285 default:
10286 out = NULL;
10287 }
10288 if (kind1 != kind)
10289 PyMem_Free(buf1);
10290 if (kind2 != kind)
10291 PyMem_Free(buf2);
10292 return out;
10293}
10294
10295static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010296anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10297 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010298{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010299 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010301 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10302 return asciilib_find(buf1, len1, buf2, len2, offset);
10303 else
10304 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 case PyUnicode_2BYTE_KIND:
10306 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10307 case PyUnicode_4BYTE_KIND:
10308 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10309 }
10310 assert(0);
10311 return -1;
10312}
10313
10314static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010315anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10316 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010317{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010318 switch (kind) {
10319 case PyUnicode_1BYTE_KIND:
10320 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10321 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10322 else
10323 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10324 case PyUnicode_2BYTE_KIND:
10325 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10326 case PyUnicode_4BYTE_KIND:
10327 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10328 }
10329 assert(0);
10330 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010331}
10332
Alexander Belopolsky40018472011-02-26 01:02:56 +000010333static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010334replace(PyObject *self, PyObject *str1,
10335 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010336{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010337 PyObject *u;
10338 char *sbuf = PyUnicode_DATA(self);
10339 char *buf1 = PyUnicode_DATA(str1);
10340 char *buf2 = PyUnicode_DATA(str2);
10341 int srelease = 0, release1 = 0, release2 = 0;
10342 int skind = PyUnicode_KIND(self);
10343 int kind1 = PyUnicode_KIND(str1);
10344 int kind2 = PyUnicode_KIND(str2);
10345 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10346 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10347 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010348 int mayshrink;
10349 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010350
10351 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010352 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010353 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010354 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010355
Victor Stinner59de0ee2011-10-07 10:01:28 +020010356 if (str1 == str2)
10357 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010358 if (skind < kind1)
10359 /* substring too wide to be present */
10360 goto nothing;
10361
Victor Stinner49a0a212011-10-12 23:46:10 +020010362 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10363 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10364 /* Replacing str1 with str2 may cause a maxchar reduction in the
10365 result string. */
10366 mayshrink = (maxchar_str2 < maxchar);
10367 maxchar = Py_MAX(maxchar, maxchar_str2);
10368
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010369 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010370 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010371 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010372 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010373 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010374 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010375 Py_UCS4 u1, u2;
10376 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010377 Py_ssize_t index, pos;
10378 char *src;
10379
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010380 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010381 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10382 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010383 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010384 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010385 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010386 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010387 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010388 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010389 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010390
10391 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10392 index = 0;
10393 src = sbuf;
10394 while (--maxcount)
10395 {
10396 pos++;
10397 src += pos * PyUnicode_KIND(self);
10398 slen -= pos;
10399 index += pos;
10400 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10401 if (pos < 0)
10402 break;
10403 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10404 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010405 }
10406 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010407 int rkind = skind;
10408 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010409 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010410
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010411 if (kind1 < rkind) {
10412 /* widen substring */
10413 buf1 = _PyUnicode_AsKind(str1, rkind);
10414 if (!buf1) goto error;
10415 release1 = 1;
10416 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010417 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010418 if (i < 0)
10419 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010420 if (rkind > kind2) {
10421 /* widen replacement */
10422 buf2 = _PyUnicode_AsKind(str2, rkind);
10423 if (!buf2) goto error;
10424 release2 = 1;
10425 }
10426 else if (rkind < kind2) {
10427 /* widen self and buf1 */
10428 rkind = kind2;
10429 if (release1) PyMem_Free(buf1);
10430 sbuf = _PyUnicode_AsKind(self, rkind);
10431 if (!sbuf) goto error;
10432 srelease = 1;
10433 buf1 = _PyUnicode_AsKind(str1, rkind);
10434 if (!buf1) goto error;
10435 release1 = 1;
10436 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010437 u = PyUnicode_New(slen, maxchar);
10438 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010440 assert(PyUnicode_KIND(u) == rkind);
10441 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010442
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010443 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010444 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010445 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010446 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010447 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010449
10450 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010451 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010452 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010453 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010454 if (i == -1)
10455 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010456 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010457 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010458 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010459 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010460 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010461 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010462 }
10463 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010464 Py_ssize_t n, i, j, ires;
10465 Py_ssize_t product, new_size;
10466 int rkind = skind;
10467 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010468
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010469 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010470 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010471 buf1 = _PyUnicode_AsKind(str1, rkind);
10472 if (!buf1) goto error;
10473 release1 = 1;
10474 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010475 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010476 if (n == 0)
10477 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010478 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010479 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010480 buf2 = _PyUnicode_AsKind(str2, rkind);
10481 if (!buf2) goto error;
10482 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010483 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010485 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486 rkind = kind2;
10487 sbuf = _PyUnicode_AsKind(self, rkind);
10488 if (!sbuf) goto error;
10489 srelease = 1;
10490 if (release1) PyMem_Free(buf1);
10491 buf1 = _PyUnicode_AsKind(str1, rkind);
10492 if (!buf1) goto error;
10493 release1 = 1;
10494 }
10495 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10496 PyUnicode_GET_LENGTH(str1))); */
10497 product = n * (len2-len1);
10498 if ((product / (len2-len1)) != n) {
10499 PyErr_SetString(PyExc_OverflowError,
10500 "replace string is too long");
10501 goto error;
10502 }
10503 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010504 if (new_size == 0) {
10505 Py_INCREF(unicode_empty);
10506 u = unicode_empty;
10507 goto done;
10508 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10510 PyErr_SetString(PyExc_OverflowError,
10511 "replace string is too long");
10512 goto error;
10513 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010514 u = PyUnicode_New(new_size, maxchar);
10515 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010516 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010517 assert(PyUnicode_KIND(u) == rkind);
10518 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010519 ires = i = 0;
10520 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010521 while (n-- > 0) {
10522 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010523 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010524 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010525 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010526 if (j == -1)
10527 break;
10528 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010529 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010530 memcpy(res + rkind * ires,
10531 sbuf + rkind * i,
10532 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010533 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010534 }
10535 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010536 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010537 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010538 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010539 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010540 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010541 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010542 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010543 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010544 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010545 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010546 memcpy(res + rkind * ires,
10547 sbuf + rkind * i,
10548 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010549 }
10550 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010551 /* interleave */
10552 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010553 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010554 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010555 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010556 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010557 if (--n <= 0)
10558 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010559 memcpy(res + rkind * ires,
10560 sbuf + rkind * i,
10561 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010562 ires++;
10563 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010564 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010565 memcpy(res + rkind * ires,
10566 sbuf + rkind * i,
10567 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010568 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010569 }
10570
10571 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010572 unicode_adjust_maxchar(&u);
10573 if (u == NULL)
10574 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010575 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010576
10577 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010578 if (srelease)
10579 PyMem_FREE(sbuf);
10580 if (release1)
10581 PyMem_FREE(buf1);
10582 if (release2)
10583 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010584 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010585 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010586
Benjamin Peterson29060642009-01-31 22:14:21 +000010587 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010588 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010589 if (srelease)
10590 PyMem_FREE(sbuf);
10591 if (release1)
10592 PyMem_FREE(buf1);
10593 if (release2)
10594 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010595 return unicode_result_unchanged(self);
10596
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010597 error:
10598 if (srelease && sbuf)
10599 PyMem_FREE(sbuf);
10600 if (release1 && buf1)
10601 PyMem_FREE(buf1);
10602 if (release2 && buf2)
10603 PyMem_FREE(buf2);
10604 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010605}
10606
10607/* --- Unicode Object Methods --------------------------------------------- */
10608
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010609PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010610 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010611\n\
10612Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010613characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010614
10615static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010616unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010617{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010618 if (PyUnicode_READY(self) == -1)
10619 return NULL;
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010620 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010621}
10622
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010623PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010624 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010625\n\
10626Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010627have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010628
10629static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010630unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010631{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010632 if (PyUnicode_READY(self) == -1)
10633 return NULL;
10634 if (PyUnicode_GET_LENGTH(self) == 0)
10635 return unicode_result_unchanged(self);
10636 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010637}
10638
Benjamin Petersond5890c82012-01-14 13:23:30 -050010639PyDoc_STRVAR(casefold__doc__,
10640 "S.casefold() -> str\n\
10641\n\
10642Return a version of S suitable for caseless comparisons.");
10643
10644static PyObject *
10645unicode_casefold(PyObject *self)
10646{
10647 if (PyUnicode_READY(self) == -1)
10648 return NULL;
10649 if (PyUnicode_IS_ASCII(self))
10650 return ascii_upper_or_lower(self, 1);
10651 return case_operation(self, do_casefold);
10652}
10653
10654
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010655/* Argument converter. Coerces to a single unicode character */
10656
10657static int
10658convert_uc(PyObject *obj, void *addr)
10659{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010660 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010661 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010662
Benjamin Peterson14339b62009-01-31 16:36:08 +000010663 uniobj = PyUnicode_FromObject(obj);
10664 if (uniobj == NULL) {
10665 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010666 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010667 return 0;
10668 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010669 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010670 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010671 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010672 Py_DECREF(uniobj);
10673 return 0;
10674 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010675 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010676 Py_DECREF(uniobj);
10677 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010678}
10679
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010680PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010681 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010682\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010683Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010684done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010685
10686static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010687unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010688{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010689 Py_ssize_t marg, left;
10690 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010691 Py_UCS4 fillchar = ' ';
10692
Victor Stinnere9a29352011-10-01 02:14:59 +020010693 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010694 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010695
Benjamin Petersonbac79492012-01-14 13:34:47 -050010696 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010697 return NULL;
10698
Victor Stinnerc4b49542011-12-11 22:44:26 +010010699 if (PyUnicode_GET_LENGTH(self) >= width)
10700 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010701
Victor Stinnerc4b49542011-12-11 22:44:26 +010010702 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010703 left = marg / 2 + (marg & width & 1);
10704
Victor Stinner9310abb2011-10-05 00:59:23 +020010705 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010706}
10707
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010708/* This function assumes that str1 and str2 are readied by the caller. */
10709
Marc-André Lemburge5034372000-08-08 08:04:29 +000010710static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010711unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010712{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010713 int kind1, kind2;
10714 void *data1, *data2;
10715 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010716
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010717 kind1 = PyUnicode_KIND(str1);
10718 kind2 = PyUnicode_KIND(str2);
10719 data1 = PyUnicode_DATA(str1);
10720 data2 = PyUnicode_DATA(str2);
10721 len1 = PyUnicode_GET_LENGTH(str1);
10722 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010723
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010724 for (i = 0; i < len1 && i < len2; ++i) {
10725 Py_UCS4 c1, c2;
10726 c1 = PyUnicode_READ(kind1, data1, i);
10727 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010728
10729 if (c1 != c2)
10730 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010731 }
10732
10733 return (len1 < len2) ? -1 : (len1 != len2);
10734}
10735
Alexander Belopolsky40018472011-02-26 01:02:56 +000010736int
10737PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010738{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010739 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10740 if (PyUnicode_READY(left) == -1 ||
10741 PyUnicode_READY(right) == -1)
10742 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010743 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010744 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010745 PyErr_Format(PyExc_TypeError,
10746 "Can't compare %.100s and %.100s",
10747 left->ob_type->tp_name,
10748 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010749 return -1;
10750}
10751
Martin v. Löwis5b222132007-06-10 09:51:05 +000010752int
10753PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10754{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010755 Py_ssize_t i;
10756 int kind;
10757 void *data;
10758 Py_UCS4 chr;
10759
Victor Stinner910337b2011-10-03 03:20:16 +020010760 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010761 if (PyUnicode_READY(uni) == -1)
10762 return -1;
10763 kind = PyUnicode_KIND(uni);
10764 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010765 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010766 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10767 if (chr != str[i])
10768 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010769 /* This check keeps Python strings that end in '\0' from comparing equal
10770 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010771 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010772 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010773 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010774 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010775 return 0;
10776}
10777
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010778
Benjamin Peterson29060642009-01-31 22:14:21 +000010779#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010780 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010781
Alexander Belopolsky40018472011-02-26 01:02:56 +000010782PyObject *
10783PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010784{
10785 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010786
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010787 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10788 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010789 if (PyUnicode_READY(left) == -1 ||
10790 PyUnicode_READY(right) == -1)
10791 return NULL;
10792 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10793 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010794 if (op == Py_EQ) {
10795 Py_INCREF(Py_False);
10796 return Py_False;
10797 }
10798 if (op == Py_NE) {
10799 Py_INCREF(Py_True);
10800 return Py_True;
10801 }
10802 }
10803 if (left == right)
10804 result = 0;
10805 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010806 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010807
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010808 /* Convert the return value to a Boolean */
10809 switch (op) {
10810 case Py_EQ:
10811 v = TEST_COND(result == 0);
10812 break;
10813 case Py_NE:
10814 v = TEST_COND(result != 0);
10815 break;
10816 case Py_LE:
10817 v = TEST_COND(result <= 0);
10818 break;
10819 case Py_GE:
10820 v = TEST_COND(result >= 0);
10821 break;
10822 case Py_LT:
10823 v = TEST_COND(result == -1);
10824 break;
10825 case Py_GT:
10826 v = TEST_COND(result == 1);
10827 break;
10828 default:
10829 PyErr_BadArgument();
10830 return NULL;
10831 }
10832 Py_INCREF(v);
10833 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010834 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010835
Brian Curtindfc80e32011-08-10 20:28:54 -050010836 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010837}
10838
Alexander Belopolsky40018472011-02-26 01:02:56 +000010839int
10840PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010841{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010842 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010843 int kind1, kind2, kind;
10844 void *buf1, *buf2;
10845 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010846 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010847
10848 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010849 sub = PyUnicode_FromObject(element);
10850 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010851 PyErr_Format(PyExc_TypeError,
10852 "'in <string>' requires string as left operand, not %s",
10853 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010854 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010855 }
10856
Thomas Wouters477c8d52006-05-27 19:21:47 +000010857 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010858 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010859 Py_DECREF(sub);
10860 return -1;
10861 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010862 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10863 Py_DECREF(sub);
10864 Py_DECREF(str);
10865 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010866
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010867 kind1 = PyUnicode_KIND(str);
10868 kind2 = PyUnicode_KIND(sub);
10869 kind = kind1 > kind2 ? kind1 : kind2;
10870 buf1 = PyUnicode_DATA(str);
10871 buf2 = PyUnicode_DATA(sub);
10872 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010873 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010874 if (!buf1) {
10875 Py_DECREF(sub);
10876 return -1;
10877 }
10878 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010879 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010880 if (!buf2) {
10881 Py_DECREF(sub);
10882 if (kind1 != kind) PyMem_Free(buf1);
10883 return -1;
10884 }
10885 len1 = PyUnicode_GET_LENGTH(str);
10886 len2 = PyUnicode_GET_LENGTH(sub);
10887
Benjamin Petersonead6b532011-12-20 17:23:42 -060010888 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010889 case PyUnicode_1BYTE_KIND:
10890 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10891 break;
10892 case PyUnicode_2BYTE_KIND:
10893 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10894 break;
10895 case PyUnicode_4BYTE_KIND:
10896 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10897 break;
10898 default:
10899 result = -1;
10900 assert(0);
10901 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010902
10903 Py_DECREF(str);
10904 Py_DECREF(sub);
10905
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010906 if (kind1 != kind)
10907 PyMem_Free(buf1);
10908 if (kind2 != kind)
10909 PyMem_Free(buf2);
10910
Guido van Rossum403d68b2000-03-13 15:55:09 +000010911 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010912}
10913
Guido van Rossumd57fd912000-03-10 22:53:23 +000010914/* Concat to string or Unicode object giving a new Unicode object. */
10915
Alexander Belopolsky40018472011-02-26 01:02:56 +000010916PyObject *
10917PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010918{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010919 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010920 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010921 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010922
10923 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010924 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010925 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010926 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010927 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010928 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010929 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010930
10931 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010932 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010933 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010934 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010935 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010936 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010937 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010938 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010939 }
10940
Victor Stinner488fa492011-12-12 00:01:39 +010010941 u_len = PyUnicode_GET_LENGTH(u);
10942 v_len = PyUnicode_GET_LENGTH(v);
10943 if (u_len > PY_SSIZE_T_MAX - v_len) {
10944 PyErr_SetString(PyExc_OverflowError,
10945 "strings are too large to concat");
10946 goto onError;
10947 }
10948 new_len = u_len + v_len;
10949
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010950 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010951 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10952 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010953
Guido van Rossumd57fd912000-03-10 22:53:23 +000010954 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010955 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010956 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010957 goto onError;
Victor Stinner488fa492011-12-12 00:01:39 +010010958 copy_characters(w, 0, u, 0, u_len);
10959 copy_characters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010960 Py_DECREF(u);
10961 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010962 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010963 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010964
Benjamin Peterson29060642009-01-31 22:14:21 +000010965 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010966 Py_XDECREF(u);
10967 Py_XDECREF(v);
10968 return NULL;
10969}
10970
Walter Dörwald1ab83302007-05-18 17:15:44 +000010971void
Victor Stinner23e56682011-10-03 03:54:37 +020010972PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010973{
Victor Stinner23e56682011-10-03 03:54:37 +020010974 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010975 Py_UCS4 maxchar, maxchar2;
10976 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010977
10978 if (p_left == NULL) {
10979 if (!PyErr_Occurred())
10980 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010981 return;
10982 }
Victor Stinner23e56682011-10-03 03:54:37 +020010983 left = *p_left;
10984 if (right == NULL || !PyUnicode_Check(left)) {
10985 if (!PyErr_Occurred())
10986 PyErr_BadInternalCall();
10987 goto error;
10988 }
10989
Benjamin Petersonbac79492012-01-14 13:34:47 -050010990 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010991 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010992 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010993 goto error;
10994
Victor Stinner488fa492011-12-12 00:01:39 +010010995 /* Shortcuts */
10996 if (left == unicode_empty) {
10997 Py_DECREF(left);
10998 Py_INCREF(right);
10999 *p_left = right;
11000 return;
11001 }
11002 if (right == unicode_empty)
11003 return;
11004
11005 left_len = PyUnicode_GET_LENGTH(left);
11006 right_len = PyUnicode_GET_LENGTH(right);
11007 if (left_len > PY_SSIZE_T_MAX - right_len) {
11008 PyErr_SetString(PyExc_OverflowError,
11009 "strings are too large to concat");
11010 goto error;
11011 }
11012 new_len = left_len + right_len;
11013
11014 if (unicode_modifiable(left)
11015 && PyUnicode_CheckExact(right)
11016 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011017 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11018 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011019 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011020 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011021 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11022 {
11023 /* append inplace */
11024 if (unicode_resize(p_left, new_len) != 0) {
11025 /* XXX if _PyUnicode_Resize() fails, 'left' has been
11026 * deallocated so it cannot be put back into
11027 * 'variable'. The MemoryError is raised when there
11028 * is no value in 'variable', which might (very
11029 * remotely) be a cause of incompatibilities.
11030 */
11031 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020011032 }
Victor Stinner488fa492011-12-12 00:01:39 +010011033 /* copy 'right' into the newly allocated area of 'left' */
11034 copy_characters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011035 }
Victor Stinner488fa492011-12-12 00:01:39 +010011036 else {
11037 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11038 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11039 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011040
Victor Stinner488fa492011-12-12 00:01:39 +010011041 /* Concat the two Unicode strings */
11042 res = PyUnicode_New(new_len, maxchar);
11043 if (res == NULL)
11044 goto error;
11045 copy_characters(res, 0, left, 0, left_len);
11046 copy_characters(res, left_len, right, 0, right_len);
11047 Py_DECREF(left);
11048 *p_left = res;
11049 }
11050 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011051 return;
11052
11053error:
Victor Stinner488fa492011-12-12 00:01:39 +010011054 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011055}
11056
11057void
11058PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11059{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011060 PyUnicode_Append(pleft, right);
11061 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011062}
11063
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011064PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011065 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011066\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011067Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011068string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011069interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011070
11071static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011072unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011073{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011074 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011075 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011076 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011077 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011078 int kind1, kind2, kind;
11079 void *buf1, *buf2;
11080 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011081
Jesus Ceaac451502011-04-20 17:09:23 +020011082 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11083 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011084 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011085
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011086 kind1 = PyUnicode_KIND(self);
11087 kind2 = PyUnicode_KIND(substring);
11088 kind = kind1 > kind2 ? kind1 : kind2;
11089 buf1 = PyUnicode_DATA(self);
11090 buf2 = PyUnicode_DATA(substring);
11091 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011092 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011093 if (!buf1) {
11094 Py_DECREF(substring);
11095 return NULL;
11096 }
11097 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011098 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011099 if (!buf2) {
11100 Py_DECREF(substring);
11101 if (kind1 != kind) PyMem_Free(buf1);
11102 return NULL;
11103 }
11104 len1 = PyUnicode_GET_LENGTH(self);
11105 len2 = PyUnicode_GET_LENGTH(substring);
11106
11107 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060011108 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011109 case PyUnicode_1BYTE_KIND:
11110 iresult = ucs1lib_count(
11111 ((Py_UCS1*)buf1) + start, end - start,
11112 buf2, len2, PY_SSIZE_T_MAX
11113 );
11114 break;
11115 case PyUnicode_2BYTE_KIND:
11116 iresult = ucs2lib_count(
11117 ((Py_UCS2*)buf1) + start, end - start,
11118 buf2, len2, PY_SSIZE_T_MAX
11119 );
11120 break;
11121 case PyUnicode_4BYTE_KIND:
11122 iresult = ucs4lib_count(
11123 ((Py_UCS4*)buf1) + start, end - start,
11124 buf2, len2, PY_SSIZE_T_MAX
11125 );
11126 break;
11127 default:
11128 assert(0); iresult = 0;
11129 }
11130
11131 result = PyLong_FromSsize_t(iresult);
11132
11133 if (kind1 != kind)
11134 PyMem_Free(buf1);
11135 if (kind2 != kind)
11136 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011137
11138 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011139
Guido van Rossumd57fd912000-03-10 22:53:23 +000011140 return result;
11141}
11142
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011143PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011144 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011145\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011146Encode S using the codec registered for encoding. Default encoding\n\
11147is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011148handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011149a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11150'xmlcharrefreplace' as well as any other name registered with\n\
11151codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011152
11153static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011154unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011155{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011156 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011157 char *encoding = NULL;
11158 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011159
Benjamin Peterson308d6372009-09-18 21:42:35 +000011160 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11161 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011162 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011163 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011164}
11165
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011166PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011167 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011168\n\
11169Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011170If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011171
11172static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011173unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011175 Py_ssize_t i, j, line_pos, src_len, incr;
11176 Py_UCS4 ch;
11177 PyObject *u;
11178 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011180 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011181 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182
11183 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011184 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011185
Antoine Pitrou22425222011-10-04 19:10:51 +020011186 if (PyUnicode_READY(self) == -1)
11187 return NULL;
11188
Thomas Wouters7e474022000-07-16 12:04:32 +000011189 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011190 src_len = PyUnicode_GET_LENGTH(self);
11191 i = j = line_pos = 0;
11192 kind = PyUnicode_KIND(self);
11193 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011194 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011195 for (; i < src_len; i++) {
11196 ch = PyUnicode_READ(kind, src_data, i);
11197 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011198 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011199 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011200 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011201 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011202 goto overflow;
11203 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011204 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011205 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011206 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011208 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011209 goto overflow;
11210 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011211 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011212 if (ch == '\n' || ch == '\r')
11213 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011214 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011215 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011216 if (!found)
11217 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011218
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011220 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221 if (!u)
11222 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011223 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224
Antoine Pitroue71d5742011-10-04 15:55:09 +020011225 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011226
Antoine Pitroue71d5742011-10-04 15:55:09 +020011227 for (; i < src_len; i++) {
11228 ch = PyUnicode_READ(kind, src_data, i);
11229 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011230 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011231 incr = tabsize - (line_pos % tabsize);
11232 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011233 FILL(kind, dest_data, ' ', j, incr);
11234 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011235 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011236 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011237 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011238 line_pos++;
11239 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011240 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011241 if (ch == '\n' || ch == '\r')
11242 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011243 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011244 }
11245 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011246 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011247
Antoine Pitroue71d5742011-10-04 15:55:09 +020011248 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011249 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11250 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251}
11252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011253PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011254 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011255\n\
11256Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011257such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011258arguments start and end are interpreted as in slice notation.\n\
11259\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011260Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011261
11262static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011263unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011264{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011265 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011266 Py_ssize_t start;
11267 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011268 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011269
Jesus Ceaac451502011-04-20 17:09:23 +020011270 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11271 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011272 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011273
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011274 if (PyUnicode_READY(self) == -1)
11275 return NULL;
11276 if (PyUnicode_READY(substring) == -1)
11277 return NULL;
11278
Victor Stinner7931d9a2011-11-04 00:22:48 +010011279 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011280
11281 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011282
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011283 if (result == -2)
11284 return NULL;
11285
Christian Heimes217cfd12007-12-02 14:31:20 +000011286 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011287}
11288
11289static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011290unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011291{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011292 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11293 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011294 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011295 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011296}
11297
Guido van Rossumc2504932007-09-18 19:42:40 +000011298/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011299 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011300static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011301unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011302{
Guido van Rossumc2504932007-09-18 19:42:40 +000011303 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011304 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011305
Benjamin Peterson69e97272012-02-21 11:08:50 -050011306 assert(_Py_HashSecret_Initialized);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011307 if (_PyUnicode_HASH(self) != -1)
11308 return _PyUnicode_HASH(self);
11309 if (PyUnicode_READY(self) == -1)
11310 return -1;
11311 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011312 /*
11313 We make the hash of the empty string be 0, rather than using
11314 (prefix ^ suffix), since this slightly obfuscates the hash secret
11315 */
11316 if (len == 0) {
11317 _PyUnicode_HASH(self) = 0;
11318 return 0;
11319 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011320
11321 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011322#define HASH(P) \
11323 x ^= (Py_uhash_t) *P << 7; \
11324 while (--len >= 0) \
11325 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011326
Georg Brandl2fb477c2012-02-21 00:33:36 +010011327 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011328 switch (PyUnicode_KIND(self)) {
11329 case PyUnicode_1BYTE_KIND: {
11330 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11331 HASH(c);
11332 break;
11333 }
11334 case PyUnicode_2BYTE_KIND: {
11335 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11336 HASH(s);
11337 break;
11338 }
11339 default: {
11340 Py_UCS4 *l;
11341 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11342 "Impossible switch case in unicode_hash");
11343 l = PyUnicode_4BYTE_DATA(self);
11344 HASH(l);
11345 break;
11346 }
11347 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011348 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11349 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011350
Guido van Rossumc2504932007-09-18 19:42:40 +000011351 if (x == -1)
11352 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011353 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011354 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011355}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011356#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011357
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011358PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011359 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011360\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011361Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011362
11363static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011364unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011365{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011366 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011367 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011368 Py_ssize_t start;
11369 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011370
Jesus Ceaac451502011-04-20 17:09:23 +020011371 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11372 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011373 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011374
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011375 if (PyUnicode_READY(self) == -1)
11376 return NULL;
11377 if (PyUnicode_READY(substring) == -1)
11378 return NULL;
11379
Victor Stinner7931d9a2011-11-04 00:22:48 +010011380 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011381
11382 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011383
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011384 if (result == -2)
11385 return NULL;
11386
Guido van Rossumd57fd912000-03-10 22:53:23 +000011387 if (result < 0) {
11388 PyErr_SetString(PyExc_ValueError, "substring not found");
11389 return NULL;
11390 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011391
Christian Heimes217cfd12007-12-02 14:31:20 +000011392 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011393}
11394
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011395PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011396 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011397\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011398Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011399at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011400
11401static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011402unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011403{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011404 Py_ssize_t i, length;
11405 int kind;
11406 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407 int cased;
11408
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011409 if (PyUnicode_READY(self) == -1)
11410 return NULL;
11411 length = PyUnicode_GET_LENGTH(self);
11412 kind = PyUnicode_KIND(self);
11413 data = PyUnicode_DATA(self);
11414
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011416 if (length == 1)
11417 return PyBool_FromLong(
11418 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011420 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011421 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011422 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011423
Guido van Rossumd57fd912000-03-10 22:53:23 +000011424 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011425 for (i = 0; i < length; i++) {
11426 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011427
Benjamin Peterson29060642009-01-31 22:14:21 +000011428 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11429 return PyBool_FromLong(0);
11430 else if (!cased && Py_UNICODE_ISLOWER(ch))
11431 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011433 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011434}
11435
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011436PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011437 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011438\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011439Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011440at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011441
11442static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011443unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011444{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011445 Py_ssize_t i, length;
11446 int kind;
11447 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011448 int cased;
11449
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011450 if (PyUnicode_READY(self) == -1)
11451 return NULL;
11452 length = PyUnicode_GET_LENGTH(self);
11453 kind = PyUnicode_KIND(self);
11454 data = PyUnicode_DATA(self);
11455
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011457 if (length == 1)
11458 return PyBool_FromLong(
11459 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011460
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011461 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011462 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011463 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011464
Guido van Rossumd57fd912000-03-10 22:53:23 +000011465 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011466 for (i = 0; i < length; i++) {
11467 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011468
Benjamin Peterson29060642009-01-31 22:14:21 +000011469 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11470 return PyBool_FromLong(0);
11471 else if (!cased && Py_UNICODE_ISUPPER(ch))
11472 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011473 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011474 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475}
11476
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011477PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011478 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011479\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011480Return True if S is a titlecased string and there is at least one\n\
11481character in S, i.e. upper- and titlecase characters may only\n\
11482follow uncased characters and lowercase characters only cased ones.\n\
11483Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484
11485static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011486unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011487{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011488 Py_ssize_t i, length;
11489 int kind;
11490 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491 int cased, previous_is_cased;
11492
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011493 if (PyUnicode_READY(self) == -1)
11494 return NULL;
11495 length = PyUnicode_GET_LENGTH(self);
11496 kind = PyUnicode_KIND(self);
11497 data = PyUnicode_DATA(self);
11498
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011500 if (length == 1) {
11501 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11502 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11503 (Py_UNICODE_ISUPPER(ch) != 0));
11504 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011505
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011506 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011507 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011508 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011509
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510 cased = 0;
11511 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011512 for (i = 0; i < length; i++) {
11513 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011514
Benjamin Peterson29060642009-01-31 22:14:21 +000011515 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11516 if (previous_is_cased)
11517 return PyBool_FromLong(0);
11518 previous_is_cased = 1;
11519 cased = 1;
11520 }
11521 else if (Py_UNICODE_ISLOWER(ch)) {
11522 if (!previous_is_cased)
11523 return PyBool_FromLong(0);
11524 previous_is_cased = 1;
11525 cased = 1;
11526 }
11527 else
11528 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011530 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011531}
11532
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011533PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011534 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011536Return True if all characters in S are whitespace\n\
11537and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538
11539static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011540unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011542 Py_ssize_t i, length;
11543 int kind;
11544 void *data;
11545
11546 if (PyUnicode_READY(self) == -1)
11547 return NULL;
11548 length = PyUnicode_GET_LENGTH(self);
11549 kind = PyUnicode_KIND(self);
11550 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011551
Guido van Rossumd57fd912000-03-10 22:53:23 +000011552 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011553 if (length == 1)
11554 return PyBool_FromLong(
11555 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011556
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011557 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011558 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011559 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011560
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011561 for (i = 0; i < length; i++) {
11562 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011563 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011564 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011565 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011566 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567}
11568
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011569PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011570 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011571\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011572Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011573and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011574
11575static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011576unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011577{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011578 Py_ssize_t i, length;
11579 int kind;
11580 void *data;
11581
11582 if (PyUnicode_READY(self) == -1)
11583 return NULL;
11584 length = PyUnicode_GET_LENGTH(self);
11585 kind = PyUnicode_KIND(self);
11586 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011587
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011588 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011589 if (length == 1)
11590 return PyBool_FromLong(
11591 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011592
11593 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011594 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011595 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011596
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011597 for (i = 0; i < length; i++) {
11598 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011599 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011600 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011601 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011602}
11603
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011604PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011605 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011606\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011607Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011608and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011609
11610static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011611unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011612{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011613 int kind;
11614 void *data;
11615 Py_ssize_t len, i;
11616
11617 if (PyUnicode_READY(self) == -1)
11618 return NULL;
11619
11620 kind = PyUnicode_KIND(self);
11621 data = PyUnicode_DATA(self);
11622 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011623
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011624 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011625 if (len == 1) {
11626 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11627 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11628 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011629
11630 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011631 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011632 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011634 for (i = 0; i < len; i++) {
11635 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011636 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011637 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011638 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011639 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011640}
11641
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011642PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011643 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011644\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011645Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011646False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011647
11648static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011649unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011650{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011651 Py_ssize_t i, length;
11652 int kind;
11653 void *data;
11654
11655 if (PyUnicode_READY(self) == -1)
11656 return NULL;
11657 length = PyUnicode_GET_LENGTH(self);
11658 kind = PyUnicode_KIND(self);
11659 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011660
Guido van Rossumd57fd912000-03-10 22:53:23 +000011661 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011662 if (length == 1)
11663 return PyBool_FromLong(
11664 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011665
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011666 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011667 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011668 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011669
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011670 for (i = 0; i < length; i++) {
11671 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011672 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011673 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011674 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675}
11676
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011677PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011678 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011679\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011680Return True if all characters in S are digits\n\
11681and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011682
11683static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011684unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011685{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011686 Py_ssize_t i, length;
11687 int kind;
11688 void *data;
11689
11690 if (PyUnicode_READY(self) == -1)
11691 return NULL;
11692 length = PyUnicode_GET_LENGTH(self);
11693 kind = PyUnicode_KIND(self);
11694 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695
Guido van Rossumd57fd912000-03-10 22:53:23 +000011696 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011697 if (length == 1) {
11698 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11699 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11700 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011702 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011703 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011704 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011705
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011706 for (i = 0; i < length; i++) {
11707 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011708 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011709 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011710 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011711}
11712
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011713PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011714 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011715\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011716Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011717False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011718
11719static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011720unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011722 Py_ssize_t i, length;
11723 int kind;
11724 void *data;
11725
11726 if (PyUnicode_READY(self) == -1)
11727 return NULL;
11728 length = PyUnicode_GET_LENGTH(self);
11729 kind = PyUnicode_KIND(self);
11730 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011731
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011733 if (length == 1)
11734 return PyBool_FromLong(
11735 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011736
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011737 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011738 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011739 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011740
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011741 for (i = 0; i < length; i++) {
11742 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011743 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011744 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011745 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011746}
11747
Martin v. Löwis47383402007-08-15 07:32:56 +000011748int
11749PyUnicode_IsIdentifier(PyObject *self)
11750{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011751 int kind;
11752 void *data;
11753 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011754 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011755
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011756 if (PyUnicode_READY(self) == -1) {
11757 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011758 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011759 }
11760
11761 /* Special case for empty strings */
11762 if (PyUnicode_GET_LENGTH(self) == 0)
11763 return 0;
11764 kind = PyUnicode_KIND(self);
11765 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011766
11767 /* PEP 3131 says that the first character must be in
11768 XID_Start and subsequent characters in XID_Continue,
11769 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011770 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011771 letters, digits, underscore). However, given the current
11772 definition of XID_Start and XID_Continue, it is sufficient
11773 to check just for these, except that _ must be allowed
11774 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011775 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011776 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011777 return 0;
11778
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011779 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011780 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011781 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011782 return 1;
11783}
11784
11785PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011786 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011787\n\
11788Return True if S is a valid identifier according\n\
11789to the language definition.");
11790
11791static PyObject*
11792unicode_isidentifier(PyObject *self)
11793{
11794 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11795}
11796
Georg Brandl559e5d72008-06-11 18:37:52 +000011797PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011798 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011799\n\
11800Return True if all characters in S are considered\n\
11801printable in repr() or S is empty, False otherwise.");
11802
11803static PyObject*
11804unicode_isprintable(PyObject *self)
11805{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011806 Py_ssize_t i, length;
11807 int kind;
11808 void *data;
11809
11810 if (PyUnicode_READY(self) == -1)
11811 return NULL;
11812 length = PyUnicode_GET_LENGTH(self);
11813 kind = PyUnicode_KIND(self);
11814 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011815
11816 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011817 if (length == 1)
11818 return PyBool_FromLong(
11819 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011820
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011821 for (i = 0; i < length; i++) {
11822 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011823 Py_RETURN_FALSE;
11824 }
11825 }
11826 Py_RETURN_TRUE;
11827}
11828
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011829PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011830 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011831\n\
11832Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011833iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011834
11835static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011836unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011837{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011838 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011839}
11840
Martin v. Löwis18e16552006-02-15 17:27:45 +000011841static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011842unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011843{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011844 if (PyUnicode_READY(self) == -1)
11845 return -1;
11846 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011847}
11848
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011849PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011850 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011851\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011852Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011853done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011854
11855static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011856unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011857{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011858 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011859 Py_UCS4 fillchar = ' ';
11860
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011861 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011862 return NULL;
11863
Benjamin Petersonbac79492012-01-14 13:34:47 -050011864 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011865 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866
Victor Stinnerc4b49542011-12-11 22:44:26 +010011867 if (PyUnicode_GET_LENGTH(self) >= width)
11868 return unicode_result_unchanged(self);
11869
11870 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011871}
11872
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011873PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011874 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011875\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011876Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011877
11878static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011879unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011880{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011881 if (PyUnicode_READY(self) == -1)
11882 return NULL;
11883 if (PyUnicode_IS_ASCII(self))
11884 return ascii_upper_or_lower(self, 1);
11885 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011886}
11887
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011888#define LEFTSTRIP 0
11889#define RIGHTSTRIP 1
11890#define BOTHSTRIP 2
11891
11892/* Arrays indexed by above */
11893static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11894
11895#define STRIPNAME(i) (stripformat[i]+3)
11896
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011897/* externally visible for str.strip(unicode) */
11898PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011899_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011900{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011901 void *data;
11902 int kind;
11903 Py_ssize_t i, j, len;
11904 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011905
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011906 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11907 return NULL;
11908
11909 kind = PyUnicode_KIND(self);
11910 data = PyUnicode_DATA(self);
11911 len = PyUnicode_GET_LENGTH(self);
11912 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11913 PyUnicode_DATA(sepobj),
11914 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011915
Benjamin Peterson14339b62009-01-31 16:36:08 +000011916 i = 0;
11917 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011918 while (i < len &&
11919 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011920 i++;
11921 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011922 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011923
Benjamin Peterson14339b62009-01-31 16:36:08 +000011924 j = len;
11925 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011926 do {
11927 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011928 } while (j >= i &&
11929 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011930 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011931 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011932
Victor Stinner7931d9a2011-11-04 00:22:48 +010011933 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011934}
11935
11936PyObject*
11937PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11938{
11939 unsigned char *data;
11940 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011941 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011942
Victor Stinnerde636f32011-10-01 03:55:54 +020011943 if (PyUnicode_READY(self) == -1)
11944 return NULL;
11945
11946 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11947
Victor Stinner12bab6d2011-10-01 01:53:49 +020011948 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Victor Stinnerc4b49542011-12-11 22:44:26 +010011949 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011950
Victor Stinner12bab6d2011-10-01 01:53:49 +020011951 length = end - start;
11952 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011953 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011954
Victor Stinnerde636f32011-10-01 03:55:54 +020011955 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011956 PyErr_SetString(PyExc_IndexError, "string index out of range");
11957 return NULL;
11958 }
11959
Victor Stinnerb9275c12011-10-05 14:01:42 +020011960 if (PyUnicode_IS_ASCII(self)) {
11961 kind = PyUnicode_KIND(self);
11962 data = PyUnicode_1BYTE_DATA(self);
11963 return unicode_fromascii(data + start, length);
11964 }
11965 else {
11966 kind = PyUnicode_KIND(self);
11967 data = PyUnicode_1BYTE_DATA(self);
11968 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011969 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011970 length);
11971 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011972}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011973
11974static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011975do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011976{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011977 int kind;
11978 void *data;
11979 Py_ssize_t len, i, j;
11980
11981 if (PyUnicode_READY(self) == -1)
11982 return NULL;
11983
11984 kind = PyUnicode_KIND(self);
11985 data = PyUnicode_DATA(self);
11986 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011987
Benjamin Peterson14339b62009-01-31 16:36:08 +000011988 i = 0;
11989 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011990 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011991 i++;
11992 }
11993 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011994
Benjamin Peterson14339b62009-01-31 16:36:08 +000011995 j = len;
11996 if (striptype != LEFTSTRIP) {
11997 do {
11998 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011999 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012000 j++;
12001 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012002
Victor Stinner7931d9a2011-11-04 00:22:48 +010012003 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012004}
12005
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012006
12007static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012008do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012009{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012010 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012011
Benjamin Peterson14339b62009-01-31 16:36:08 +000012012 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
12013 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012014
Benjamin Peterson14339b62009-01-31 16:36:08 +000012015 if (sep != NULL && sep != Py_None) {
12016 if (PyUnicode_Check(sep))
12017 return _PyUnicode_XStrip(self, striptype, sep);
12018 else {
12019 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012020 "%s arg must be None or str",
12021 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012022 return NULL;
12023 }
12024 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012025
Benjamin Peterson14339b62009-01-31 16:36:08 +000012026 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012027}
12028
12029
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012030PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012031 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012032\n\
12033Return a copy of the string S with leading and trailing\n\
12034whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012035If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012036
12037static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012038unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012039{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012040 if (PyTuple_GET_SIZE(args) == 0)
12041 return do_strip(self, BOTHSTRIP); /* Common case */
12042 else
12043 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012044}
12045
12046
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012047PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012048 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012049\n\
12050Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012051If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012052
12053static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012054unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012055{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012056 if (PyTuple_GET_SIZE(args) == 0)
12057 return do_strip(self, LEFTSTRIP); /* Common case */
12058 else
12059 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012060}
12061
12062
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012063PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012064 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012065\n\
12066Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012067If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012068
12069static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012070unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012071{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012072 if (PyTuple_GET_SIZE(args) == 0)
12073 return do_strip(self, RIGHTSTRIP); /* Common case */
12074 else
12075 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012076}
12077
12078
Guido van Rossumd57fd912000-03-10 22:53:23 +000012079static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012080unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012081{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012082 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012083 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012084
Georg Brandl222de0f2009-04-12 12:01:50 +000012085 if (len < 1) {
12086 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020012087 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000012088 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012089
Victor Stinnerc4b49542011-12-11 22:44:26 +010012090 /* no repeat, return original string */
12091 if (len == 1)
12092 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012093
Benjamin Petersonbac79492012-01-14 13:34:47 -050012094 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012095 return NULL;
12096
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012097 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012098 PyErr_SetString(PyExc_OverflowError,
12099 "repeated string is too long");
12100 return NULL;
12101 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012102 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012103
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012104 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012105 if (!u)
12106 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012107 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012108
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012109 if (PyUnicode_GET_LENGTH(str) == 1) {
12110 const int kind = PyUnicode_KIND(str);
12111 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012112 if (kind == PyUnicode_1BYTE_KIND) {
12113 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012114 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012115 }
12116 else if (kind == PyUnicode_2BYTE_KIND) {
12117 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012118 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012119 ucs2[n] = fill_char;
12120 } else {
12121 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12122 assert(kind == PyUnicode_4BYTE_KIND);
12123 for (n = 0; n < len; ++n)
12124 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012125 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012126 }
12127 else {
12128 /* number of characters copied this far */
12129 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012130 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012131 char *to = (char *) PyUnicode_DATA(u);
12132 Py_MEMCPY(to, PyUnicode_DATA(str),
12133 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012134 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012135 n = (done <= nchars-done) ? done : nchars-done;
12136 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012137 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012138 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012139 }
12140
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012141 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012142 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012143}
12144
Alexander Belopolsky40018472011-02-26 01:02:56 +000012145PyObject *
12146PyUnicode_Replace(PyObject *obj,
12147 PyObject *subobj,
12148 PyObject *replobj,
12149 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012150{
12151 PyObject *self;
12152 PyObject *str1;
12153 PyObject *str2;
12154 PyObject *result;
12155
12156 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012157 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012158 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012159 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012160 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012161 Py_DECREF(self);
12162 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012163 }
12164 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012165 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012166 Py_DECREF(self);
12167 Py_DECREF(str1);
12168 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012169 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012170 if (PyUnicode_READY(self) == -1 ||
12171 PyUnicode_READY(str1) == -1 ||
12172 PyUnicode_READY(str2) == -1)
12173 result = NULL;
12174 else
12175 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012176 Py_DECREF(self);
12177 Py_DECREF(str1);
12178 Py_DECREF(str2);
12179 return result;
12180}
12181
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012182PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012183 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012184\n\
12185Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012186old replaced by new. If the optional argument count is\n\
12187given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188
12189static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012190unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012191{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012192 PyObject *str1;
12193 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012194 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012195 PyObject *result;
12196
Martin v. Löwis18e16552006-02-15 17:27:45 +000012197 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012198 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012199 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012200 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012201 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012202 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012203 return NULL;
12204 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012205 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012206 Py_DECREF(str1);
12207 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012208 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012209 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12210 result = NULL;
12211 else
12212 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012213
12214 Py_DECREF(str1);
12215 Py_DECREF(str2);
12216 return result;
12217}
12218
Alexander Belopolsky40018472011-02-26 01:02:56 +000012219static PyObject *
12220unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012221{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012222 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012223 Py_ssize_t isize;
12224 Py_ssize_t osize, squote, dquote, i, o;
12225 Py_UCS4 max, quote;
12226 int ikind, okind;
12227 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012228
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012229 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012230 return NULL;
12231
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012232 isize = PyUnicode_GET_LENGTH(unicode);
12233 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012234
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012235 /* Compute length of output, quote characters, and
12236 maximum character */
12237 osize = 2; /* quotes */
12238 max = 127;
12239 squote = dquote = 0;
12240 ikind = PyUnicode_KIND(unicode);
12241 for (i = 0; i < isize; i++) {
12242 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12243 switch (ch) {
12244 case '\'': squote++; osize++; break;
12245 case '"': dquote++; osize++; break;
12246 case '\\': case '\t': case '\r': case '\n':
12247 osize += 2; break;
12248 default:
12249 /* Fast-path ASCII */
12250 if (ch < ' ' || ch == 0x7f)
12251 osize += 4; /* \xHH */
12252 else if (ch < 0x7f)
12253 osize++;
12254 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12255 osize++;
12256 max = ch > max ? ch : max;
12257 }
12258 else if (ch < 0x100)
12259 osize += 4; /* \xHH */
12260 else if (ch < 0x10000)
12261 osize += 6; /* \uHHHH */
12262 else
12263 osize += 10; /* \uHHHHHHHH */
12264 }
12265 }
12266
12267 quote = '\'';
12268 if (squote) {
12269 if (dquote)
12270 /* Both squote and dquote present. Use squote,
12271 and escape them */
12272 osize += squote;
12273 else
12274 quote = '"';
12275 }
12276
12277 repr = PyUnicode_New(osize, max);
12278 if (repr == NULL)
12279 return NULL;
12280 okind = PyUnicode_KIND(repr);
12281 odata = PyUnicode_DATA(repr);
12282
12283 PyUnicode_WRITE(okind, odata, 0, quote);
12284 PyUnicode_WRITE(okind, odata, osize-1, quote);
12285
12286 for (i = 0, o = 1; i < isize; i++) {
12287 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012288
12289 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012290 if ((ch == quote) || (ch == '\\')) {
12291 PyUnicode_WRITE(okind, odata, o++, '\\');
12292 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012293 continue;
12294 }
12295
Benjamin Peterson29060642009-01-31 22:14:21 +000012296 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012297 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012298 PyUnicode_WRITE(okind, odata, o++, '\\');
12299 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012300 }
12301 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012302 PyUnicode_WRITE(okind, odata, o++, '\\');
12303 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012304 }
12305 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012306 PyUnicode_WRITE(okind, odata, o++, '\\');
12307 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012308 }
12309
12310 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012311 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012312 PyUnicode_WRITE(okind, odata, o++, '\\');
12313 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012314 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12315 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012316 }
12317
Georg Brandl559e5d72008-06-11 18:37:52 +000012318 /* Copy ASCII characters as-is */
12319 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012320 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012321 }
12322
Benjamin Peterson29060642009-01-31 22:14:21 +000012323 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012324 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012325 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012326 (categories Z* and C* except ASCII space)
12327 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012328 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012329 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012330 if (ch <= 0xff) {
12331 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]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012335 }
12336 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012337 else if (ch >= 0x10000) {
12338 PyUnicode_WRITE(okind, odata, o++, '\\');
12339 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012340 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12341 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12342 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12343 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12344 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12345 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12346 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12347 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012348 }
12349 /* Map 16-bit characters to '\uxxxx' */
12350 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012351 PyUnicode_WRITE(okind, odata, o++, '\\');
12352 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012353 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12354 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12355 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12356 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012357 }
12358 }
12359 /* Copy characters as-is */
12360 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012361 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012362 }
12363 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012364 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012365 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012366 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012367 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012368}
12369
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012370PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012371 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012372\n\
12373Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012374such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012375arguments start and end are interpreted as in slice notation.\n\
12376\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012377Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012378
12379static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012380unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012381{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012382 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012383 Py_ssize_t start;
12384 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012385 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012386
Jesus Ceaac451502011-04-20 17:09:23 +020012387 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12388 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012389 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012390
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012391 if (PyUnicode_READY(self) == -1)
12392 return NULL;
12393 if (PyUnicode_READY(substring) == -1)
12394 return NULL;
12395
Victor Stinner7931d9a2011-11-04 00:22:48 +010012396 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012397
12398 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012399
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012400 if (result == -2)
12401 return NULL;
12402
Christian Heimes217cfd12007-12-02 14:31:20 +000012403 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012404}
12405
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012406PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012407 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012408\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012409Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012410
12411static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012412unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012413{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012414 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012415 Py_ssize_t start;
12416 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012417 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012418
Jesus Ceaac451502011-04-20 17:09:23 +020012419 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12420 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012421 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012422
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012423 if (PyUnicode_READY(self) == -1)
12424 return NULL;
12425 if (PyUnicode_READY(substring) == -1)
12426 return NULL;
12427
Victor Stinner7931d9a2011-11-04 00:22:48 +010012428 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012429
12430 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012431
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012432 if (result == -2)
12433 return NULL;
12434
Guido van Rossumd57fd912000-03-10 22:53:23 +000012435 if (result < 0) {
12436 PyErr_SetString(PyExc_ValueError, "substring not found");
12437 return NULL;
12438 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012439
Christian Heimes217cfd12007-12-02 14:31:20 +000012440 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012441}
12442
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012443PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012444 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012445\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012446Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012447done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012448
12449static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012450unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012451{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012452 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012453 Py_UCS4 fillchar = ' ';
12454
Victor Stinnere9a29352011-10-01 02:14:59 +020012455 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012456 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012457
Benjamin Petersonbac79492012-01-14 13:34:47 -050012458 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012459 return NULL;
12460
Victor Stinnerc4b49542011-12-11 22:44:26 +010012461 if (PyUnicode_GET_LENGTH(self) >= width)
12462 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012463
Victor Stinnerc4b49542011-12-11 22:44:26 +010012464 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012465}
12466
Alexander Belopolsky40018472011-02-26 01:02:56 +000012467PyObject *
12468PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012469{
12470 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012471
Guido van Rossumd57fd912000-03-10 22:53:23 +000012472 s = PyUnicode_FromObject(s);
12473 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012474 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012475 if (sep != NULL) {
12476 sep = PyUnicode_FromObject(sep);
12477 if (sep == NULL) {
12478 Py_DECREF(s);
12479 return NULL;
12480 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012481 }
12482
Victor Stinner9310abb2011-10-05 00:59:23 +020012483 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012484
12485 Py_DECREF(s);
12486 Py_XDECREF(sep);
12487 return result;
12488}
12489
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012490PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012491 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012492\n\
12493Return a list of the words in S, using sep as the\n\
12494delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012495splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012496whitespace string is a separator and empty strings are\n\
12497removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012498
12499static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012500unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012501{
12502 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012503 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012504
Martin v. Löwis18e16552006-02-15 17:27:45 +000012505 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012506 return NULL;
12507
12508 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012509 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012510 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012511 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012512 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012513 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012514}
12515
Thomas Wouters477c8d52006-05-27 19:21:47 +000012516PyObject *
12517PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12518{
12519 PyObject* str_obj;
12520 PyObject* sep_obj;
12521 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012522 int kind1, kind2, kind;
12523 void *buf1 = NULL, *buf2 = NULL;
12524 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012525
12526 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012527 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012528 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012529 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012530 if (!sep_obj) {
12531 Py_DECREF(str_obj);
12532 return NULL;
12533 }
12534 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12535 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012536 Py_DECREF(str_obj);
12537 return NULL;
12538 }
12539
Victor Stinner14f8f022011-10-05 20:58:25 +020012540 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012541 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012542 kind = Py_MAX(kind1, kind2);
12543 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012544 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012545 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012546 if (!buf1)
12547 goto onError;
12548 buf2 = PyUnicode_DATA(sep_obj);
12549 if (kind2 != kind)
12550 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12551 if (!buf2)
12552 goto onError;
12553 len1 = PyUnicode_GET_LENGTH(str_obj);
12554 len2 = PyUnicode_GET_LENGTH(sep_obj);
12555
Benjamin Petersonead6b532011-12-20 17:23:42 -060012556 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012557 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012558 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12559 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12560 else
12561 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012562 break;
12563 case PyUnicode_2BYTE_KIND:
12564 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12565 break;
12566 case PyUnicode_4BYTE_KIND:
12567 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12568 break;
12569 default:
12570 assert(0);
12571 out = 0;
12572 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012573
12574 Py_DECREF(sep_obj);
12575 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012576 if (kind1 != kind)
12577 PyMem_Free(buf1);
12578 if (kind2 != kind)
12579 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012580
12581 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012582 onError:
12583 Py_DECREF(sep_obj);
12584 Py_DECREF(str_obj);
12585 if (kind1 != kind && buf1)
12586 PyMem_Free(buf1);
12587 if (kind2 != kind && buf2)
12588 PyMem_Free(buf2);
12589 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012590}
12591
12592
12593PyObject *
12594PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12595{
12596 PyObject* str_obj;
12597 PyObject* sep_obj;
12598 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012599 int kind1, kind2, kind;
12600 void *buf1 = NULL, *buf2 = NULL;
12601 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012602
12603 str_obj = PyUnicode_FromObject(str_in);
12604 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012605 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012606 sep_obj = PyUnicode_FromObject(sep_in);
12607 if (!sep_obj) {
12608 Py_DECREF(str_obj);
12609 return NULL;
12610 }
12611
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012612 kind1 = PyUnicode_KIND(str_in);
12613 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012614 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012615 buf1 = PyUnicode_DATA(str_in);
12616 if (kind1 != kind)
12617 buf1 = _PyUnicode_AsKind(str_in, kind);
12618 if (!buf1)
12619 goto onError;
12620 buf2 = PyUnicode_DATA(sep_obj);
12621 if (kind2 != kind)
12622 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12623 if (!buf2)
12624 goto onError;
12625 len1 = PyUnicode_GET_LENGTH(str_obj);
12626 len2 = PyUnicode_GET_LENGTH(sep_obj);
12627
Benjamin Petersonead6b532011-12-20 17:23:42 -060012628 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012629 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012630 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12631 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12632 else
12633 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012634 break;
12635 case PyUnicode_2BYTE_KIND:
12636 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12637 break;
12638 case PyUnicode_4BYTE_KIND:
12639 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12640 break;
12641 default:
12642 assert(0);
12643 out = 0;
12644 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012645
12646 Py_DECREF(sep_obj);
12647 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012648 if (kind1 != kind)
12649 PyMem_Free(buf1);
12650 if (kind2 != kind)
12651 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012652
12653 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012654 onError:
12655 Py_DECREF(sep_obj);
12656 Py_DECREF(str_obj);
12657 if (kind1 != kind && buf1)
12658 PyMem_Free(buf1);
12659 if (kind2 != kind && buf2)
12660 PyMem_Free(buf2);
12661 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012662}
12663
12664PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012665 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012666\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012667Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012668the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012669found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012670
12671static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012672unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012673{
Victor Stinner9310abb2011-10-05 00:59:23 +020012674 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012675}
12676
12677PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012678 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012679\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012680Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012681the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012682separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012683
12684static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012685unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012686{
Victor Stinner9310abb2011-10-05 00:59:23 +020012687 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012688}
12689
Alexander Belopolsky40018472011-02-26 01:02:56 +000012690PyObject *
12691PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012692{
12693 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012694
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012695 s = PyUnicode_FromObject(s);
12696 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012697 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012698 if (sep != NULL) {
12699 sep = PyUnicode_FromObject(sep);
12700 if (sep == NULL) {
12701 Py_DECREF(s);
12702 return NULL;
12703 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012704 }
12705
Victor Stinner9310abb2011-10-05 00:59:23 +020012706 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012707
12708 Py_DECREF(s);
12709 Py_XDECREF(sep);
12710 return result;
12711}
12712
12713PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012714 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012715\n\
12716Return a list of the words in S, using sep as the\n\
12717delimiter string, starting at the end of the string and\n\
12718working to the front. If maxsplit is given, at most maxsplit\n\
12719splits are done. If sep is not specified, any whitespace string\n\
12720is a separator.");
12721
12722static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012723unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012724{
12725 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012726 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012727
Martin v. Löwis18e16552006-02-15 17:27:45 +000012728 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012729 return NULL;
12730
12731 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012732 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012733 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012734 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012735 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012736 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012737}
12738
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012739PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012740 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012741\n\
12742Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012743Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012744is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012745
12746static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012747unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012748{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012749 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012750 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012751
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012752 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12753 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012754 return NULL;
12755
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012756 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012757}
12758
12759static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012760PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012761{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012762 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012763}
12764
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012765PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012766 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012767\n\
12768Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012769and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012770
12771static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012772unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012773{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012774 if (PyUnicode_READY(self) == -1)
12775 return NULL;
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012776 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012777}
12778
Georg Brandlceee0772007-11-27 23:48:05 +000012779PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012780 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012781\n\
12782Return a translation table usable for str.translate().\n\
12783If there is only one argument, it must be a dictionary mapping Unicode\n\
12784ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012785Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012786If there are two arguments, they must be strings of equal length, and\n\
12787in the resulting dictionary, each character in x will be mapped to the\n\
12788character at the same position in y. If there is a third argument, it\n\
12789must be a string, whose characters will be mapped to None in the result.");
12790
12791static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012792unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012793{
12794 PyObject *x, *y = NULL, *z = NULL;
12795 PyObject *new = NULL, *key, *value;
12796 Py_ssize_t i = 0;
12797 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012798
Georg Brandlceee0772007-11-27 23:48:05 +000012799 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12800 return NULL;
12801 new = PyDict_New();
12802 if (!new)
12803 return NULL;
12804 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012805 int x_kind, y_kind, z_kind;
12806 void *x_data, *y_data, *z_data;
12807
Georg Brandlceee0772007-11-27 23:48:05 +000012808 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012809 if (!PyUnicode_Check(x)) {
12810 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12811 "be a string if there is a second argument");
12812 goto err;
12813 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012814 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012815 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12816 "arguments must have equal length");
12817 goto err;
12818 }
12819 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012820 x_kind = PyUnicode_KIND(x);
12821 y_kind = PyUnicode_KIND(y);
12822 x_data = PyUnicode_DATA(x);
12823 y_data = PyUnicode_DATA(y);
12824 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12825 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012826 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012827 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012828 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012829 if (!value) {
12830 Py_DECREF(key);
12831 goto err;
12832 }
Georg Brandlceee0772007-11-27 23:48:05 +000012833 res = PyDict_SetItem(new, key, value);
12834 Py_DECREF(key);
12835 Py_DECREF(value);
12836 if (res < 0)
12837 goto err;
12838 }
12839 /* create entries for deleting chars in z */
12840 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012841 z_kind = PyUnicode_KIND(z);
12842 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012843 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012844 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012845 if (!key)
12846 goto err;
12847 res = PyDict_SetItem(new, key, Py_None);
12848 Py_DECREF(key);
12849 if (res < 0)
12850 goto err;
12851 }
12852 }
12853 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012854 int kind;
12855 void *data;
12856
Georg Brandlceee0772007-11-27 23:48:05 +000012857 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012858 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012859 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12860 "to maketrans it must be a dict");
12861 goto err;
12862 }
12863 /* copy entries into the new dict, converting string keys to int keys */
12864 while (PyDict_Next(x, &i, &key, &value)) {
12865 if (PyUnicode_Check(key)) {
12866 /* convert string keys to integer keys */
12867 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012868 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012869 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12870 "table must be of length 1");
12871 goto err;
12872 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012873 kind = PyUnicode_KIND(key);
12874 data = PyUnicode_DATA(key);
12875 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012876 if (!newkey)
12877 goto err;
12878 res = PyDict_SetItem(new, newkey, value);
12879 Py_DECREF(newkey);
12880 if (res < 0)
12881 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012882 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012883 /* just keep integer keys */
12884 if (PyDict_SetItem(new, key, value) < 0)
12885 goto err;
12886 } else {
12887 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12888 "be strings or integers");
12889 goto err;
12890 }
12891 }
12892 }
12893 return new;
12894 err:
12895 Py_DECREF(new);
12896 return NULL;
12897}
12898
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012899PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012900 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012901\n\
12902Return a copy of the string S, where all characters have been mapped\n\
12903through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012904Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012905Unmapped characters are left untouched. Characters mapped to None\n\
12906are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012907
12908static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012909unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012910{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012911 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012912}
12913
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012914PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012915 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012916\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012917Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012918
12919static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012920unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012921{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012922 if (PyUnicode_READY(self) == -1)
12923 return NULL;
12924 if (PyUnicode_IS_ASCII(self))
12925 return ascii_upper_or_lower(self, 0);
12926 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012927}
12928
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012929PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012930 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012931\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012932Pad a numeric string S with zeros on the left, to fill a field\n\
12933of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012934
12935static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012936unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012937{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012938 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012939 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012940 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012941 int kind;
12942 void *data;
12943 Py_UCS4 chr;
12944
Martin v. Löwis18e16552006-02-15 17:27:45 +000012945 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012946 return NULL;
12947
Benjamin Petersonbac79492012-01-14 13:34:47 -050012948 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012949 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012950
Victor Stinnerc4b49542011-12-11 22:44:26 +010012951 if (PyUnicode_GET_LENGTH(self) >= width)
12952 return unicode_result_unchanged(self);
12953
12954 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012955
12956 u = pad(self, fill, 0, '0');
12957
Walter Dörwald068325e2002-04-15 13:36:47 +000012958 if (u == NULL)
12959 return NULL;
12960
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012961 kind = PyUnicode_KIND(u);
12962 data = PyUnicode_DATA(u);
12963 chr = PyUnicode_READ(kind, data, fill);
12964
12965 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012966 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012967 PyUnicode_WRITE(kind, data, 0, chr);
12968 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012969 }
12970
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012971 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012972 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012973}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012974
12975#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012976static PyObject *
12977unicode__decimal2ascii(PyObject *self)
12978{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012979 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012980}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012981#endif
12982
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012983PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012984 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012985\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012986Return True if S starts with the specified prefix, False otherwise.\n\
12987With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012988With optional end, stop comparing S at that position.\n\
12989prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012990
12991static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012992unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012993 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012994{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012995 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012996 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012997 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012998 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012999 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013000
Jesus Ceaac451502011-04-20 17:09:23 +020013001 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013002 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013003 if (PyTuple_Check(subobj)) {
13004 Py_ssize_t i;
13005 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013006 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013007 if (substring == NULL)
13008 return NULL;
13009 result = tailmatch(self, substring, start, end, -1);
13010 Py_DECREF(substring);
13011 if (result) {
13012 Py_RETURN_TRUE;
13013 }
13014 }
13015 /* nothing matched */
13016 Py_RETURN_FALSE;
13017 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013018 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013019 if (substring == NULL) {
13020 if (PyErr_ExceptionMatches(PyExc_TypeError))
13021 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13022 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013023 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013024 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013025 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013026 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013027 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013028}
13029
13030
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013031PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013032 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013033\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013034Return True if S ends with the specified suffix, False otherwise.\n\
13035With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013036With optional end, stop comparing S at that position.\n\
13037suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013038
13039static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013040unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013041 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013042{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013043 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013044 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013045 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013046 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013047 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013048
Jesus Ceaac451502011-04-20 17:09:23 +020013049 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013050 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013051 if (PyTuple_Check(subobj)) {
13052 Py_ssize_t i;
13053 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013054 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013055 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013056 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013057 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013058 result = tailmatch(self, substring, start, end, +1);
13059 Py_DECREF(substring);
13060 if (result) {
13061 Py_RETURN_TRUE;
13062 }
13063 }
13064 Py_RETURN_FALSE;
13065 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013066 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013067 if (substring == NULL) {
13068 if (PyErr_ExceptionMatches(PyExc_TypeError))
13069 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13070 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013071 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013072 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013073 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013074 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013075 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013076}
13077
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013078#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013079
13080PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013081 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013082\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013083Return a formatted version of S, using substitutions from args and kwargs.\n\
13084The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013085
Eric Smith27bbca62010-11-04 17:06:58 +000013086PyDoc_STRVAR(format_map__doc__,
13087 "S.format_map(mapping) -> str\n\
13088\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013089Return a formatted version of S, using substitutions from mapping.\n\
13090The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013091
Eric Smith4a7d76d2008-05-30 18:10:19 +000013092static PyObject *
13093unicode__format__(PyObject* self, PyObject* args)
13094{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013095 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013096
13097 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13098 return NULL;
13099
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013100 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013101 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013102 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013103}
13104
Eric Smith8c663262007-08-25 02:26:07 +000013105PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013106 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013107\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013108Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013109
13110static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013111unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013112{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013113 Py_ssize_t size;
13114
13115 /* If it's a compact object, account for base structure +
13116 character data. */
13117 if (PyUnicode_IS_COMPACT_ASCII(v))
13118 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13119 else if (PyUnicode_IS_COMPACT(v))
13120 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013121 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013122 else {
13123 /* If it is a two-block object, account for base object, and
13124 for character block if present. */
13125 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013126 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013127 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013128 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013129 }
13130 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013131 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013132 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013133 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013134 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013135 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013136
13137 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013138}
13139
13140PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013141 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013142
13143static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013144unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013145{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013146 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013147 if (!copy)
13148 return NULL;
13149 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013150}
13151
Guido van Rossumd57fd912000-03-10 22:53:23 +000013152static PyMethodDef unicode_methods[] = {
13153
13154 /* Order is according to common usage: often used methods should
13155 appear first, since lookup is done sequentially. */
13156
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013157 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013158 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
13159 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013160 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013161 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13162 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013163 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013164 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13165 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13166 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13167 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13168 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013169 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013170 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13171 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13172 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013173 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013174 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13175 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13176 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013177 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013178 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013179 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013180 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013181 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13182 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13183 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13184 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13185 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13186 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13187 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13188 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13189 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13190 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13191 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13192 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13193 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13194 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013195 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013196 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013197 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013198 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013199 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013200 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013201 {"maketrans", (PyCFunction) unicode_maketrans,
13202 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013203 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013204#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013205 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013206 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013207#endif
13208
Benjamin Peterson14339b62009-01-31 16:36:08 +000013209 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013210 {NULL, NULL}
13211};
13212
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013213static PyObject *
13214unicode_mod(PyObject *v, PyObject *w)
13215{
Brian Curtindfc80e32011-08-10 20:28:54 -050013216 if (!PyUnicode_Check(v))
13217 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013218 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013219}
13220
13221static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013222 0, /*nb_add*/
13223 0, /*nb_subtract*/
13224 0, /*nb_multiply*/
13225 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013226};
13227
Guido van Rossumd57fd912000-03-10 22:53:23 +000013228static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013229 (lenfunc) unicode_length, /* sq_length */
13230 PyUnicode_Concat, /* sq_concat */
13231 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13232 (ssizeargfunc) unicode_getitem, /* sq_item */
13233 0, /* sq_slice */
13234 0, /* sq_ass_item */
13235 0, /* sq_ass_slice */
13236 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013237};
13238
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013239static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013240unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013241{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013242 if (PyUnicode_READY(self) == -1)
13243 return NULL;
13244
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013245 if (PyIndex_Check(item)) {
13246 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013247 if (i == -1 && PyErr_Occurred())
13248 return NULL;
13249 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013250 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013251 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013252 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013253 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013254 PyObject *result;
13255 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013256 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013257 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013258
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013259 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013260 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013261 return NULL;
13262 }
13263
13264 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013265 Py_INCREF(unicode_empty);
13266 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013267 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013268 slicelength == PyUnicode_GET_LENGTH(self)) {
13269 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013270 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013271 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013272 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013273 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013274 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013275 src_kind = PyUnicode_KIND(self);
13276 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013277 if (!PyUnicode_IS_ASCII(self)) {
13278 kind_limit = kind_maxchar_limit(src_kind);
13279 max_char = 0;
13280 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13281 ch = PyUnicode_READ(src_kind, src_data, cur);
13282 if (ch > max_char) {
13283 max_char = ch;
13284 if (max_char >= kind_limit)
13285 break;
13286 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013287 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013288 }
Victor Stinner55c99112011-10-13 01:17:06 +020013289 else
13290 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013291 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013292 if (result == NULL)
13293 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013294 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013295 dest_data = PyUnicode_DATA(result);
13296
13297 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013298 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13299 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013300 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013301 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013302 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013303 } else {
13304 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13305 return NULL;
13306 }
13307}
13308
13309static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013310 (lenfunc)unicode_length, /* mp_length */
13311 (binaryfunc)unicode_subscript, /* mp_subscript */
13312 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013313};
13314
Guido van Rossumd57fd912000-03-10 22:53:23 +000013315
Guido van Rossumd57fd912000-03-10 22:53:23 +000013316/* Helpers for PyUnicode_Format() */
13317
13318static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013319getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013320{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013321 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013322 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013323 (*p_argidx)++;
13324 if (arglen < 0)
13325 return args;
13326 else
13327 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013328 }
13329 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013330 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013331 return NULL;
13332}
13333
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013334/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013335
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013336static PyObject *
13337formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013338{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013339 char *p;
13340 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013341 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013342
Guido van Rossumd57fd912000-03-10 22:53:23 +000013343 x = PyFloat_AsDouble(v);
13344 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013345 return NULL;
13346
Guido van Rossumd57fd912000-03-10 22:53:23 +000013347 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013348 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013349
Eric Smith0923d1d2009-04-16 20:16:10 +000013350 p = PyOS_double_to_string(x, type, prec,
13351 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013352 if (p == NULL)
13353 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013354 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013355 PyMem_Free(p);
13356 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013357}
13358
Tim Peters38fd5b62000-09-21 05:43:11 +000013359static PyObject*
13360formatlong(PyObject *val, int flags, int prec, int type)
13361{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013362 char *buf;
13363 int len;
13364 PyObject *str; /* temporary string object. */
13365 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013366
Benjamin Peterson14339b62009-01-31 16:36:08 +000013367 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13368 if (!str)
13369 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013370 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013371 Py_DECREF(str);
13372 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013373}
13374
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013375static Py_UCS4
13376formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013377{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013378 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013379 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013380 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013381 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013382 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013383 goto onError;
13384 }
13385 else {
13386 /* Integer input truncated to a character */
13387 long x;
13388 x = PyLong_AsLong(v);
13389 if (x == -1 && PyErr_Occurred())
13390 goto onError;
13391
Victor Stinner8faf8212011-12-08 22:14:11 +010013392 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013393 PyErr_SetString(PyExc_OverflowError,
13394 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013395 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013396 }
13397
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013398 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013399 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013400
Benjamin Peterson29060642009-01-31 22:14:21 +000013401 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013402 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013403 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013404 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013405}
13406
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013407static int
13408repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13409{
13410 int r;
13411 assert(count > 0);
13412 assert(PyUnicode_Check(obj));
13413 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013414 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013415 if (repeated == NULL)
13416 return -1;
13417 r = _PyAccu_Accumulate(acc, repeated);
13418 Py_DECREF(repeated);
13419 return r;
13420 }
13421 else {
13422 do {
13423 if (_PyAccu_Accumulate(acc, obj))
13424 return -1;
13425 } while (--count);
13426 return 0;
13427 }
13428}
13429
Alexander Belopolsky40018472011-02-26 01:02:56 +000013430PyObject *
13431PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013432{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013433 void *fmt;
13434 int fmtkind;
13435 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013436 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013437 int r;
13438 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013439 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013440 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013441 PyObject *temp = NULL;
13442 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013443 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013444 _PyAccu acc;
13445 static PyObject *plus, *minus, *blank, *zero, *percent;
13446
13447 if (!plus && !(plus = get_latin1_char('+')))
13448 return NULL;
13449 if (!minus && !(minus = get_latin1_char('-')))
13450 return NULL;
13451 if (!blank && !(blank = get_latin1_char(' ')))
13452 return NULL;
13453 if (!zero && !(zero = get_latin1_char('0')))
13454 return NULL;
13455 if (!percent && !(percent = get_latin1_char('%')))
13456 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013457
Guido van Rossumd57fd912000-03-10 22:53:23 +000013458 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013459 PyErr_BadInternalCall();
13460 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013461 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013462 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013463 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013464 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013465 if (PyUnicode_READY(uformat) == -1)
13466 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013467 if (_PyAccu_Init(&acc))
13468 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013469 fmt = PyUnicode_DATA(uformat);
13470 fmtkind = PyUnicode_KIND(uformat);
13471 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13472 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013473
Guido van Rossumd57fd912000-03-10 22:53:23 +000013474 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013475 arglen = PyTuple_Size(args);
13476 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013477 }
13478 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013479 arglen = -1;
13480 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013481 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013482 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013483 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013484 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013485
13486 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013487 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013488 PyObject *nonfmt;
13489 Py_ssize_t nonfmtpos;
13490 nonfmtpos = fmtpos++;
13491 while (fmtcnt >= 0 &&
13492 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13493 fmtpos++;
13494 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013495 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013496 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013497 if (nonfmt == NULL)
13498 goto onError;
13499 r = _PyAccu_Accumulate(&acc, nonfmt);
13500 Py_DECREF(nonfmt);
13501 if (r)
13502 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013503 }
13504 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013505 /* Got a format specifier */
13506 int flags = 0;
13507 Py_ssize_t width = -1;
13508 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013509 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013510 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013511 int isnumok;
13512 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013513 void *pbuf = NULL;
13514 Py_ssize_t pindex, len;
13515 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013516
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013517 fmtpos++;
13518 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13519 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013520 Py_ssize_t keylen;
13521 PyObject *key;
13522 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013523
Benjamin Peterson29060642009-01-31 22:14:21 +000013524 if (dict == NULL) {
13525 PyErr_SetString(PyExc_TypeError,
13526 "format requires a mapping");
13527 goto onError;
13528 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013529 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013530 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013531 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013532 /* Skip over balanced parentheses */
13533 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013534 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013535 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013536 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013537 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013538 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013539 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013540 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013541 if (fmtcnt < 0 || pcount > 0) {
13542 PyErr_SetString(PyExc_ValueError,
13543 "incomplete format key");
13544 goto onError;
13545 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013546 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013547 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013548 if (key == NULL)
13549 goto onError;
13550 if (args_owned) {
13551 Py_DECREF(args);
13552 args_owned = 0;
13553 }
13554 args = PyObject_GetItem(dict, key);
13555 Py_DECREF(key);
13556 if (args == NULL) {
13557 goto onError;
13558 }
13559 args_owned = 1;
13560 arglen = -1;
13561 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013562 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013563 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013564 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013565 case '-': flags |= F_LJUST; continue;
13566 case '+': flags |= F_SIGN; continue;
13567 case ' ': flags |= F_BLANK; continue;
13568 case '#': flags |= F_ALT; continue;
13569 case '0': flags |= F_ZERO; continue;
13570 }
13571 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013572 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013573 if (c == '*') {
13574 v = getnextarg(args, arglen, &argidx);
13575 if (v == NULL)
13576 goto onError;
13577 if (!PyLong_Check(v)) {
13578 PyErr_SetString(PyExc_TypeError,
13579 "* wants int");
13580 goto onError;
13581 }
13582 width = PyLong_AsLong(v);
13583 if (width == -1 && PyErr_Occurred())
13584 goto onError;
13585 if (width < 0) {
13586 flags |= F_LJUST;
13587 width = -width;
13588 }
13589 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013590 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013591 }
13592 else if (c >= '0' && c <= '9') {
13593 width = c - '0';
13594 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013595 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013596 if (c < '0' || c > '9')
13597 break;
13598 if ((width*10) / 10 != width) {
13599 PyErr_SetString(PyExc_ValueError,
13600 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013601 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013602 }
13603 width = width*10 + (c - '0');
13604 }
13605 }
13606 if (c == '.') {
13607 prec = 0;
13608 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013609 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013610 if (c == '*') {
13611 v = getnextarg(args, arglen, &argidx);
13612 if (v == NULL)
13613 goto onError;
13614 if (!PyLong_Check(v)) {
13615 PyErr_SetString(PyExc_TypeError,
13616 "* wants int");
13617 goto onError;
13618 }
13619 prec = PyLong_AsLong(v);
13620 if (prec == -1 && PyErr_Occurred())
13621 goto onError;
13622 if (prec < 0)
13623 prec = 0;
13624 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013625 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013626 }
13627 else if (c >= '0' && c <= '9') {
13628 prec = c - '0';
13629 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013630 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013631 if (c < '0' || c > '9')
13632 break;
13633 if ((prec*10) / 10 != prec) {
13634 PyErr_SetString(PyExc_ValueError,
13635 "prec too big");
13636 goto onError;
13637 }
13638 prec = prec*10 + (c - '0');
13639 }
13640 }
13641 } /* prec */
13642 if (fmtcnt >= 0) {
13643 if (c == 'h' || c == 'l' || c == 'L') {
13644 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013645 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013646 }
13647 }
13648 if (fmtcnt < 0) {
13649 PyErr_SetString(PyExc_ValueError,
13650 "incomplete format");
13651 goto onError;
13652 }
13653 if (c != '%') {
13654 v = getnextarg(args, arglen, &argidx);
13655 if (v == NULL)
13656 goto onError;
13657 }
13658 sign = 0;
13659 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013660 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013661 switch (c) {
13662
13663 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013664 _PyAccu_Accumulate(&acc, percent);
13665 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013666
13667 case 's':
13668 case 'r':
13669 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013670 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013671 temp = v;
13672 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013673 }
13674 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013675 if (c == 's')
13676 temp = PyObject_Str(v);
13677 else if (c == 'r')
13678 temp = PyObject_Repr(v);
13679 else
13680 temp = PyObject_ASCII(v);
13681 if (temp == NULL)
13682 goto onError;
13683 if (PyUnicode_Check(temp))
13684 /* nothing to do */;
13685 else {
13686 Py_DECREF(temp);
13687 PyErr_SetString(PyExc_TypeError,
13688 "%s argument has non-string str()");
13689 goto onError;
13690 }
13691 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013692 if (PyUnicode_READY(temp) == -1) {
13693 Py_CLEAR(temp);
13694 goto onError;
13695 }
13696 pbuf = PyUnicode_DATA(temp);
13697 kind = PyUnicode_KIND(temp);
13698 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013699 if (prec >= 0 && len > prec)
13700 len = prec;
13701 break;
13702
13703 case 'i':
13704 case 'd':
13705 case 'u':
13706 case 'o':
13707 case 'x':
13708 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013709 isnumok = 0;
13710 if (PyNumber_Check(v)) {
13711 PyObject *iobj=NULL;
13712
13713 if (PyLong_Check(v)) {
13714 iobj = v;
13715 Py_INCREF(iobj);
13716 }
13717 else {
13718 iobj = PyNumber_Long(v);
13719 }
13720 if (iobj!=NULL) {
13721 if (PyLong_Check(iobj)) {
13722 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013723 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013724 Py_DECREF(iobj);
13725 if (!temp)
13726 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013727 if (PyUnicode_READY(temp) == -1) {
13728 Py_CLEAR(temp);
13729 goto onError;
13730 }
13731 pbuf = PyUnicode_DATA(temp);
13732 kind = PyUnicode_KIND(temp);
13733 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013734 sign = 1;
13735 }
13736 else {
13737 Py_DECREF(iobj);
13738 }
13739 }
13740 }
13741 if (!isnumok) {
13742 PyErr_Format(PyExc_TypeError,
13743 "%%%c format: a number is required, "
13744 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13745 goto onError;
13746 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013747 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013748 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013749 fillobj = zero;
13750 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013751 break;
13752
13753 case 'e':
13754 case 'E':
13755 case 'f':
13756 case 'F':
13757 case 'g':
13758 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013759 temp = formatfloat(v, flags, prec, c);
13760 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013761 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013762 if (PyUnicode_READY(temp) == -1) {
13763 Py_CLEAR(temp);
13764 goto onError;
13765 }
13766 pbuf = PyUnicode_DATA(temp);
13767 kind = PyUnicode_KIND(temp);
13768 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013769 sign = 1;
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 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013777 {
13778 Py_UCS4 ch = formatchar(v);
13779 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013780 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013781 temp = _PyUnicode_FromUCS4(&ch, 1);
13782 if (temp == NULL)
13783 goto onError;
13784 pbuf = PyUnicode_DATA(temp);
13785 kind = PyUnicode_KIND(temp);
13786 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013787 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013788 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013789
13790 default:
13791 PyErr_Format(PyExc_ValueError,
13792 "unsupported format character '%c' (0x%x) "
13793 "at index %zd",
13794 (31<=c && c<=126) ? (char)c : '?',
13795 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013796 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013797 goto onError;
13798 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013799 /* pbuf is initialized here. */
13800 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013801 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013802 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13803 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013804 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013805 pindex++;
13806 }
13807 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13808 signobj = plus;
13809 len--;
13810 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013811 }
13812 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013813 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013814 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013815 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013816 else
13817 sign = 0;
13818 }
13819 if (width < len)
13820 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013821 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013822 if (fill != ' ') {
13823 assert(signobj != NULL);
13824 if (_PyAccu_Accumulate(&acc, signobj))
13825 goto onError;
13826 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013827 if (width > len)
13828 width--;
13829 }
13830 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013831 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013832 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013833 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013834 second = get_latin1_char(
13835 PyUnicode_READ(kind, pbuf, pindex + 1));
13836 pindex += 2;
13837 if (second == NULL ||
13838 _PyAccu_Accumulate(&acc, zero) ||
13839 _PyAccu_Accumulate(&acc, second))
13840 goto onError;
13841 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013842 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013843 width -= 2;
13844 if (width < 0)
13845 width = 0;
13846 len -= 2;
13847 }
13848 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013849 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013850 if (repeat_accumulate(&acc, fillobj, width - len))
13851 goto onError;
13852 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013853 }
13854 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013855 if (sign) {
13856 assert(signobj != NULL);
13857 if (_PyAccu_Accumulate(&acc, signobj))
13858 goto onError;
13859 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013860 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013861 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13862 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013863 second = get_latin1_char(
13864 PyUnicode_READ(kind, pbuf, pindex + 1));
13865 pindex += 2;
13866 if (second == NULL ||
13867 _PyAccu_Accumulate(&acc, zero) ||
13868 _PyAccu_Accumulate(&acc, second))
13869 goto onError;
13870 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013871 }
13872 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013873 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013874 if (temp != NULL) {
13875 assert(pbuf == PyUnicode_DATA(temp));
13876 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013877 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013878 else {
13879 const char *p = (const char *) pbuf;
13880 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013881 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013882 v = PyUnicode_FromKindAndData(kind, p, len);
13883 }
13884 if (v == NULL)
13885 goto onError;
13886 r = _PyAccu_Accumulate(&acc, v);
13887 Py_DECREF(v);
13888 if (r)
13889 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013890 if (width > len && repeat_accumulate(&acc, blank, width - len))
13891 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013892 if (dict && (argidx < arglen) && c != '%') {
13893 PyErr_SetString(PyExc_TypeError,
13894 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013895 goto onError;
13896 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013897 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013898 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013899 } /* until end */
13900 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013901 PyErr_SetString(PyExc_TypeError,
13902 "not all arguments converted during string formatting");
13903 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013904 }
13905
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013906 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013907 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013908 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013909 }
13910 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013911 Py_XDECREF(temp);
13912 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013913 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013914
Benjamin Peterson29060642009-01-31 22:14:21 +000013915 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013916 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013917 Py_XDECREF(temp);
13918 Py_XDECREF(second);
13919 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013920 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013921 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013922 }
13923 return NULL;
13924}
13925
Jeremy Hylton938ace62002-07-17 16:30:39 +000013926static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013927unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13928
Tim Peters6d6c1a32001-08-02 04:15:00 +000013929static PyObject *
13930unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13931{
Benjamin Peterson29060642009-01-31 22:14:21 +000013932 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013933 static char *kwlist[] = {"object", "encoding", "errors", 0};
13934 char *encoding = NULL;
13935 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013936
Benjamin Peterson14339b62009-01-31 16:36:08 +000013937 if (type != &PyUnicode_Type)
13938 return unicode_subtype_new(type, args, kwds);
13939 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013940 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013941 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013942 if (x == NULL) {
13943 Py_INCREF(unicode_empty);
13944 return unicode_empty;
13945 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013946 if (encoding == NULL && errors == NULL)
13947 return PyObject_Str(x);
13948 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013949 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013950}
13951
Guido van Rossume023fe02001-08-30 03:12:59 +000013952static PyObject *
13953unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13954{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013955 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013956 Py_ssize_t length, char_size;
13957 int share_wstr, share_utf8;
13958 unsigned int kind;
13959 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013960
Benjamin Peterson14339b62009-01-31 16:36:08 +000013961 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013962
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013963 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013964 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013965 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013966 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050013967 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013968 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013969 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013970 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013971
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013972 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013973 if (self == NULL) {
13974 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013975 return NULL;
13976 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013977 kind = PyUnicode_KIND(unicode);
13978 length = PyUnicode_GET_LENGTH(unicode);
13979
13980 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013981#ifdef Py_DEBUG
13982 _PyUnicode_HASH(self) = -1;
13983#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013984 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013985#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013986 _PyUnicode_STATE(self).interned = 0;
13987 _PyUnicode_STATE(self).kind = kind;
13988 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013989 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013990 _PyUnicode_STATE(self).ready = 1;
13991 _PyUnicode_WSTR(self) = NULL;
13992 _PyUnicode_UTF8_LENGTH(self) = 0;
13993 _PyUnicode_UTF8(self) = NULL;
13994 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013995 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013996
13997 share_utf8 = 0;
13998 share_wstr = 0;
13999 if (kind == PyUnicode_1BYTE_KIND) {
14000 char_size = 1;
14001 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14002 share_utf8 = 1;
14003 }
14004 else if (kind == PyUnicode_2BYTE_KIND) {
14005 char_size = 2;
14006 if (sizeof(wchar_t) == 2)
14007 share_wstr = 1;
14008 }
14009 else {
14010 assert(kind == PyUnicode_4BYTE_KIND);
14011 char_size = 4;
14012 if (sizeof(wchar_t) == 4)
14013 share_wstr = 1;
14014 }
14015
14016 /* Ensure we won't overflow the length. */
14017 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14018 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014019 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014020 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014021 data = PyObject_MALLOC((length + 1) * char_size);
14022 if (data == NULL) {
14023 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014024 goto onError;
14025 }
14026
Victor Stinnerc3c74152011-10-02 20:39:55 +020014027 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014028 if (share_utf8) {
14029 _PyUnicode_UTF8_LENGTH(self) = length;
14030 _PyUnicode_UTF8(self) = data;
14031 }
14032 if (share_wstr) {
14033 _PyUnicode_WSTR_LENGTH(self) = length;
14034 _PyUnicode_WSTR(self) = (wchar_t *)data;
14035 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014036
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014037 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014038 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014039 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014040#ifdef Py_DEBUG
14041 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14042#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014043 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014044 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014045
14046onError:
14047 Py_DECREF(unicode);
14048 Py_DECREF(self);
14049 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014050}
14051
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014052PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000014053 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014054\n\
Collin Winterd474ce82007-08-07 19:42:11 +000014055Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000014056encoding defaults to the current default string encoding.\n\
14057errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014058
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014059static PyObject *unicode_iter(PyObject *seq);
14060
Guido van Rossumd57fd912000-03-10 22:53:23 +000014061PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014062 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014063 "str", /* tp_name */
14064 sizeof(PyUnicodeObject), /* tp_size */
14065 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014066 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014067 (destructor)unicode_dealloc, /* tp_dealloc */
14068 0, /* tp_print */
14069 0, /* tp_getattr */
14070 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014071 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014072 unicode_repr, /* tp_repr */
14073 &unicode_as_number, /* tp_as_number */
14074 &unicode_as_sequence, /* tp_as_sequence */
14075 &unicode_as_mapping, /* tp_as_mapping */
14076 (hashfunc) unicode_hash, /* tp_hash*/
14077 0, /* tp_call*/
14078 (reprfunc) unicode_str, /* tp_str */
14079 PyObject_GenericGetAttr, /* tp_getattro */
14080 0, /* tp_setattro */
14081 0, /* tp_as_buffer */
14082 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014083 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014084 unicode_doc, /* tp_doc */
14085 0, /* tp_traverse */
14086 0, /* tp_clear */
14087 PyUnicode_RichCompare, /* tp_richcompare */
14088 0, /* tp_weaklistoffset */
14089 unicode_iter, /* tp_iter */
14090 0, /* tp_iternext */
14091 unicode_methods, /* tp_methods */
14092 0, /* tp_members */
14093 0, /* tp_getset */
14094 &PyBaseObject_Type, /* tp_base */
14095 0, /* tp_dict */
14096 0, /* tp_descr_get */
14097 0, /* tp_descr_set */
14098 0, /* tp_dictoffset */
14099 0, /* tp_init */
14100 0, /* tp_alloc */
14101 unicode_new, /* tp_new */
14102 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014103};
14104
14105/* Initialize the Unicode implementation */
14106
Victor Stinner3a50e702011-10-18 21:21:00 +020014107int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014108{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014109 int i;
14110
Thomas Wouters477c8d52006-05-27 19:21:47 +000014111 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014112 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014113 0x000A, /* LINE FEED */
14114 0x000D, /* CARRIAGE RETURN */
14115 0x001C, /* FILE SEPARATOR */
14116 0x001D, /* GROUP SEPARATOR */
14117 0x001E, /* RECORD SEPARATOR */
14118 0x0085, /* NEXT LINE */
14119 0x2028, /* LINE SEPARATOR */
14120 0x2029, /* PARAGRAPH SEPARATOR */
14121 };
14122
Fred Drakee4315f52000-05-09 19:53:39 +000014123 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014124 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014125 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014126 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014127 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014128
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014129 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014130 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014131 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014132 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014133
14134 /* initialize the linebreak bloom filter */
14135 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014136 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014137 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014138
14139 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014140
14141#ifdef HAVE_MBCS
14142 winver.dwOSVersionInfoSize = sizeof(winver);
14143 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14144 PyErr_SetFromWindowsErr(0);
14145 return -1;
14146 }
14147#endif
14148 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014149}
14150
14151/* Finalize the Unicode implementation */
14152
Christian Heimesa156e092008-02-16 07:38:31 +000014153int
14154PyUnicode_ClearFreeList(void)
14155{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014156 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014157}
14158
Guido van Rossumd57fd912000-03-10 22:53:23 +000014159void
Thomas Wouters78890102000-07-22 19:25:51 +000014160_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014161{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014162 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014163
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014164 Py_XDECREF(unicode_empty);
14165 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014166
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014167 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014168 if (unicode_latin1[i]) {
14169 Py_DECREF(unicode_latin1[i]);
14170 unicode_latin1[i] = NULL;
14171 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014172 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014173 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014174 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014175}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014176
Walter Dörwald16807132007-05-25 13:52:07 +000014177void
14178PyUnicode_InternInPlace(PyObject **p)
14179{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014180 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014181 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014182#ifdef Py_DEBUG
14183 assert(s != NULL);
14184 assert(_PyUnicode_CHECK(s));
14185#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014186 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014187 return;
14188#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014189 /* If it's a subclass, we don't really know what putting
14190 it in the interned dict might do. */
14191 if (!PyUnicode_CheckExact(s))
14192 return;
14193 if (PyUnicode_CHECK_INTERNED(s))
14194 return;
14195 if (interned == NULL) {
14196 interned = PyDict_New();
14197 if (interned == NULL) {
14198 PyErr_Clear(); /* Don't leave an exception */
14199 return;
14200 }
14201 }
14202 /* It might be that the GetItem call fails even
14203 though the key is present in the dictionary,
14204 namely when this happens during a stack overflow. */
14205 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014206 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014207 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014208
Benjamin Peterson29060642009-01-31 22:14:21 +000014209 if (t) {
14210 Py_INCREF(t);
14211 Py_DECREF(*p);
14212 *p = t;
14213 return;
14214 }
Walter Dörwald16807132007-05-25 13:52:07 +000014215
Benjamin Peterson14339b62009-01-31 16:36:08 +000014216 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014217 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014218 PyErr_Clear();
14219 PyThreadState_GET()->recursion_critical = 0;
14220 return;
14221 }
14222 PyThreadState_GET()->recursion_critical = 0;
14223 /* The two references in interned are not counted by refcnt.
14224 The deallocator will take care of this */
14225 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014226 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014227}
14228
14229void
14230PyUnicode_InternImmortal(PyObject **p)
14231{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014232 PyUnicode_InternInPlace(p);
14233 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014234 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014235 Py_INCREF(*p);
14236 }
Walter Dörwald16807132007-05-25 13:52:07 +000014237}
14238
14239PyObject *
14240PyUnicode_InternFromString(const char *cp)
14241{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014242 PyObject *s = PyUnicode_FromString(cp);
14243 if (s == NULL)
14244 return NULL;
14245 PyUnicode_InternInPlace(&s);
14246 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014247}
14248
Alexander Belopolsky40018472011-02-26 01:02:56 +000014249void
14250_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014251{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014252 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014253 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014254 Py_ssize_t i, n;
14255 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014256
Benjamin Peterson14339b62009-01-31 16:36:08 +000014257 if (interned == NULL || !PyDict_Check(interned))
14258 return;
14259 keys = PyDict_Keys(interned);
14260 if (keys == NULL || !PyList_Check(keys)) {
14261 PyErr_Clear();
14262 return;
14263 }
Walter Dörwald16807132007-05-25 13:52:07 +000014264
Benjamin Peterson14339b62009-01-31 16:36:08 +000014265 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14266 detector, interned unicode strings are not forcibly deallocated;
14267 rather, we give them their stolen references back, and then clear
14268 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014269
Benjamin Peterson14339b62009-01-31 16:36:08 +000014270 n = PyList_GET_SIZE(keys);
14271 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014272 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014273 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014274 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014275 if (PyUnicode_READY(s) == -1) {
14276 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014277 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014278 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014279 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014280 case SSTATE_NOT_INTERNED:
14281 /* XXX Shouldn't happen */
14282 break;
14283 case SSTATE_INTERNED_IMMORTAL:
14284 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014285 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014286 break;
14287 case SSTATE_INTERNED_MORTAL:
14288 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014289 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014290 break;
14291 default:
14292 Py_FatalError("Inconsistent interned string state.");
14293 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014294 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014295 }
14296 fprintf(stderr, "total size of all interned strings: "
14297 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14298 "mortal/immortal\n", mortal_size, immortal_size);
14299 Py_DECREF(keys);
14300 PyDict_Clear(interned);
14301 Py_DECREF(interned);
14302 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014303}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014304
14305
14306/********************* Unicode Iterator **************************/
14307
14308typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014309 PyObject_HEAD
14310 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014311 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014312} unicodeiterobject;
14313
14314static void
14315unicodeiter_dealloc(unicodeiterobject *it)
14316{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014317 _PyObject_GC_UNTRACK(it);
14318 Py_XDECREF(it->it_seq);
14319 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014320}
14321
14322static int
14323unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14324{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014325 Py_VISIT(it->it_seq);
14326 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014327}
14328
14329static PyObject *
14330unicodeiter_next(unicodeiterobject *it)
14331{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014332 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014333
Benjamin Peterson14339b62009-01-31 16:36:08 +000014334 assert(it != NULL);
14335 seq = it->it_seq;
14336 if (seq == NULL)
14337 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014338 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014339
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014340 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14341 int kind = PyUnicode_KIND(seq);
14342 void *data = PyUnicode_DATA(seq);
14343 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14344 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014345 if (item != NULL)
14346 ++it->it_index;
14347 return item;
14348 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014349
Benjamin Peterson14339b62009-01-31 16:36:08 +000014350 Py_DECREF(seq);
14351 it->it_seq = NULL;
14352 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014353}
14354
14355static PyObject *
14356unicodeiter_len(unicodeiterobject *it)
14357{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014358 Py_ssize_t len = 0;
14359 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014360 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014361 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014362}
14363
14364PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14365
14366static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014367 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014368 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014369 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014370};
14371
14372PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014373 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14374 "str_iterator", /* tp_name */
14375 sizeof(unicodeiterobject), /* tp_basicsize */
14376 0, /* tp_itemsize */
14377 /* methods */
14378 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14379 0, /* tp_print */
14380 0, /* tp_getattr */
14381 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014382 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014383 0, /* tp_repr */
14384 0, /* tp_as_number */
14385 0, /* tp_as_sequence */
14386 0, /* tp_as_mapping */
14387 0, /* tp_hash */
14388 0, /* tp_call */
14389 0, /* tp_str */
14390 PyObject_GenericGetAttr, /* tp_getattro */
14391 0, /* tp_setattro */
14392 0, /* tp_as_buffer */
14393 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14394 0, /* tp_doc */
14395 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14396 0, /* tp_clear */
14397 0, /* tp_richcompare */
14398 0, /* tp_weaklistoffset */
14399 PyObject_SelfIter, /* tp_iter */
14400 (iternextfunc)unicodeiter_next, /* tp_iternext */
14401 unicodeiter_methods, /* tp_methods */
14402 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014403};
14404
14405static PyObject *
14406unicode_iter(PyObject *seq)
14407{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014408 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014409
Benjamin Peterson14339b62009-01-31 16:36:08 +000014410 if (!PyUnicode_Check(seq)) {
14411 PyErr_BadInternalCall();
14412 return NULL;
14413 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014414 if (PyUnicode_READY(seq) == -1)
14415 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014416 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14417 if (it == NULL)
14418 return NULL;
14419 it->it_index = 0;
14420 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014421 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014422 _PyObject_GC_TRACK(it);
14423 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014424}
14425
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014426
14427size_t
14428Py_UNICODE_strlen(const Py_UNICODE *u)
14429{
14430 int res = 0;
14431 while(*u++)
14432 res++;
14433 return res;
14434}
14435
14436Py_UNICODE*
14437Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14438{
14439 Py_UNICODE *u = s1;
14440 while ((*u++ = *s2++));
14441 return s1;
14442}
14443
14444Py_UNICODE*
14445Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14446{
14447 Py_UNICODE *u = s1;
14448 while ((*u++ = *s2++))
14449 if (n-- == 0)
14450 break;
14451 return s1;
14452}
14453
14454Py_UNICODE*
14455Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14456{
14457 Py_UNICODE *u1 = s1;
14458 u1 += Py_UNICODE_strlen(u1);
14459 Py_UNICODE_strcpy(u1, s2);
14460 return s1;
14461}
14462
14463int
14464Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14465{
14466 while (*s1 && *s2 && *s1 == *s2)
14467 s1++, s2++;
14468 if (*s1 && *s2)
14469 return (*s1 < *s2) ? -1 : +1;
14470 if (*s1)
14471 return 1;
14472 if (*s2)
14473 return -1;
14474 return 0;
14475}
14476
14477int
14478Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14479{
14480 register Py_UNICODE u1, u2;
14481 for (; n != 0; n--) {
14482 u1 = *s1;
14483 u2 = *s2;
14484 if (u1 != u2)
14485 return (u1 < u2) ? -1 : +1;
14486 if (u1 == '\0')
14487 return 0;
14488 s1++;
14489 s2++;
14490 }
14491 return 0;
14492}
14493
14494Py_UNICODE*
14495Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14496{
14497 const Py_UNICODE *p;
14498 for (p = s; *p; p++)
14499 if (*p == c)
14500 return (Py_UNICODE*)p;
14501 return NULL;
14502}
14503
14504Py_UNICODE*
14505Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14506{
14507 const Py_UNICODE *p;
14508 p = s + Py_UNICODE_strlen(s);
14509 while (p != s) {
14510 p--;
14511 if (*p == c)
14512 return (Py_UNICODE*)p;
14513 }
14514 return NULL;
14515}
Victor Stinner331ea922010-08-10 16:37:20 +000014516
Victor Stinner71133ff2010-09-01 23:43:53 +000014517Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014518PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014519{
Victor Stinner577db2c2011-10-11 22:12:48 +020014520 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014521 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014522
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014523 if (!PyUnicode_Check(unicode)) {
14524 PyErr_BadArgument();
14525 return NULL;
14526 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014527 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014528 if (u == NULL)
14529 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014530 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014531 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014532 PyErr_NoMemory();
14533 return NULL;
14534 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014535 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014536 size *= sizeof(Py_UNICODE);
14537 copy = PyMem_Malloc(size);
14538 if (copy == NULL) {
14539 PyErr_NoMemory();
14540 return NULL;
14541 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014542 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014543 return copy;
14544}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014545
Georg Brandl66c221e2010-10-14 07:04:07 +000014546/* A _string module, to export formatter_parser and formatter_field_name_split
14547 to the string.Formatter class implemented in Python. */
14548
14549static PyMethodDef _string_methods[] = {
14550 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14551 METH_O, PyDoc_STR("split the argument as a field name")},
14552 {"formatter_parser", (PyCFunction) formatter_parser,
14553 METH_O, PyDoc_STR("parse the argument as a format string")},
14554 {NULL, NULL}
14555};
14556
14557static struct PyModuleDef _string_module = {
14558 PyModuleDef_HEAD_INIT,
14559 "_string",
14560 PyDoc_STR("string helper module"),
14561 0,
14562 _string_methods,
14563 NULL,
14564 NULL,
14565 NULL,
14566 NULL
14567};
14568
14569PyMODINIT_FUNC
14570PyInit__string(void)
14571{
14572 return PyModule_Create(&_string_module);
14573}
14574
14575
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014576#ifdef __cplusplus
14577}
14578#endif