blob: 9c1a5f09a1dd0351d06dace31697b4a0aabbe795 [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 Stinnere6abb482012-05-02 01:15:40 +0200114/* Optimized version of Py_MAX() to compute the maximum character:
115 use it when your are computing the second argument of PyUnicode_New() */
116#define MAX_MAXCHAR(maxchar1, maxchar2) \
117 ((maxchar1) | (maxchar2))
118
Victor Stinner910337b2011-10-03 03:20:16 +0200119#undef PyUnicode_READY
120#define PyUnicode_READY(op) \
121 (assert(_PyUnicode_CHECK(op)), \
122 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200123 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100124 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200125
Victor Stinnerc379ead2011-10-03 12:52:27 +0200126#define _PyUnicode_SHARE_UTF8(op) \
127 (assert(_PyUnicode_CHECK(op)), \
128 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
129 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
130#define _PyUnicode_SHARE_WSTR(op) \
131 (assert(_PyUnicode_CHECK(op)), \
132 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
133
Victor Stinner829c0ad2011-10-03 01:08:02 +0200134/* true if the Unicode object has an allocated UTF-8 memory block
135 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200136#define _PyUnicode_HAS_UTF8_MEMORY(op) \
137 (assert(_PyUnicode_CHECK(op)), \
138 (!PyUnicode_IS_COMPACT_ASCII(op) \
139 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200140 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
141
Victor Stinner03490912011-10-03 23:45:12 +0200142/* true if the Unicode object has an allocated wstr memory block
143 (not shared with other data) */
144#define _PyUnicode_HAS_WSTR_MEMORY(op) \
145 (assert(_PyUnicode_CHECK(op)), \
146 (_PyUnicode_WSTR(op) && \
147 (!PyUnicode_IS_READY(op) || \
148 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
149
Victor Stinner910337b2011-10-03 03:20:16 +0200150/* Generic helper macro to convert characters of different types.
151 from_type and to_type have to be valid type names, begin and end
152 are pointers to the source characters which should be of type
153 "from_type *". to is a pointer of type "to_type *" and points to the
154 buffer where the result characters are written to. */
155#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
156 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200157 to_type *_to = (to_type *) to; \
158 const from_type *_iter = (begin); \
159 const from_type *_end = (end); \
160 Py_ssize_t n = (_end) - (_iter); \
161 const from_type *_unrolled_end = \
162 _iter + (n & ~ (Py_ssize_t) 3); \
163 while (_iter < (_unrolled_end)) { \
164 _to[0] = (to_type) _iter[0]; \
165 _to[1] = (to_type) _iter[1]; \
166 _to[2] = (to_type) _iter[2]; \
167 _to[3] = (to_type) _iter[3]; \
168 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200169 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_end)) \
171 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200172 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200173
Walter Dörwald16807132007-05-25 13:52:07 +0000174/* This dictionary holds all interned unicode strings. Note that references
175 to strings in this dictionary are *not* counted in the string's ob_refcnt.
176 When the interned string reaches a refcnt of 0 the string deallocation
177 function will delete the reference from this dictionary.
178
179 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000180 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000181*/
182static PyObject *interned;
183
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000184/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200185static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000186
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200187/* List of static strings. */
188static _Py_Identifier *static_strings;
189
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000190/* Single character Unicode strings in the Latin-1 range are being
191 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200192static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000193
Christian Heimes190d79e2008-01-30 11:58:22 +0000194/* Fast detection of the most frequent whitespace characters */
195const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000196 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000197/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000198/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000199/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000200/* case 0x000C: * FORM FEED */
201/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000202 0, 1, 1, 1, 1, 1, 0, 0,
203 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000204/* case 0x001C: * FILE SEPARATOR */
205/* case 0x001D: * GROUP SEPARATOR */
206/* case 0x001E: * RECORD SEPARATOR */
207/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000208 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000209/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000210 1, 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,
Christian Heimes190d79e2008-01-30 11:58:22 +0000214
Benjamin Peterson14339b62009-01-31 16:36:08 +0000215 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,
218 0, 0, 0, 0, 0, 0, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0,
220 0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000223};
224
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200225/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200226static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200227static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100228static int unicode_modifiable(PyObject *unicode);
229
Victor Stinnerfe226c02011-10-03 03:52:20 +0200230
Alexander Belopolsky40018472011-02-26 01:02:56 +0000231static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200232_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
233static PyObject *
234_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
235static PyObject *
236_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
237
238static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000239unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000240 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100241 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000242 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
243
Alexander Belopolsky40018472011-02-26 01:02:56 +0000244static void
245raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300246 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100247 PyObject *unicode,
248 Py_ssize_t startpos, Py_ssize_t endpos,
249 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000250
Christian Heimes190d79e2008-01-30 11:58:22 +0000251/* Same for linebreaks */
252static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000253 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000254/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000255/* 0x000B, * LINE TABULATION */
256/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000257/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000258 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000259 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000260/* 0x001C, * FILE SEPARATOR */
261/* 0x001D, * GROUP SEPARATOR */
262/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000263 0, 0, 0, 0, 1, 1, 1, 0,
264 0, 0, 0, 0, 0, 0, 0, 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,
Christian Heimes190d79e2008-01-30 11:58:22 +0000268
Benjamin Peterson14339b62009-01-31 16:36:08 +0000269 0, 0, 0, 0, 0, 0, 0, 0,
270 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
Christian Heimes190d79e2008-01-30 11:58:22 +0000277};
278
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300279/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
280 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000281Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000282PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000283{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000284#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000285 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000286#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000287 /* This is actually an illegal character, so it should
288 not be passed to unichr. */
289 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000290#endif
291}
292
Victor Stinner910337b2011-10-03 03:20:16 +0200293#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200294int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100295_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200296{
297 PyASCIIObject *ascii;
298 unsigned int kind;
299
300 assert(PyUnicode_Check(op));
301
302 ascii = (PyASCIIObject *)op;
303 kind = ascii->state.kind;
304
Victor Stinnera3b334d2011-10-03 13:53:37 +0200305 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200306 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200307 assert(ascii->state.ready == 1);
308 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200309 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200310 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200311 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200312
Victor Stinnera41463c2011-10-04 01:05:08 +0200313 if (ascii->state.compact == 1) {
314 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200315 assert(kind == PyUnicode_1BYTE_KIND
316 || kind == PyUnicode_2BYTE_KIND
317 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200318 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200319 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200320 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100321 }
322 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200323 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
324
325 data = unicode->data.any;
326 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100327 assert(ascii->length == 0);
328 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200329 assert(ascii->state.compact == 0);
330 assert(ascii->state.ascii == 0);
331 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100332 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200333 assert(ascii->wstr != NULL);
334 assert(data == NULL);
335 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200336 }
337 else {
338 assert(kind == PyUnicode_1BYTE_KIND
339 || kind == PyUnicode_2BYTE_KIND
340 || kind == PyUnicode_4BYTE_KIND);
341 assert(ascii->state.compact == 0);
342 assert(ascii->state.ready == 1);
343 assert(data != NULL);
344 if (ascii->state.ascii) {
345 assert (compact->utf8 == data);
346 assert (compact->utf8_length == ascii->length);
347 }
348 else
349 assert (compact->utf8 != data);
350 }
351 }
352 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200353 if (
354#if SIZEOF_WCHAR_T == 2
355 kind == PyUnicode_2BYTE_KIND
356#else
357 kind == PyUnicode_4BYTE_KIND
358#endif
359 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200360 {
361 assert(ascii->wstr == data);
362 assert(compact->wstr_length == ascii->length);
363 } else
364 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200365 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200366
367 if (compact->utf8 == NULL)
368 assert(compact->utf8_length == 0);
369 if (ascii->wstr == NULL)
370 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200371 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200372 /* check that the best kind is used */
373 if (check_content && kind != PyUnicode_WCHAR_KIND)
374 {
375 Py_ssize_t i;
376 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200377 void *data;
378 Py_UCS4 ch;
379
380 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200381 for (i=0; i < ascii->length; i++)
382 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200383 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200384 if (ch > maxchar)
385 maxchar = ch;
386 }
387 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100388 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200389 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100390 assert(maxchar <= 255);
391 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200392 else
393 assert(maxchar < 128);
394 }
Victor Stinner77faf692011-11-20 18:56:05 +0100395 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200396 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100397 assert(maxchar <= 0xFFFF);
398 }
399 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200400 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100401 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100402 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200403 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200404 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400405 return 1;
406}
Victor Stinner910337b2011-10-03 03:20:16 +0200407#endif
408
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100409static PyObject*
410unicode_result_wchar(PyObject *unicode)
411{
412#ifndef Py_DEBUG
413 Py_ssize_t len;
414
415 assert(Py_REFCNT(unicode) == 1);
416
417 len = _PyUnicode_WSTR_LENGTH(unicode);
418 if (len == 0) {
419 Py_INCREF(unicode_empty);
420 Py_DECREF(unicode);
421 return unicode_empty;
422 }
423
424 if (len == 1) {
425 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
426 if (ch < 256) {
427 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
428 Py_DECREF(unicode);
429 return latin1_char;
430 }
431 }
432
433 if (_PyUnicode_Ready(unicode) < 0) {
434 Py_XDECREF(unicode);
435 return NULL;
436 }
437#else
438 /* don't make the result ready in debug mode to ensure that the caller
439 makes the string ready before using it */
440 assert(_PyUnicode_CheckConsistency(unicode, 1));
441#endif
442 return unicode;
443}
444
445static PyObject*
446unicode_result_ready(PyObject *unicode)
447{
448 Py_ssize_t length;
449
450 length = PyUnicode_GET_LENGTH(unicode);
451 if (length == 0) {
452 if (unicode != unicode_empty) {
453 Py_INCREF(unicode_empty);
454 Py_DECREF(unicode);
455 }
456 return unicode_empty;
457 }
458
459 if (length == 1) {
460 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
461 if (ch < 256) {
462 PyObject *latin1_char = unicode_latin1[ch];
463 if (latin1_char != NULL) {
464 if (unicode != latin1_char) {
465 Py_INCREF(latin1_char);
466 Py_DECREF(unicode);
467 }
468 return latin1_char;
469 }
470 else {
471 assert(_PyUnicode_CheckConsistency(unicode, 1));
472 Py_INCREF(unicode);
473 unicode_latin1[ch] = unicode;
474 return unicode;
475 }
476 }
477 }
478
479 assert(_PyUnicode_CheckConsistency(unicode, 1));
480 return unicode;
481}
482
483static PyObject*
484unicode_result(PyObject *unicode)
485{
486 assert(_PyUnicode_CHECK(unicode));
487 if (PyUnicode_IS_READY(unicode))
488 return unicode_result_ready(unicode);
489 else
490 return unicode_result_wchar(unicode);
491}
492
Victor Stinnerc4b49542011-12-11 22:44:26 +0100493static PyObject*
494unicode_result_unchanged(PyObject *unicode)
495{
496 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500497 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100498 return NULL;
499 Py_INCREF(unicode);
500 return unicode;
501 }
502 else
503 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100504 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100505}
506
Victor Stinner3a50e702011-10-18 21:21:00 +0200507#ifdef HAVE_MBCS
508static OSVERSIONINFOEX winver;
509#endif
510
Thomas Wouters477c8d52006-05-27 19:21:47 +0000511/* --- Bloom Filters ----------------------------------------------------- */
512
513/* stuff to implement simple "bloom filters" for Unicode characters.
514 to keep things simple, we use a single bitmask, using the least 5
515 bits from each unicode characters as the bit index. */
516
517/* the linebreak mask is set up by Unicode_Init below */
518
Antoine Pitrouf068f942010-01-13 14:19:12 +0000519#if LONG_BIT >= 128
520#define BLOOM_WIDTH 128
521#elif LONG_BIT >= 64
522#define BLOOM_WIDTH 64
523#elif LONG_BIT >= 32
524#define BLOOM_WIDTH 32
525#else
526#error "LONG_BIT is smaller than 32"
527#endif
528
Thomas Wouters477c8d52006-05-27 19:21:47 +0000529#define BLOOM_MASK unsigned long
530
531static BLOOM_MASK bloom_linebreak;
532
Antoine Pitrouf068f942010-01-13 14:19:12 +0000533#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
534#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000535
Benjamin Peterson29060642009-01-31 22:14:21 +0000536#define BLOOM_LINEBREAK(ch) \
537 ((ch) < 128U ? ascii_linebreak[(ch)] : \
538 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539
Alexander Belopolsky40018472011-02-26 01:02:56 +0000540Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200541make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000542{
543 /* calculate simple bloom-style bitmask for a given unicode string */
544
Antoine Pitrouf068f942010-01-13 14:19:12 +0000545 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000546 Py_ssize_t i;
547
548 mask = 0;
549 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200550 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000551
552 return mask;
553}
554
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200555#define BLOOM_MEMBER(mask, chr, str) \
556 (BLOOM(mask, chr) \
557 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000558
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200559/* Compilation of templated routines */
560
561#include "stringlib/asciilib.h"
562#include "stringlib/fastsearch.h"
563#include "stringlib/partition.h"
564#include "stringlib/split.h"
565#include "stringlib/count.h"
566#include "stringlib/find.h"
567#include "stringlib/find_max_char.h"
568#include "stringlib/localeutil.h"
569#include "stringlib/undef.h"
570
571#include "stringlib/ucs1lib.h"
572#include "stringlib/fastsearch.h"
573#include "stringlib/partition.h"
574#include "stringlib/split.h"
575#include "stringlib/count.h"
576#include "stringlib/find.h"
577#include "stringlib/find_max_char.h"
578#include "stringlib/localeutil.h"
579#include "stringlib/undef.h"
580
581#include "stringlib/ucs2lib.h"
582#include "stringlib/fastsearch.h"
583#include "stringlib/partition.h"
584#include "stringlib/split.h"
585#include "stringlib/count.h"
586#include "stringlib/find.h"
587#include "stringlib/find_max_char.h"
588#include "stringlib/localeutil.h"
589#include "stringlib/undef.h"
590
591#include "stringlib/ucs4lib.h"
592#include "stringlib/fastsearch.h"
593#include "stringlib/partition.h"
594#include "stringlib/split.h"
595#include "stringlib/count.h"
596#include "stringlib/find.h"
597#include "stringlib/find_max_char.h"
598#include "stringlib/localeutil.h"
599#include "stringlib/undef.h"
600
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200601#include "stringlib/unicodedefs.h"
602#include "stringlib/fastsearch.h"
603#include "stringlib/count.h"
604#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100605#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200606
Guido van Rossumd57fd912000-03-10 22:53:23 +0000607/* --- Unicode Object ----------------------------------------------------- */
608
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200609static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200610fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200611
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200612Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
613 Py_ssize_t size, Py_UCS4 ch,
614 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200615{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200616 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
617
618 switch (kind) {
619 case PyUnicode_1BYTE_KIND:
620 {
621 Py_UCS1 ch1 = (Py_UCS1) ch;
622 if (ch1 == ch)
623 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
624 else
625 return -1;
626 }
627 case PyUnicode_2BYTE_KIND:
628 {
629 Py_UCS2 ch2 = (Py_UCS2) ch;
630 if (ch2 == ch)
631 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
632 else
633 return -1;
634 }
635 case PyUnicode_4BYTE_KIND:
636 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
637 default:
638 assert(0);
639 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200640 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200641}
642
Victor Stinnerfe226c02011-10-03 03:52:20 +0200643static PyObject*
644resize_compact(PyObject *unicode, Py_ssize_t length)
645{
646 Py_ssize_t char_size;
647 Py_ssize_t struct_size;
648 Py_ssize_t new_size;
649 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100650 PyObject *new_unicode;
Victor Stinner79891572012-05-03 13:43:07 +0200651 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200652 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100653 assert(PyUnicode_IS_COMPACT(unicode));
654
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200655 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100656 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200657 struct_size = sizeof(PyASCIIObject);
658 else
659 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200660 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200661
Victor Stinnerfe226c02011-10-03 03:52:20 +0200662 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
663 PyErr_NoMemory();
664 return NULL;
665 }
666 new_size = (struct_size + (length + 1) * char_size);
667
Victor Stinner84def372011-12-11 20:04:56 +0100668 _Py_DEC_REFTOTAL;
669 _Py_ForgetReference(unicode);
670
671 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
672 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100673 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200674 PyErr_NoMemory();
675 return NULL;
676 }
Victor Stinner84def372011-12-11 20:04:56 +0100677 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200678 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100679
Victor Stinnerfe226c02011-10-03 03:52:20 +0200680 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200681 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200682 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100683 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200684 _PyUnicode_WSTR_LENGTH(unicode) = length;
685 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200686 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
687 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200688 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200689 return unicode;
690}
691
Alexander Belopolsky40018472011-02-26 01:02:56 +0000692static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200693resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000694{
Victor Stinner95663112011-10-04 01:03:50 +0200695 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100696 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200697 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200698 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000699
Victor Stinnerfe226c02011-10-03 03:52:20 +0200700 if (PyUnicode_IS_READY(unicode)) {
701 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200702 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200703 void *data;
704
705 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200706 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200707 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
708 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200709
710 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
711 PyErr_NoMemory();
712 return -1;
713 }
714 new_size = (length + 1) * char_size;
715
Victor Stinner7a9105a2011-12-12 00:13:42 +0100716 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
717 {
718 PyObject_DEL(_PyUnicode_UTF8(unicode));
719 _PyUnicode_UTF8(unicode) = NULL;
720 _PyUnicode_UTF8_LENGTH(unicode) = 0;
721 }
722
Victor Stinnerfe226c02011-10-03 03:52:20 +0200723 data = (PyObject *)PyObject_REALLOC(data, new_size);
724 if (data == NULL) {
725 PyErr_NoMemory();
726 return -1;
727 }
728 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200729 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200730 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200731 _PyUnicode_WSTR_LENGTH(unicode) = length;
732 }
733 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200734 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200735 _PyUnicode_UTF8_LENGTH(unicode) = length;
736 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200737 _PyUnicode_LENGTH(unicode) = length;
738 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200739 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200740 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200741 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200742 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200743 }
Victor Stinner95663112011-10-04 01:03:50 +0200744 assert(_PyUnicode_WSTR(unicode) != NULL);
745
746 /* check for integer overflow */
747 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
748 PyErr_NoMemory();
749 return -1;
750 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100751 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200752 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100753 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200754 if (!wstr) {
755 PyErr_NoMemory();
756 return -1;
757 }
758 _PyUnicode_WSTR(unicode) = wstr;
759 _PyUnicode_WSTR(unicode)[length] = 0;
760 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200761 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000762 return 0;
763}
764
Victor Stinnerfe226c02011-10-03 03:52:20 +0200765static PyObject*
766resize_copy(PyObject *unicode, Py_ssize_t length)
767{
768 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100769 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200770 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100771
Benjamin Petersonbac79492012-01-14 13:34:47 -0500772 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100773 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200774
775 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
776 if (copy == NULL)
777 return NULL;
778
779 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200780 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200781 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200782 }
783 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200784 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100785
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200786 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200787 if (w == NULL)
788 return NULL;
789 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
790 copy_length = Py_MIN(copy_length, length);
791 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
792 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200793 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200794 }
795}
796
Guido van Rossumd57fd912000-03-10 22:53:23 +0000797/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000798 Ux0000 terminated; some code (e.g. new_identifier)
799 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000800
801 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000802 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000803
804*/
805
Alexander Belopolsky40018472011-02-26 01:02:56 +0000806static PyUnicodeObject *
807_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000808{
809 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200810 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000811
Thomas Wouters477c8d52006-05-27 19:21:47 +0000812 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000813 if (length == 0 && unicode_empty != NULL) {
814 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200815 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000816 }
817
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000818 /* Ensure we won't overflow the size. */
819 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
820 return (PyUnicodeObject *)PyErr_NoMemory();
821 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200822 if (length < 0) {
823 PyErr_SetString(PyExc_SystemError,
824 "Negative size passed to _PyUnicode_New");
825 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000826 }
827
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200828 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
829 if (unicode == NULL)
830 return NULL;
831 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
832 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
833 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100834 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000835 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100836 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000837 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200838
Jeremy Hyltond8082792003-09-16 19:41:39 +0000839 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000840 * the caller fails before initializing str -- unicode_resize()
841 * reads str[0], and the Keep-Alive optimization can keep memory
842 * allocated for str alive across a call to unicode_dealloc(unicode).
843 * We don't want unicode_resize to read uninitialized memory in
844 * that case.
845 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200846 _PyUnicode_WSTR(unicode)[0] = 0;
847 _PyUnicode_WSTR(unicode)[length] = 0;
848 _PyUnicode_WSTR_LENGTH(unicode) = length;
849 _PyUnicode_HASH(unicode) = -1;
850 _PyUnicode_STATE(unicode).interned = 0;
851 _PyUnicode_STATE(unicode).kind = 0;
852 _PyUnicode_STATE(unicode).compact = 0;
853 _PyUnicode_STATE(unicode).ready = 0;
854 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200855 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200856 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200857 _PyUnicode_UTF8(unicode) = NULL;
858 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100859 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000860 return unicode;
861}
862
Victor Stinnerf42dc442011-10-02 23:33:16 +0200863static const char*
864unicode_kind_name(PyObject *unicode)
865{
Victor Stinner42dfd712011-10-03 14:41:45 +0200866 /* don't check consistency: unicode_kind_name() is called from
867 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200868 if (!PyUnicode_IS_COMPACT(unicode))
869 {
870 if (!PyUnicode_IS_READY(unicode))
871 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600872 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200873 {
874 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200875 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200876 return "legacy ascii";
877 else
878 return "legacy latin1";
879 case PyUnicode_2BYTE_KIND:
880 return "legacy UCS2";
881 case PyUnicode_4BYTE_KIND:
882 return "legacy UCS4";
883 default:
884 return "<legacy invalid kind>";
885 }
886 }
887 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600888 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200889 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200890 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200891 return "ascii";
892 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200893 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200894 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200895 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200896 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200897 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200898 default:
899 return "<invalid compact kind>";
900 }
901}
902
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200903#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200904/* Functions wrapping macros for use in debugger */
905char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200906 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200907}
908
909void *_PyUnicode_compact_data(void *unicode) {
910 return _PyUnicode_COMPACT_DATA(unicode);
911}
912void *_PyUnicode_data(void *unicode){
913 printf("obj %p\n", unicode);
914 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
915 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
916 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
917 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
918 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
919 return PyUnicode_DATA(unicode);
920}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200921
922void
923_PyUnicode_Dump(PyObject *op)
924{
925 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200926 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
927 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
928 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200929
Victor Stinnera849a4b2011-10-03 12:12:11 +0200930 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200931 {
932 if (ascii->state.ascii)
933 data = (ascii + 1);
934 else
935 data = (compact + 1);
936 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200937 else
938 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200939 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
940
Victor Stinnera849a4b2011-10-03 12:12:11 +0200941 if (ascii->wstr == data)
942 printf("shared ");
943 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200944
Victor Stinnera3b334d2011-10-03 13:53:37 +0200945 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200946 printf(" (%zu), ", compact->wstr_length);
947 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
948 printf("shared ");
949 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200950 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200951 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200952}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200953#endif
954
955PyObject *
956PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
957{
958 PyObject *obj;
959 PyCompactUnicodeObject *unicode;
960 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +0200961 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200962 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200963 Py_ssize_t char_size;
964 Py_ssize_t struct_size;
965
966 /* Optimization for empty strings */
967 if (size == 0 && unicode_empty != NULL) {
968 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200969 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200970 }
971
Victor Stinner9e9d6892011-10-04 01:02:02 +0200972 is_ascii = 0;
973 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200974 struct_size = sizeof(PyCompactUnicodeObject);
975 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +0200976 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200977 char_size = 1;
978 is_ascii = 1;
979 struct_size = sizeof(PyASCIIObject);
980 }
981 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +0200982 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200983 char_size = 1;
984 }
985 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +0200986 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987 char_size = 2;
988 if (sizeof(wchar_t) == 2)
989 is_sharing = 1;
990 }
991 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +0100992 if (maxchar > MAX_UNICODE) {
993 PyErr_SetString(PyExc_SystemError,
994 "invalid maximum character passed to PyUnicode_New");
995 return NULL;
996 }
Victor Stinner8f825062012-04-27 13:55:39 +0200997 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200998 char_size = 4;
999 if (sizeof(wchar_t) == 4)
1000 is_sharing = 1;
1001 }
1002
1003 /* Ensure we won't overflow the size. */
1004 if (size < 0) {
1005 PyErr_SetString(PyExc_SystemError,
1006 "Negative size passed to PyUnicode_New");
1007 return NULL;
1008 }
1009 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1010 return PyErr_NoMemory();
1011
1012 /* Duplicated allocation code from _PyObject_New() instead of a call to
1013 * PyObject_New() so we are able to allocate space for the object and
1014 * it's data buffer.
1015 */
1016 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1017 if (obj == NULL)
1018 return PyErr_NoMemory();
1019 obj = PyObject_INIT(obj, &PyUnicode_Type);
1020 if (obj == NULL)
1021 return NULL;
1022
1023 unicode = (PyCompactUnicodeObject *)obj;
1024 if (is_ascii)
1025 data = ((PyASCIIObject*)obj) + 1;
1026 else
1027 data = unicode + 1;
1028 _PyUnicode_LENGTH(unicode) = size;
1029 _PyUnicode_HASH(unicode) = -1;
1030 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001031 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001032 _PyUnicode_STATE(unicode).compact = 1;
1033 _PyUnicode_STATE(unicode).ready = 1;
1034 _PyUnicode_STATE(unicode).ascii = is_ascii;
1035 if (is_ascii) {
1036 ((char*)data)[size] = 0;
1037 _PyUnicode_WSTR(unicode) = NULL;
1038 }
Victor Stinner8f825062012-04-27 13:55:39 +02001039 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001040 ((char*)data)[size] = 0;
1041 _PyUnicode_WSTR(unicode) = NULL;
1042 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001043 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001044 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001045 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001046 else {
1047 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001048 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001049 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001050 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001051 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 ((Py_UCS4*)data)[size] = 0;
1053 if (is_sharing) {
1054 _PyUnicode_WSTR_LENGTH(unicode) = size;
1055 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1056 }
1057 else {
1058 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1059 _PyUnicode_WSTR(unicode) = NULL;
1060 }
1061 }
Victor Stinner8f825062012-04-27 13:55:39 +02001062#ifdef Py_DEBUG
1063 /* Fill the data with invalid characters to detect bugs earlier.
1064 _PyUnicode_CheckConsistency(str, 1) detects invalid characters,
1065 at least for ASCII and UCS-4 strings. U+00FF is invalid in ASCII
1066 and U+FFFFFFFF is an invalid character in Unicode 6.0. */
1067 memset(data, 0xff, size * kind);
1068#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001069 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001070 return obj;
1071}
1072
1073#if SIZEOF_WCHAR_T == 2
1074/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1075 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001076 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001077
1078 This function assumes that unicode can hold one more code point than wstr
1079 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001080static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001081unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001082 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001083{
1084 const wchar_t *iter;
1085 Py_UCS4 *ucs4_out;
1086
Victor Stinner910337b2011-10-03 03:20:16 +02001087 assert(unicode != NULL);
1088 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001089 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1090 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1091
1092 for (iter = begin; iter < end; ) {
1093 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1094 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001095 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1096 && (iter+1) < end
1097 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001098 {
Victor Stinner551ac952011-11-29 22:58:13 +01001099 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001100 iter += 2;
1101 }
1102 else {
1103 *ucs4_out++ = *iter;
1104 iter++;
1105 }
1106 }
1107 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1108 _PyUnicode_GET_LENGTH(unicode)));
1109
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001110}
1111#endif
1112
Victor Stinnercd9950f2011-10-02 00:34:53 +02001113static int
Victor Stinner488fa492011-12-12 00:01:39 +01001114unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001115{
Victor Stinner488fa492011-12-12 00:01:39 +01001116 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001117 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001118 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001119 return -1;
1120 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001121 return 0;
1122}
1123
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001124static int
1125_copy_characters(PyObject *to, Py_ssize_t to_start,
1126 PyObject *from, Py_ssize_t from_start,
1127 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001128{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001129 unsigned int from_kind, to_kind;
1130 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001131 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001132
Victor Stinneree4544c2012-05-09 22:24:08 +02001133 assert(0 <= how_many);
1134 assert(0 <= from_start);
1135 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001136 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001137 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001138 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
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
Victor Stinnerd3f08822012-05-29 12:57:52 +02001143 assert(PyUnicode_Check(to));
1144 assert(PyUnicode_IS_READY(to));
1145 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001147 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001148 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001149 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001150 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001151
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001152#ifdef Py_DEBUG
1153 if (!check_maxchar
1154 && (from_kind > to_kind
1155 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001156 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001157 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1158 Py_UCS4 ch;
1159 Py_ssize_t i;
1160 for (i=0; i < how_many; i++) {
1161 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1162 assert(ch <= to_maxchar);
1163 }
1164 }
1165#endif
1166 fast = (from_kind == to_kind);
1167 if (check_maxchar
1168 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1169 {
1170 /* deny latin1 => ascii */
1171 fast = 0;
1172 }
1173
1174 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001175 Py_MEMCPY((char*)to_data + to_kind * to_start,
1176 (char*)from_data + from_kind * from_start,
1177 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001178 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001179 else if (from_kind == PyUnicode_1BYTE_KIND
1180 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001181 {
1182 _PyUnicode_CONVERT_BYTES(
1183 Py_UCS1, Py_UCS2,
1184 PyUnicode_1BYTE_DATA(from) + from_start,
1185 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1186 PyUnicode_2BYTE_DATA(to) + to_start
1187 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001188 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001189 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001190 && to_kind == PyUnicode_4BYTE_KIND)
1191 {
1192 _PyUnicode_CONVERT_BYTES(
1193 Py_UCS1, Py_UCS4,
1194 PyUnicode_1BYTE_DATA(from) + from_start,
1195 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1196 PyUnicode_4BYTE_DATA(to) + to_start
1197 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001198 }
1199 else if (from_kind == PyUnicode_2BYTE_KIND
1200 && to_kind == PyUnicode_4BYTE_KIND)
1201 {
1202 _PyUnicode_CONVERT_BYTES(
1203 Py_UCS2, Py_UCS4,
1204 PyUnicode_2BYTE_DATA(from) + from_start,
1205 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1206 PyUnicode_4BYTE_DATA(to) + to_start
1207 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001208 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001209 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001210 /* check if max_char(from substring) <= max_char(to) */
1211 if (from_kind > to_kind
1212 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001213 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001214 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001215 /* slow path to check for character overflow */
1216 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001217 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001218 Py_ssize_t i;
1219
Victor Stinner56c161a2011-10-06 02:47:11 +02001220#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001221 for (i=0; i < how_many; i++) {
1222 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001223 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001224 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1225 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001226#else
1227 if (!check_maxchar) {
1228 for (i=0; i < how_many; i++) {
1229 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1230 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1231 }
1232 }
1233 else {
1234 for (i=0; i < how_many; i++) {
1235 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1236 if (ch > to_maxchar)
1237 return 1;
1238 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1239 }
1240 }
1241#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001242 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001243 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001244 assert(0 && "inconsistent state");
1245 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001246 }
1247 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001248 return 0;
1249}
1250
Victor Stinnerd3f08822012-05-29 12:57:52 +02001251void
1252_PyUnicode_FastCopyCharacters(
1253 PyObject *to, Py_ssize_t to_start,
1254 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001255{
1256 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1257}
1258
1259Py_ssize_t
1260PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1261 PyObject *from, Py_ssize_t from_start,
1262 Py_ssize_t how_many)
1263{
1264 int err;
1265
1266 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1267 PyErr_BadInternalCall();
1268 return -1;
1269 }
1270
Benjamin Petersonbac79492012-01-14 13:34:47 -05001271 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001272 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001273 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001274 return -1;
1275
Victor Stinnerd3f08822012-05-29 12:57:52 +02001276 if (from_start < 0) {
1277 PyErr_SetString(PyExc_IndexError, "string index out of range");
1278 return -1;
1279 }
1280 if (to_start < 0) {
1281 PyErr_SetString(PyExc_IndexError, "string index out of range");
1282 return -1;
1283 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001284 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1285 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1286 PyErr_Format(PyExc_SystemError,
1287 "Cannot write %zi characters at %zi "
1288 "in a string of %zi characters",
1289 how_many, to_start, PyUnicode_GET_LENGTH(to));
1290 return -1;
1291 }
1292
1293 if (how_many == 0)
1294 return 0;
1295
Victor Stinner488fa492011-12-12 00:01:39 +01001296 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001297 return -1;
1298
1299 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1300 if (err) {
1301 PyErr_Format(PyExc_SystemError,
1302 "Cannot copy %s characters "
1303 "into a string of %s characters",
1304 unicode_kind_name(from),
1305 unicode_kind_name(to));
1306 return -1;
1307 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001308 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001309}
1310
Victor Stinner17222162011-09-28 22:15:37 +02001311/* Find the maximum code point and count the number of surrogate pairs so a
1312 correct string length can be computed before converting a string to UCS4.
1313 This function counts single surrogates as a character and not as a pair.
1314
1315 Return 0 on success, or -1 on error. */
1316static int
1317find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1318 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001319{
1320 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001321 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001322
Victor Stinnerc53be962011-10-02 21:33:54 +02001323 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324 *num_surrogates = 0;
1325 *maxchar = 0;
1326
1327 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001328#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001329 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1330 && (iter+1) < end
1331 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001332 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001333 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001334 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001335 iter += 2;
1336 }
1337 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001338#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001339 {
1340 ch = *iter;
1341 iter++;
1342 }
1343 if (ch > *maxchar) {
1344 *maxchar = ch;
1345 if (*maxchar > MAX_UNICODE) {
1346 PyErr_Format(PyExc_ValueError,
1347 "character U+%x is not in range [U+0000; U+10ffff]",
1348 ch);
1349 return -1;
1350 }
1351 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001352 }
1353 return 0;
1354}
1355
1356#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001357static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001358#endif
1359
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001360int
1361_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001362{
1363 wchar_t *end;
1364 Py_UCS4 maxchar = 0;
1365 Py_ssize_t num_surrogates;
1366#if SIZEOF_WCHAR_T == 2
1367 Py_ssize_t length_wo_surrogates;
1368#endif
1369
Georg Brandl7597add2011-10-05 16:36:47 +02001370 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001371 strings were created using _PyObject_New() and where no canonical
1372 representation (the str field) has been set yet aka strings
1373 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001374 assert(_PyUnicode_CHECK(unicode));
1375 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001376 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001377 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001378 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001379 /* Actually, it should neither be interned nor be anything else: */
1380 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001381
1382#ifdef Py_DEBUG
1383 ++unicode_ready_calls;
1384#endif
1385
1386 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001387 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001388 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001389 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001390
1391 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001392 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1393 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001394 PyErr_NoMemory();
1395 return -1;
1396 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001397 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001398 _PyUnicode_WSTR(unicode), end,
1399 PyUnicode_1BYTE_DATA(unicode));
1400 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1401 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1402 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1403 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001404 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001405 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001406 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001407 }
1408 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001409 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001410 _PyUnicode_UTF8(unicode) = NULL;
1411 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001412 }
1413 PyObject_FREE(_PyUnicode_WSTR(unicode));
1414 _PyUnicode_WSTR(unicode) = NULL;
1415 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1416 }
1417 /* In this case we might have to convert down from 4-byte native
1418 wchar_t to 2-byte unicode. */
1419 else if (maxchar < 65536) {
1420 assert(num_surrogates == 0 &&
1421 "FindMaxCharAndNumSurrogatePairs() messed up");
1422
Victor Stinner506f5922011-09-28 22:34:18 +02001423#if SIZEOF_WCHAR_T == 2
1424 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001425 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001426 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1427 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1428 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001429 _PyUnicode_UTF8(unicode) = NULL;
1430 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001431#else
1432 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001433 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001434 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001435 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001436 PyErr_NoMemory();
1437 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001438 }
Victor Stinner506f5922011-09-28 22:34:18 +02001439 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1440 _PyUnicode_WSTR(unicode), end,
1441 PyUnicode_2BYTE_DATA(unicode));
1442 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1443 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1444 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001445 _PyUnicode_UTF8(unicode) = NULL;
1446 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001447 PyObject_FREE(_PyUnicode_WSTR(unicode));
1448 _PyUnicode_WSTR(unicode) = NULL;
1449 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1450#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001451 }
1452 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1453 else {
1454#if SIZEOF_WCHAR_T == 2
1455 /* in case the native representation is 2-bytes, we need to allocate a
1456 new normalized 4-byte version. */
1457 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001458 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1459 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001460 PyErr_NoMemory();
1461 return -1;
1462 }
1463 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1464 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001465 _PyUnicode_UTF8(unicode) = NULL;
1466 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001467 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1468 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001469 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001470 PyObject_FREE(_PyUnicode_WSTR(unicode));
1471 _PyUnicode_WSTR(unicode) = NULL;
1472 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1473#else
1474 assert(num_surrogates == 0);
1475
Victor Stinnerc3c74152011-10-02 20:39:55 +02001476 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001477 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001478 _PyUnicode_UTF8(unicode) = NULL;
1479 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001480 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1481#endif
1482 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1483 }
1484 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001485 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001486 return 0;
1487}
1488
Alexander Belopolsky40018472011-02-26 01:02:56 +00001489static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001490unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001491{
Walter Dörwald16807132007-05-25 13:52:07 +00001492 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001493 case SSTATE_NOT_INTERNED:
1494 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001495
Benjamin Peterson29060642009-01-31 22:14:21 +00001496 case SSTATE_INTERNED_MORTAL:
1497 /* revive dead object temporarily for DelItem */
1498 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001499 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001500 Py_FatalError(
1501 "deletion of interned string failed");
1502 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001503
Benjamin Peterson29060642009-01-31 22:14:21 +00001504 case SSTATE_INTERNED_IMMORTAL:
1505 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001506
Benjamin Peterson29060642009-01-31 22:14:21 +00001507 default:
1508 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001509 }
1510
Victor Stinner03490912011-10-03 23:45:12 +02001511 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001512 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001513 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001514 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001515 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1516 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001517
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001518 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001519}
1520
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001521#ifdef Py_DEBUG
1522static int
1523unicode_is_singleton(PyObject *unicode)
1524{
1525 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1526 if (unicode == unicode_empty)
1527 return 1;
1528 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1529 {
1530 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1531 if (ch < 256 && unicode_latin1[ch] == unicode)
1532 return 1;
1533 }
1534 return 0;
1535}
1536#endif
1537
Alexander Belopolsky40018472011-02-26 01:02:56 +00001538static int
Victor Stinner488fa492011-12-12 00:01:39 +01001539unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001540{
Victor Stinner488fa492011-12-12 00:01:39 +01001541 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001542 if (Py_REFCNT(unicode) != 1)
1543 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001544 if (_PyUnicode_HASH(unicode) != -1)
1545 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001546 if (PyUnicode_CHECK_INTERNED(unicode))
1547 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001548 if (!PyUnicode_CheckExact(unicode))
1549 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001550#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001551 /* singleton refcount is greater than 1 */
1552 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001553#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001554 return 1;
1555}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001556
Victor Stinnerfe226c02011-10-03 03:52:20 +02001557static int
1558unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1559{
1560 PyObject *unicode;
1561 Py_ssize_t old_length;
1562
1563 assert(p_unicode != NULL);
1564 unicode = *p_unicode;
1565
1566 assert(unicode != NULL);
1567 assert(PyUnicode_Check(unicode));
1568 assert(0 <= length);
1569
Victor Stinner910337b2011-10-03 03:20:16 +02001570 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001571 old_length = PyUnicode_WSTR_LENGTH(unicode);
1572 else
1573 old_length = PyUnicode_GET_LENGTH(unicode);
1574 if (old_length == length)
1575 return 0;
1576
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001577 if (length == 0) {
1578 Py_DECREF(*p_unicode);
1579 *p_unicode = unicode_empty;
1580 Py_INCREF(*p_unicode);
1581 return 0;
1582 }
1583
Victor Stinner488fa492011-12-12 00:01:39 +01001584 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001585 PyObject *copy = resize_copy(unicode, length);
1586 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001587 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001588 Py_DECREF(*p_unicode);
1589 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001590 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001591 }
1592
Victor Stinnerfe226c02011-10-03 03:52:20 +02001593 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001594 PyObject *new_unicode = resize_compact(unicode, length);
1595 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001596 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001597 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001598 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001599 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001600 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001601}
1602
Alexander Belopolsky40018472011-02-26 01:02:56 +00001603int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001604PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001605{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001606 PyObject *unicode;
1607 if (p_unicode == NULL) {
1608 PyErr_BadInternalCall();
1609 return -1;
1610 }
1611 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001612 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001613 {
1614 PyErr_BadInternalCall();
1615 return -1;
1616 }
1617 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001618}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001619
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001620static int
Victor Stinner1b487b42012-05-03 12:29:04 +02001621unicode_widen(PyObject **p_unicode, Py_ssize_t length,
1622 unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001623{
1624 PyObject *result;
1625 assert(PyUnicode_IS_READY(*p_unicode));
Victor Stinner1b487b42012-05-03 12:29:04 +02001626 assert(length <= PyUnicode_GET_LENGTH(*p_unicode));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001627 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1628 return 0;
1629 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1630 maxchar);
1631 if (result == NULL)
1632 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001633 _PyUnicode_FastCopyCharacters(result, 0, *p_unicode, 0, length);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001634 Py_DECREF(*p_unicode);
1635 *p_unicode = result;
1636 return 0;
1637}
1638
1639static int
1640unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1641 Py_UCS4 ch)
1642{
Victor Stinner15e9ed22012-02-22 13:36:20 +01001643 assert(ch <= MAX_UNICODE);
Victor Stinner1b487b42012-05-03 12:29:04 +02001644 if (unicode_widen(p_unicode, *pos, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001645 return -1;
1646 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1647 PyUnicode_DATA(*p_unicode),
1648 (*pos)++, ch);
1649 return 0;
1650}
1651
Victor Stinnerc5166102012-02-22 13:55:02 +01001652/* Copy a ASCII or latin1 char* string into a Python Unicode string.
1653 Return the length of the input string.
1654
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001655 WARNING: The function doesn't copy the terminating null character and
1656 doesn't check the maximum character (may write a latin1 character in an
1657 ASCII string). */
Victor Stinnerc5166102012-02-22 13:55:02 +01001658static Py_ssize_t
1659unicode_write_cstr(PyObject *unicode, Py_ssize_t index, const char *str)
1660{
1661 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1662 void *data = PyUnicode_DATA(unicode);
1663
1664 switch (kind) {
1665 case PyUnicode_1BYTE_KIND: {
1666 Py_ssize_t len = strlen(str);
1667 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001668 memcpy((char *) data + index, str, len);
Victor Stinnerc5166102012-02-22 13:55:02 +01001669 return len;
1670 }
1671 case PyUnicode_2BYTE_KIND: {
1672 Py_UCS2 *start = (Py_UCS2 *)data + index;
1673 Py_UCS2 *ucs2 = start;
1674 assert(index <= PyUnicode_GET_LENGTH(unicode));
1675
1676 for (; *str; ++ucs2, ++str)
1677 *ucs2 = (Py_UCS2)*str;
1678
1679 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
1680 return ucs2 - start;
1681 }
1682 default: {
1683 Py_UCS4 *start = (Py_UCS4 *)data + index;
1684 Py_UCS4 *ucs4 = start;
1685 assert(kind == PyUnicode_4BYTE_KIND);
1686 assert(index <= PyUnicode_GET_LENGTH(unicode));
1687
1688 for (; *str; ++ucs4, ++str)
1689 *ucs4 = (Py_UCS4)*str;
1690
1691 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
1692 return ucs4 - start;
1693 }
1694 }
1695}
1696
1697
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001698static PyObject*
1699get_latin1_char(unsigned char ch)
1700{
Victor Stinnera464fc12011-10-02 20:39:30 +02001701 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001702 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001703 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001704 if (!unicode)
1705 return NULL;
1706 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001707 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001708 unicode_latin1[ch] = unicode;
1709 }
1710 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001711 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001712}
1713
Alexander Belopolsky40018472011-02-26 01:02:56 +00001714PyObject *
1715PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001716{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001717 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001718 Py_UCS4 maxchar = 0;
1719 Py_ssize_t num_surrogates;
1720
1721 if (u == NULL)
1722 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001723
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001724 /* If the Unicode data is known at construction time, we can apply
1725 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001726
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001727 /* Optimization for empty strings */
1728 if (size == 0 && unicode_empty != NULL) {
1729 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001730 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001731 }
Tim Petersced69f82003-09-16 20:30:58 +00001732
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001733 /* Single character Unicode objects in the Latin-1 range are
1734 shared when using this constructor */
1735 if (size == 1 && *u < 256)
1736 return get_latin1_char((unsigned char)*u);
1737
1738 /* If not empty and not single character, copy the Unicode data
1739 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001740 if (find_maxchar_surrogates(u, u + size,
1741 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001742 return NULL;
1743
Victor Stinner8faf8212011-12-08 22:14:11 +01001744 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001745 if (!unicode)
1746 return NULL;
1747
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001748 switch (PyUnicode_KIND(unicode)) {
1749 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001750 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001751 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1752 break;
1753 case PyUnicode_2BYTE_KIND:
1754#if Py_UNICODE_SIZE == 2
1755 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1756#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001757 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1759#endif
1760 break;
1761 case PyUnicode_4BYTE_KIND:
1762#if SIZEOF_WCHAR_T == 2
1763 /* This is the only case which has to process surrogates, thus
1764 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001765 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001766#else
1767 assert(num_surrogates == 0);
1768 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1769#endif
1770 break;
1771 default:
1772 assert(0 && "Impossible state");
1773 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001774
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001775 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001776}
1777
Alexander Belopolsky40018472011-02-26 01:02:56 +00001778PyObject *
1779PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001780{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001781 if (size < 0) {
1782 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001783 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001784 return NULL;
1785 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001786 if (u != NULL)
1787 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1788 else
1789 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001790}
1791
Alexander Belopolsky40018472011-02-26 01:02:56 +00001792PyObject *
1793PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001794{
1795 size_t size = strlen(u);
1796 if (size > PY_SSIZE_T_MAX) {
1797 PyErr_SetString(PyExc_OverflowError, "input too long");
1798 return NULL;
1799 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001800 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001801}
1802
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001803PyObject *
1804_PyUnicode_FromId(_Py_Identifier *id)
1805{
1806 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001807 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1808 strlen(id->string),
1809 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001810 if (!id->object)
1811 return NULL;
1812 PyUnicode_InternInPlace(&id->object);
1813 assert(!id->next);
1814 id->next = static_strings;
1815 static_strings = id;
1816 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001817 return id->object;
1818}
1819
1820void
1821_PyUnicode_ClearStaticStrings()
1822{
1823 _Py_Identifier *i;
1824 for (i = static_strings; i; i = i->next) {
1825 Py_DECREF(i->object);
1826 i->object = NULL;
1827 i->next = NULL;
1828 }
1829}
1830
Benjamin Peterson0df54292012-03-26 14:50:32 -04001831/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001832
Victor Stinnerd3f08822012-05-29 12:57:52 +02001833PyObject*
1834_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001835{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001836 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001837 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001838 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001839#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001840 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001841#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001842 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001843 }
Victor Stinner785938e2011-12-11 20:09:03 +01001844 unicode = PyUnicode_New(size, 127);
1845 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001846 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001847 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1848 assert(_PyUnicode_CheckConsistency(unicode, 1));
1849 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001850}
1851
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001852static Py_UCS4
1853kind_maxchar_limit(unsigned int kind)
1854{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001855 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001856 case PyUnicode_1BYTE_KIND:
1857 return 0x80;
1858 case PyUnicode_2BYTE_KIND:
1859 return 0x100;
1860 case PyUnicode_4BYTE_KIND:
1861 return 0x10000;
1862 default:
1863 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001864 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001865 }
1866}
1867
Victor Stinnere6abb482012-05-02 01:15:40 +02001868Py_LOCAL_INLINE(Py_UCS4)
1869align_maxchar(Py_UCS4 maxchar)
1870{
1871 if (maxchar <= 127)
1872 return 127;
1873 else if (maxchar <= 255)
1874 return 255;
1875 else if (maxchar <= 65535)
1876 return 65535;
1877 else
1878 return MAX_UNICODE;
1879}
1880
Victor Stinner702c7342011-10-05 13:50:52 +02001881static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001882_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001883{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001884 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001885 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001886
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001887 if (size == 0) {
1888 Py_INCREF(unicode_empty);
1889 return unicode_empty;
1890 }
1891 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001892 if (size == 1)
1893 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001894
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001895 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001896 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001897 if (!res)
1898 return NULL;
1899 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001900 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001901 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001902}
1903
Victor Stinnere57b1c02011-09-28 22:20:48 +02001904static PyObject*
1905_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001906{
1907 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001908 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001909
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001910 if (size == 0) {
1911 Py_INCREF(unicode_empty);
1912 return unicode_empty;
1913 }
1914 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001915 if (size == 1) {
1916 Py_UCS4 ch = u[0];
1917 if (ch < 256)
1918 return get_latin1_char((unsigned char)ch);
1919
1920 res = PyUnicode_New(1, ch);
1921 if (res == NULL)
1922 return NULL;
1923 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1924 assert(_PyUnicode_CheckConsistency(res, 1));
1925 return res;
1926 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001927
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001928 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001929 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001930 if (!res)
1931 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001932 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001933 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001934 else {
1935 _PyUnicode_CONVERT_BYTES(
1936 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1937 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001938 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001939 return res;
1940}
1941
Victor Stinnere57b1c02011-09-28 22:20:48 +02001942static PyObject*
1943_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001944{
1945 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001946 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001947
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001948 if (size == 0) {
1949 Py_INCREF(unicode_empty);
1950 return unicode_empty;
1951 }
1952 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001953 if (size == 1) {
1954 Py_UCS4 ch = u[0];
1955 if (ch < 256)
1956 return get_latin1_char((unsigned char)ch);
1957
1958 res = PyUnicode_New(1, ch);
1959 if (res == NULL)
1960 return NULL;
1961 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1962 assert(_PyUnicode_CheckConsistency(res, 1));
1963 return res;
1964 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001965
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001966 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001967 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001968 if (!res)
1969 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001970 if (max_char < 256)
1971 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1972 PyUnicode_1BYTE_DATA(res));
1973 else if (max_char < 0x10000)
1974 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1975 PyUnicode_2BYTE_DATA(res));
1976 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001977 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001978 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001979 return res;
1980}
1981
1982PyObject*
1983PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1984{
Victor Stinnercfed46e2011-11-22 01:29:14 +01001985 if (size < 0) {
1986 PyErr_SetString(PyExc_ValueError, "size must be positive");
1987 return NULL;
1988 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06001989 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001990 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001991 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001992 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001993 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001994 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001995 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001996 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02001997 PyErr_SetString(PyExc_SystemError, "invalid kind");
1998 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001999 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002000}
2001
Victor Stinnerece58de2012-04-23 23:36:38 +02002002Py_UCS4
2003_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2004{
2005 enum PyUnicode_Kind kind;
2006 void *startptr, *endptr;
2007
2008 assert(PyUnicode_IS_READY(unicode));
2009 assert(0 <= start);
2010 assert(end <= PyUnicode_GET_LENGTH(unicode));
2011 assert(start <= end);
2012
2013 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2014 return PyUnicode_MAX_CHAR_VALUE(unicode);
2015
2016 if (start == end)
2017 return 127;
2018
Victor Stinner94d558b2012-04-27 22:26:58 +02002019 if (PyUnicode_IS_ASCII(unicode))
2020 return 127;
2021
Victor Stinnerece58de2012-04-23 23:36:38 +02002022 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002023 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002024 endptr = (char *)startptr + end * kind;
2025 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002026 switch(kind) {
2027 case PyUnicode_1BYTE_KIND:
2028 return ucs1lib_find_max_char(startptr, endptr);
2029 case PyUnicode_2BYTE_KIND:
2030 return ucs2lib_find_max_char(startptr, endptr);
2031 case PyUnicode_4BYTE_KIND:
2032 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002033 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002034 assert(0);
2035 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002036 }
2037}
2038
Victor Stinner25a4b292011-10-06 12:31:55 +02002039/* Ensure that a string uses the most efficient storage, if it is not the
2040 case: create a new string with of the right kind. Write NULL into *p_unicode
2041 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002042static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002043unicode_adjust_maxchar(PyObject **p_unicode)
2044{
2045 PyObject *unicode, *copy;
2046 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002047 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002048 unsigned int kind;
2049
2050 assert(p_unicode != NULL);
2051 unicode = *p_unicode;
2052 assert(PyUnicode_IS_READY(unicode));
2053 if (PyUnicode_IS_ASCII(unicode))
2054 return;
2055
2056 len = PyUnicode_GET_LENGTH(unicode);
2057 kind = PyUnicode_KIND(unicode);
2058 if (kind == PyUnicode_1BYTE_KIND) {
2059 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002060 max_char = ucs1lib_find_max_char(u, u + len);
2061 if (max_char >= 128)
2062 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002063 }
2064 else if (kind == PyUnicode_2BYTE_KIND) {
2065 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002066 max_char = ucs2lib_find_max_char(u, u + len);
2067 if (max_char >= 256)
2068 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002069 }
2070 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002071 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002072 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002073 max_char = ucs4lib_find_max_char(u, u + len);
2074 if (max_char >= 0x10000)
2075 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002076 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002077 copy = PyUnicode_New(len, max_char);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002078 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002079 Py_DECREF(unicode);
2080 *p_unicode = copy;
2081}
2082
Victor Stinner034f6cf2011-09-30 02:26:44 +02002083PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002084_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002085{
Victor Stinner87af4f22011-11-21 23:03:47 +01002086 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002087 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002088
Victor Stinner034f6cf2011-09-30 02:26:44 +02002089 if (!PyUnicode_Check(unicode)) {
2090 PyErr_BadInternalCall();
2091 return NULL;
2092 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002093 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002094 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002095
Victor Stinner87af4f22011-11-21 23:03:47 +01002096 length = PyUnicode_GET_LENGTH(unicode);
2097 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002098 if (!copy)
2099 return NULL;
2100 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2101
Victor Stinner87af4f22011-11-21 23:03:47 +01002102 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2103 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002104 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002105 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002106}
2107
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002108
Victor Stinnerbc603d12011-10-02 01:00:40 +02002109/* Widen Unicode objects to larger buffers. Don't write terminating null
2110 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002111
2112void*
2113_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2114{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002115 Py_ssize_t len;
2116 void *result;
2117 unsigned int skind;
2118
Benjamin Petersonbac79492012-01-14 13:34:47 -05002119 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002120 return NULL;
2121
2122 len = PyUnicode_GET_LENGTH(s);
2123 skind = PyUnicode_KIND(s);
2124 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002125 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002126 return NULL;
2127 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002128 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002129 case PyUnicode_2BYTE_KIND:
2130 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2131 if (!result)
2132 return PyErr_NoMemory();
2133 assert(skind == PyUnicode_1BYTE_KIND);
2134 _PyUnicode_CONVERT_BYTES(
2135 Py_UCS1, Py_UCS2,
2136 PyUnicode_1BYTE_DATA(s),
2137 PyUnicode_1BYTE_DATA(s) + len,
2138 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002139 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002140 case PyUnicode_4BYTE_KIND:
2141 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2142 if (!result)
2143 return PyErr_NoMemory();
2144 if (skind == PyUnicode_2BYTE_KIND) {
2145 _PyUnicode_CONVERT_BYTES(
2146 Py_UCS2, Py_UCS4,
2147 PyUnicode_2BYTE_DATA(s),
2148 PyUnicode_2BYTE_DATA(s) + len,
2149 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002150 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002151 else {
2152 assert(skind == PyUnicode_1BYTE_KIND);
2153 _PyUnicode_CONVERT_BYTES(
2154 Py_UCS1, Py_UCS4,
2155 PyUnicode_1BYTE_DATA(s),
2156 PyUnicode_1BYTE_DATA(s) + len,
2157 result);
2158 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002159 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002160 default:
2161 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002162 }
Victor Stinner01698042011-10-04 00:04:26 +02002163 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002164 return NULL;
2165}
2166
2167static Py_UCS4*
2168as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2169 int copy_null)
2170{
2171 int kind;
2172 void *data;
2173 Py_ssize_t len, targetlen;
2174 if (PyUnicode_READY(string) == -1)
2175 return NULL;
2176 kind = PyUnicode_KIND(string);
2177 data = PyUnicode_DATA(string);
2178 len = PyUnicode_GET_LENGTH(string);
2179 targetlen = len;
2180 if (copy_null)
2181 targetlen++;
2182 if (!target) {
2183 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2184 PyErr_NoMemory();
2185 return NULL;
2186 }
2187 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2188 if (!target) {
2189 PyErr_NoMemory();
2190 return NULL;
2191 }
2192 }
2193 else {
2194 if (targetsize < targetlen) {
2195 PyErr_Format(PyExc_SystemError,
2196 "string is longer than the buffer");
2197 if (copy_null && 0 < targetsize)
2198 target[0] = 0;
2199 return NULL;
2200 }
2201 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002202 if (kind == PyUnicode_1BYTE_KIND) {
2203 Py_UCS1 *start = (Py_UCS1 *) data;
2204 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002205 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002206 else if (kind == PyUnicode_2BYTE_KIND) {
2207 Py_UCS2 *start = (Py_UCS2 *) data;
2208 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2209 }
2210 else {
2211 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002212 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002213 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002214 if (copy_null)
2215 target[len] = 0;
2216 return target;
2217}
2218
2219Py_UCS4*
2220PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2221 int copy_null)
2222{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002223 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002224 PyErr_BadInternalCall();
2225 return NULL;
2226 }
2227 return as_ucs4(string, target, targetsize, copy_null);
2228}
2229
2230Py_UCS4*
2231PyUnicode_AsUCS4Copy(PyObject *string)
2232{
2233 return as_ucs4(string, NULL, 0, 1);
2234}
2235
2236#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002237
Alexander Belopolsky40018472011-02-26 01:02:56 +00002238PyObject *
2239PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002240{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002241 if (w == NULL) {
Victor Stinner382955f2011-12-11 21:44:00 +01002242 if (size == 0) {
2243 Py_INCREF(unicode_empty);
2244 return unicode_empty;
2245 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002246 PyErr_BadInternalCall();
2247 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002248 }
2249
Martin v. Löwis790465f2008-04-05 20:41:37 +00002250 if (size == -1) {
2251 size = wcslen(w);
2252 }
2253
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002254 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002255}
2256
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002257#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002258
Walter Dörwald346737f2007-05-31 10:44:43 +00002259static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002260makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2261 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002262{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002263 *fmt++ = '%';
2264 if (width) {
2265 if (zeropad)
2266 *fmt++ = '0';
2267 fmt += sprintf(fmt, "%d", width);
2268 }
2269 if (precision)
2270 fmt += sprintf(fmt, ".%d", precision);
2271 if (longflag)
2272 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002273 else if (longlongflag) {
2274 /* longlongflag should only ever be nonzero on machines with
2275 HAVE_LONG_LONG defined */
2276#ifdef HAVE_LONG_LONG
2277 char *f = PY_FORMAT_LONG_LONG;
2278 while (*f)
2279 *fmt++ = *f++;
2280#else
2281 /* we shouldn't ever get here */
2282 assert(0);
2283 *fmt++ = 'l';
2284#endif
2285 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002286 else if (size_tflag) {
2287 char *f = PY_FORMAT_SIZE_T;
2288 while (*f)
2289 *fmt++ = *f++;
2290 }
2291 *fmt++ = c;
2292 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002293}
2294
Victor Stinner96865452011-03-01 23:44:09 +00002295/* helper for PyUnicode_FromFormatV() */
2296
2297static const char*
2298parse_format_flags(const char *f,
2299 int *p_width, int *p_precision,
2300 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2301{
2302 int width, precision, longflag, longlongflag, size_tflag;
2303
2304 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2305 f++;
2306 width = 0;
2307 while (Py_ISDIGIT((unsigned)*f))
2308 width = (width*10) + *f++ - '0';
2309 precision = 0;
2310 if (*f == '.') {
2311 f++;
2312 while (Py_ISDIGIT((unsigned)*f))
2313 precision = (precision*10) + *f++ - '0';
2314 if (*f == '%') {
2315 /* "%.3%s" => f points to "3" */
2316 f--;
2317 }
2318 }
2319 if (*f == '\0') {
2320 /* bogus format "%.1" => go backward, f points to "1" */
2321 f--;
2322 }
2323 if (p_width != NULL)
2324 *p_width = width;
2325 if (p_precision != NULL)
2326 *p_precision = precision;
2327
2328 /* Handle %ld, %lu, %lld and %llu. */
2329 longflag = 0;
2330 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002331 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002332
2333 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002334 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002335 longflag = 1;
2336 ++f;
2337 }
2338#ifdef HAVE_LONG_LONG
2339 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002340 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002341 longlongflag = 1;
2342 f += 2;
2343 }
2344#endif
2345 }
2346 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002347 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002348 size_tflag = 1;
2349 ++f;
2350 }
2351 if (p_longflag != NULL)
2352 *p_longflag = longflag;
2353 if (p_longlongflag != NULL)
2354 *p_longlongflag = longlongflag;
2355 if (p_size_tflag != NULL)
2356 *p_size_tflag = size_tflag;
2357 return f;
2358}
2359
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002360/* maximum number of characters required for output of %ld. 21 characters
2361 allows for 64-bit integers (in decimal) and an optional sign. */
2362#define MAX_LONG_CHARS 21
2363/* maximum number of characters required for output of %lld.
2364 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2365 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2366#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2367
Walter Dörwaldd2034312007-05-18 16:29:38 +00002368PyObject *
2369PyUnicode_FromFormatV(const char *format, va_list vargs)
2370{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002371 va_list count;
2372 Py_ssize_t callcount = 0;
2373 PyObject **callresults = NULL;
2374 PyObject **callresult = NULL;
2375 Py_ssize_t n = 0;
2376 int width = 0;
2377 int precision = 0;
2378 int zeropad;
2379 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002380 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002381 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002382 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002383 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2384 Py_UCS4 argmaxchar;
2385 Py_ssize_t numbersize = 0;
2386 char *numberresults = NULL;
2387 char *numberresult = NULL;
2388 Py_ssize_t i;
2389 int kind;
2390 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002391
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002392 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002393 /* step 1: count the number of %S/%R/%A/%s format specifications
2394 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2395 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002396 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002397 * also estimate a upper bound for all the number formats in the string,
2398 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002399 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002400 for (f = format; *f; f++) {
2401 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002402 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2404 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2405 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2406 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002407
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002408 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002409#ifdef HAVE_LONG_LONG
2410 if (longlongflag) {
2411 if (width < MAX_LONG_LONG_CHARS)
2412 width = MAX_LONG_LONG_CHARS;
2413 }
2414 else
2415#endif
2416 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2417 including sign. Decimal takes the most space. This
2418 isn't enough for octal. If a width is specified we
2419 need more (which we allocate later). */
2420 if (width < MAX_LONG_CHARS)
2421 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002422
2423 /* account for the size + '\0' to separate numbers
2424 inside of the numberresults buffer */
2425 numbersize += (width + 1);
2426 }
2427 }
2428 else if ((unsigned char)*f > 127) {
2429 PyErr_Format(PyExc_ValueError,
2430 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2431 "string, got a non-ASCII byte: 0x%02x",
2432 (unsigned char)*f);
2433 return NULL;
2434 }
2435 }
2436 /* step 2: allocate memory for the results of
2437 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2438 if (callcount) {
2439 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2440 if (!callresults) {
2441 PyErr_NoMemory();
2442 return NULL;
2443 }
2444 callresult = callresults;
2445 }
2446 /* step 2.5: allocate memory for the results of formating numbers */
2447 if (numbersize) {
2448 numberresults = PyObject_Malloc(numbersize);
2449 if (!numberresults) {
2450 PyErr_NoMemory();
2451 goto fail;
2452 }
2453 numberresult = numberresults;
2454 }
2455
2456 /* step 3: format numbers and figure out how large a buffer we need */
2457 for (f = format; *f; f++) {
2458 if (*f == '%') {
2459 const char* p;
2460 int longflag;
2461 int longlongflag;
2462 int size_tflag;
2463 int numprinted;
2464
2465 p = f;
2466 zeropad = (f[1] == '0');
2467 f = parse_format_flags(f, &width, &precision,
2468 &longflag, &longlongflag, &size_tflag);
2469 switch (*f) {
2470 case 'c':
2471 {
2472 Py_UCS4 ordinal = va_arg(count, int);
Victor Stinnere6abb482012-05-02 01:15:40 +02002473 maxchar = MAX_MAXCHAR(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002474 n++;
2475 break;
2476 }
2477 case '%':
2478 n++;
2479 break;
2480 case 'i':
2481 case 'd':
2482 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2483 width, precision, *f);
2484 if (longflag)
2485 numprinted = sprintf(numberresult, fmt,
2486 va_arg(count, long));
2487#ifdef HAVE_LONG_LONG
2488 else if (longlongflag)
2489 numprinted = sprintf(numberresult, fmt,
2490 va_arg(count, PY_LONG_LONG));
2491#endif
2492 else if (size_tflag)
2493 numprinted = sprintf(numberresult, fmt,
2494 va_arg(count, Py_ssize_t));
2495 else
2496 numprinted = sprintf(numberresult, fmt,
2497 va_arg(count, int));
2498 n += numprinted;
2499 /* advance by +1 to skip over the '\0' */
2500 numberresult += (numprinted + 1);
2501 assert(*(numberresult - 1) == '\0');
2502 assert(*(numberresult - 2) != '\0');
2503 assert(numprinted >= 0);
2504 assert(numberresult <= numberresults + numbersize);
2505 break;
2506 case 'u':
2507 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2508 width, precision, 'u');
2509 if (longflag)
2510 numprinted = sprintf(numberresult, fmt,
2511 va_arg(count, unsigned long));
2512#ifdef HAVE_LONG_LONG
2513 else if (longlongflag)
2514 numprinted = sprintf(numberresult, fmt,
2515 va_arg(count, unsigned PY_LONG_LONG));
2516#endif
2517 else if (size_tflag)
2518 numprinted = sprintf(numberresult, fmt,
2519 va_arg(count, size_t));
2520 else
2521 numprinted = sprintf(numberresult, fmt,
2522 va_arg(count, unsigned int));
2523 n += numprinted;
2524 numberresult += (numprinted + 1);
2525 assert(*(numberresult - 1) == '\0');
2526 assert(*(numberresult - 2) != '\0');
2527 assert(numprinted >= 0);
2528 assert(numberresult <= numberresults + numbersize);
2529 break;
2530 case 'x':
2531 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2532 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2533 n += numprinted;
2534 numberresult += (numprinted + 1);
2535 assert(*(numberresult - 1) == '\0');
2536 assert(*(numberresult - 2) != '\0');
2537 assert(numprinted >= 0);
2538 assert(numberresult <= numberresults + numbersize);
2539 break;
2540 case 'p':
2541 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2542 /* %p is ill-defined: ensure leading 0x. */
2543 if (numberresult[1] == 'X')
2544 numberresult[1] = 'x';
2545 else if (numberresult[1] != 'x') {
2546 memmove(numberresult + 2, numberresult,
2547 strlen(numberresult) + 1);
2548 numberresult[0] = '0';
2549 numberresult[1] = 'x';
2550 numprinted += 2;
2551 }
2552 n += numprinted;
2553 numberresult += (numprinted + 1);
2554 assert(*(numberresult - 1) == '\0');
2555 assert(*(numberresult - 2) != '\0');
2556 assert(numprinted >= 0);
2557 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002558 break;
2559 case 's':
2560 {
2561 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002562 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002563 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002564 if (!str)
2565 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002566 /* since PyUnicode_DecodeUTF8 returns already flexible
2567 unicode objects, there is no need to call ready on them */
2568 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Victor Stinnere6abb482012-05-02 01:15:40 +02002569 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002570 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002571 /* Remember the str and switch to the next slot */
2572 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002573 break;
2574 }
2575 case 'U':
2576 {
2577 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002578 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002579 if (PyUnicode_READY(obj) == -1)
2580 goto fail;
2581 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002582 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002583 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002584 break;
2585 }
2586 case 'V':
2587 {
2588 PyObject *obj = va_arg(count, PyObject *);
2589 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002590 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002591 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002592 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002593 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002594 if (PyUnicode_READY(obj) == -1)
2595 goto fail;
2596 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002597 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002598 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002599 *callresult++ = NULL;
2600 }
2601 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002602 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002603 if (!str_obj)
2604 goto fail;
Benjamin Petersonbac79492012-01-14 13:34:47 -05002605 if (PyUnicode_READY(str_obj) == -1) {
Victor Stinnere1335c72011-10-04 20:53:03 +02002606 Py_DECREF(str_obj);
2607 goto fail;
2608 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002609 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002610 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002611 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002612 *callresult++ = str_obj;
2613 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002614 break;
2615 }
2616 case 'S':
2617 {
2618 PyObject *obj = va_arg(count, PyObject *);
2619 PyObject *str;
2620 assert(obj);
2621 str = PyObject_Str(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002622 if (!str)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002623 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002624 if (PyUnicode_READY(str) == -1) {
2625 Py_DECREF(str);
2626 goto fail;
2627 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002628 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Victor Stinnere6abb482012-05-02 01:15:40 +02002629 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002630 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002631 /* Remember the str and switch to the next slot */
2632 *callresult++ = str;
2633 break;
2634 }
2635 case 'R':
2636 {
2637 PyObject *obj = va_arg(count, PyObject *);
2638 PyObject *repr;
2639 assert(obj);
2640 repr = PyObject_Repr(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002641 if (!repr)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002642 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002643 if (PyUnicode_READY(repr) == -1) {
2644 Py_DECREF(repr);
2645 goto fail;
2646 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002647 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Victor Stinnere6abb482012-05-02 01:15:40 +02002648 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002649 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002650 /* Remember the repr and switch to the next slot */
2651 *callresult++ = repr;
2652 break;
2653 }
2654 case 'A':
2655 {
2656 PyObject *obj = va_arg(count, PyObject *);
2657 PyObject *ascii;
2658 assert(obj);
2659 ascii = PyObject_ASCII(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002660 if (!ascii)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002661 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002662 if (PyUnicode_READY(ascii) == -1) {
2663 Py_DECREF(ascii);
2664 goto fail;
2665 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002666 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Victor Stinnere6abb482012-05-02 01:15:40 +02002667 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002668 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002669 /* Remember the repr and switch to the next slot */
2670 *callresult++ = ascii;
2671 break;
2672 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002673 default:
2674 /* if we stumble upon an unknown
2675 formatting code, copy the rest of
2676 the format string to the output
2677 string. (we cannot just skip the
2678 code, since there's no way to know
2679 what's in the argument list) */
2680 n += strlen(p);
2681 goto expand;
2682 }
2683 } else
2684 n++;
2685 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002686 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002687 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002688 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002689 we don't have to resize the string.
2690 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002691 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002692 if (!string)
2693 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002694 kind = PyUnicode_KIND(string);
2695 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002696 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002697 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002698
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002699 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002700 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002701 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002702
2703 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002704 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2705 /* checking for == because the last argument could be a empty
2706 string, which causes i to point to end, the assert at the end of
2707 the loop */
2708 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002709
Benjamin Peterson14339b62009-01-31 16:36:08 +00002710 switch (*f) {
2711 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002712 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002713 const int ordinal = va_arg(vargs, int);
2714 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002715 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002716 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002717 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002718 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002719 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002720 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002721 case 'p':
Victor Stinnerc5166102012-02-22 13:55:02 +01002722 {
2723 Py_ssize_t written;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002724 /* unused, since we already have the result */
2725 if (*f == 'p')
2726 (void) va_arg(vargs, void *);
2727 else
2728 (void) va_arg(vargs, int);
2729 /* extract the result from numberresults and append. */
Victor Stinnerc5166102012-02-22 13:55:02 +01002730 written = unicode_write_cstr(string, i, numberresult);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002731 /* skip over the separating '\0' */
Victor Stinnerc5166102012-02-22 13:55:02 +01002732 i += written;
2733 numberresult += written;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002734 assert(*numberresult == '\0');
2735 numberresult++;
2736 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002737 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002738 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002739 case 's':
2740 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002741 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002742 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002743 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002744 size = PyUnicode_GET_LENGTH(*callresult);
2745 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002746 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002747 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002748 /* We're done with the unicode()/repr() => forget it */
2749 Py_DECREF(*callresult);
2750 /* switch to next unicode()/repr() result */
2751 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002752 break;
2753 }
2754 case 'U':
2755 {
2756 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002757 Py_ssize_t size;
2758 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2759 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002760 _PyUnicode_FastCopyCharacters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002761 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002762 break;
2763 }
2764 case 'V':
2765 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002766 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002767 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002768 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002769 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002770 size = PyUnicode_GET_LENGTH(obj);
2771 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002772 _PyUnicode_FastCopyCharacters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002773 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002774 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002775 size = PyUnicode_GET_LENGTH(*callresult);
2776 assert(PyUnicode_KIND(*callresult) <=
2777 PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002778 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002779 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002780 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002781 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002782 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002783 break;
2784 }
2785 case 'S':
2786 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002787 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002788 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002789 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002790 /* unused, since we already have the result */
2791 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002792 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002793 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002794 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002795 /* We're done with the unicode()/repr() => forget it */
2796 Py_DECREF(*callresult);
2797 /* switch to next unicode()/repr() result */
2798 ++callresult;
2799 break;
2800 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002801 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002802 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002803 break;
2804 default:
Victor Stinnerc5166102012-02-22 13:55:02 +01002805 i += unicode_write_cstr(string, i, p);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002806 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002807 goto end;
2808 }
Victor Stinner1205f272010-09-11 00:54:47 +00002809 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002810 else {
2811 assert(i < PyUnicode_GET_LENGTH(string));
2812 PyUnicode_WRITE(kind, data, i++, *f);
2813 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002814 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002815 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002816
Benjamin Peterson29060642009-01-31 22:14:21 +00002817 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002818 if (callresults)
2819 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002820 if (numberresults)
2821 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002822 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002823 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002824 if (callresults) {
2825 PyObject **callresult2 = callresults;
2826 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002827 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002828 ++callresult2;
2829 }
2830 PyObject_Free(callresults);
2831 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002832 if (numberresults)
2833 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002834 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002835}
2836
Walter Dörwaldd2034312007-05-18 16:29:38 +00002837PyObject *
2838PyUnicode_FromFormat(const char *format, ...)
2839{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002840 PyObject* ret;
2841 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002842
2843#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002844 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002845#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002846 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002847#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002848 ret = PyUnicode_FromFormatV(format, vargs);
2849 va_end(vargs);
2850 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002851}
2852
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002853#ifdef HAVE_WCHAR_H
2854
Victor Stinner5593d8a2010-10-02 11:11:27 +00002855/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2856 convert a Unicode object to a wide character string.
2857
Victor Stinnerd88d9832011-09-06 02:00:05 +02002858 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002859 character) required to convert the unicode object. Ignore size argument.
2860
Victor Stinnerd88d9832011-09-06 02:00:05 +02002861 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002862 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002863 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002864static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002865unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002866 wchar_t *w,
2867 Py_ssize_t size)
2868{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002869 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002870 const wchar_t *wstr;
2871
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002872 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002873 if (wstr == NULL)
2874 return -1;
2875
Victor Stinner5593d8a2010-10-02 11:11:27 +00002876 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002877 if (size > res)
2878 size = res + 1;
2879 else
2880 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002881 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002882 return res;
2883 }
2884 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002885 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002886}
2887
2888Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002889PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002890 wchar_t *w,
2891 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002892{
2893 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002894 PyErr_BadInternalCall();
2895 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002896 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002897 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002898}
2899
Victor Stinner137c34c2010-09-29 10:25:54 +00002900wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002901PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002902 Py_ssize_t *size)
2903{
2904 wchar_t* buffer;
2905 Py_ssize_t buflen;
2906
2907 if (unicode == NULL) {
2908 PyErr_BadInternalCall();
2909 return NULL;
2910 }
2911
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002912 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002913 if (buflen == -1)
2914 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002915 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002916 PyErr_NoMemory();
2917 return NULL;
2918 }
2919
Victor Stinner137c34c2010-09-29 10:25:54 +00002920 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2921 if (buffer == NULL) {
2922 PyErr_NoMemory();
2923 return NULL;
2924 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002925 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002926 if (buflen == -1)
2927 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002928 if (size != NULL)
2929 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002930 return buffer;
2931}
2932
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002933#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002934
Alexander Belopolsky40018472011-02-26 01:02:56 +00002935PyObject *
2936PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002937{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002938 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002939 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002940 PyErr_SetString(PyExc_ValueError,
2941 "chr() arg not in range(0x110000)");
2942 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002943 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002944
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002945 if (ordinal < 256)
2946 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002947
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002948 v = PyUnicode_New(1, ordinal);
2949 if (v == NULL)
2950 return NULL;
2951 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002952 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002953 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002954}
2955
Alexander Belopolsky40018472011-02-26 01:02:56 +00002956PyObject *
2957PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002958{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002959 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002960 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002961 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002962 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002963 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002964 Py_INCREF(obj);
2965 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002966 }
2967 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002968 /* For a Unicode subtype that's not a Unicode object,
2969 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002970 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002971 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002972 PyErr_Format(PyExc_TypeError,
2973 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002974 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002975 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002976}
2977
Alexander Belopolsky40018472011-02-26 01:02:56 +00002978PyObject *
2979PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002980 const char *encoding,
2981 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002982{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002983 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002984 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002985
Guido van Rossumd57fd912000-03-10 22:53:23 +00002986 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002987 PyErr_BadInternalCall();
2988 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002989 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002990
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002991 /* Decoding bytes objects is the most common case and should be fast */
2992 if (PyBytes_Check(obj)) {
2993 if (PyBytes_GET_SIZE(obj) == 0) {
2994 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002995 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002996 }
2997 else {
2998 v = PyUnicode_Decode(
2999 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3000 encoding, errors);
3001 }
3002 return v;
3003 }
3004
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003005 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003006 PyErr_SetString(PyExc_TypeError,
3007 "decoding str is not supported");
3008 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003009 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003010
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003011 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3012 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3013 PyErr_Format(PyExc_TypeError,
3014 "coercing to str: need bytes, bytearray "
3015 "or buffer-like object, %.80s found",
3016 Py_TYPE(obj)->tp_name);
3017 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003018 }
Tim Petersced69f82003-09-16 20:30:58 +00003019
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003020 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003021 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02003022 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003023 }
Tim Petersced69f82003-09-16 20:30:58 +00003024 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003025 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003026
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003027 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003028 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003029}
3030
Victor Stinner600d3be2010-06-10 12:00:55 +00003031/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00003032 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
3033 1 on success. */
3034static int
3035normalize_encoding(const char *encoding,
3036 char *lower,
3037 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003038{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003039 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003040 char *l;
3041 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003042
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04003043 if (encoding == NULL) {
3044 strcpy(lower, "utf-8");
3045 return 1;
3046 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003047 e = encoding;
3048 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003049 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00003050 while (*e) {
3051 if (l == l_end)
3052 return 0;
David Malcolm96960882010-11-05 17:23:41 +00003053 if (Py_ISUPPER(*e)) {
3054 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003055 }
3056 else if (*e == '_') {
3057 *l++ = '-';
3058 e++;
3059 }
3060 else {
3061 *l++ = *e++;
3062 }
3063 }
3064 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003065 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003066}
3067
Alexander Belopolsky40018472011-02-26 01:02:56 +00003068PyObject *
3069PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003070 Py_ssize_t size,
3071 const char *encoding,
3072 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003073{
3074 PyObject *buffer = NULL, *unicode;
3075 Py_buffer info;
3076 char lower[11]; /* Enough for any encoding shortcut */
3077
Fred Drakee4315f52000-05-09 19:53:39 +00003078 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003079 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003080 if ((strcmp(lower, "utf-8") == 0) ||
3081 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003082 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003083 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003084 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003085 (strcmp(lower, "iso-8859-1") == 0))
3086 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003087#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003088 else if (strcmp(lower, "mbcs") == 0)
3089 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003090#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003091 else if (strcmp(lower, "ascii") == 0)
3092 return PyUnicode_DecodeASCII(s, size, errors);
3093 else if (strcmp(lower, "utf-16") == 0)
3094 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3095 else if (strcmp(lower, "utf-32") == 0)
3096 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3097 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003098
3099 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003100 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003101 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003102 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003103 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003104 if (buffer == NULL)
3105 goto onError;
3106 unicode = PyCodec_Decode(buffer, encoding, errors);
3107 if (unicode == NULL)
3108 goto onError;
3109 if (!PyUnicode_Check(unicode)) {
3110 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003111 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003112 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003113 Py_DECREF(unicode);
3114 goto onError;
3115 }
3116 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003117 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003118
Benjamin Peterson29060642009-01-31 22:14:21 +00003119 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003120 Py_XDECREF(buffer);
3121 return NULL;
3122}
3123
Alexander Belopolsky40018472011-02-26 01:02:56 +00003124PyObject *
3125PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003126 const char *encoding,
3127 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003128{
3129 PyObject *v;
3130
3131 if (!PyUnicode_Check(unicode)) {
3132 PyErr_BadArgument();
3133 goto onError;
3134 }
3135
3136 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003137 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003138
3139 /* Decode via the codec registry */
3140 v = PyCodec_Decode(unicode, encoding, errors);
3141 if (v == NULL)
3142 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003143 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003144
Benjamin Peterson29060642009-01-31 22:14:21 +00003145 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003146 return NULL;
3147}
3148
Alexander Belopolsky40018472011-02-26 01:02:56 +00003149PyObject *
3150PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003151 const char *encoding,
3152 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003153{
3154 PyObject *v;
3155
3156 if (!PyUnicode_Check(unicode)) {
3157 PyErr_BadArgument();
3158 goto onError;
3159 }
3160
3161 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003162 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003163
3164 /* Decode via the codec registry */
3165 v = PyCodec_Decode(unicode, encoding, errors);
3166 if (v == NULL)
3167 goto onError;
3168 if (!PyUnicode_Check(v)) {
3169 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003170 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003171 Py_TYPE(v)->tp_name);
3172 Py_DECREF(v);
3173 goto onError;
3174 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003175 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003176
Benjamin Peterson29060642009-01-31 22:14:21 +00003177 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003178 return NULL;
3179}
3180
Alexander Belopolsky40018472011-02-26 01:02:56 +00003181PyObject *
3182PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003183 Py_ssize_t size,
3184 const char *encoding,
3185 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003186{
3187 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003188
Guido van Rossumd57fd912000-03-10 22:53:23 +00003189 unicode = PyUnicode_FromUnicode(s, size);
3190 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003191 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003192 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3193 Py_DECREF(unicode);
3194 return v;
3195}
3196
Alexander Belopolsky40018472011-02-26 01:02:56 +00003197PyObject *
3198PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003199 const char *encoding,
3200 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003201{
3202 PyObject *v;
3203
3204 if (!PyUnicode_Check(unicode)) {
3205 PyErr_BadArgument();
3206 goto onError;
3207 }
3208
3209 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003210 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003211
3212 /* Encode via the codec registry */
3213 v = PyCodec_Encode(unicode, encoding, errors);
3214 if (v == NULL)
3215 goto onError;
3216 return v;
3217
Benjamin Peterson29060642009-01-31 22:14:21 +00003218 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003219 return NULL;
3220}
3221
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003222static size_t
3223wcstombs_errorpos(const wchar_t *wstr)
3224{
3225 size_t len;
3226#if SIZEOF_WCHAR_T == 2
3227 wchar_t buf[3];
3228#else
3229 wchar_t buf[2];
3230#endif
3231 char outbuf[MB_LEN_MAX];
3232 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003233
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003234#if SIZEOF_WCHAR_T == 2
3235 buf[2] = 0;
3236#else
3237 buf[1] = 0;
3238#endif
3239 start = wstr;
3240 while (*wstr != L'\0')
3241 {
3242 previous = wstr;
3243#if SIZEOF_WCHAR_T == 2
3244 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3245 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3246 {
3247 buf[0] = wstr[0];
3248 buf[1] = wstr[1];
3249 wstr += 2;
3250 }
3251 else {
3252 buf[0] = *wstr;
3253 buf[1] = 0;
3254 wstr++;
3255 }
3256#else
3257 buf[0] = *wstr;
3258 wstr++;
3259#endif
3260 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003261 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003262 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003263 }
3264
3265 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003266 return 0;
3267}
3268
Victor Stinner1b579672011-12-17 05:47:23 +01003269static int
3270locale_error_handler(const char *errors, int *surrogateescape)
3271{
3272 if (errors == NULL) {
3273 *surrogateescape = 0;
3274 return 0;
3275 }
3276
3277 if (strcmp(errors, "strict") == 0) {
3278 *surrogateescape = 0;
3279 return 0;
3280 }
3281 if (strcmp(errors, "surrogateescape") == 0) {
3282 *surrogateescape = 1;
3283 return 0;
3284 }
3285 PyErr_Format(PyExc_ValueError,
3286 "only 'strict' and 'surrogateescape' error handlers "
3287 "are supported, not '%s'",
3288 errors);
3289 return -1;
3290}
3291
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003292PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003293PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003294{
3295 Py_ssize_t wlen, wlen2;
3296 wchar_t *wstr;
3297 PyObject *bytes = NULL;
3298 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003299 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003300 PyObject *exc;
3301 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003302 int surrogateescape;
3303
3304 if (locale_error_handler(errors, &surrogateescape) < 0)
3305 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003306
3307 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3308 if (wstr == NULL)
3309 return NULL;
3310
3311 wlen2 = wcslen(wstr);
3312 if (wlen2 != wlen) {
3313 PyMem_Free(wstr);
3314 PyErr_SetString(PyExc_TypeError, "embedded null character");
3315 return NULL;
3316 }
3317
3318 if (surrogateescape) {
3319 /* locale encoding with surrogateescape */
3320 char *str;
3321
3322 str = _Py_wchar2char(wstr, &error_pos);
3323 if (str == NULL) {
3324 if (error_pos == (size_t)-1) {
3325 PyErr_NoMemory();
3326 PyMem_Free(wstr);
3327 return NULL;
3328 }
3329 else {
3330 goto encode_error;
3331 }
3332 }
3333 PyMem_Free(wstr);
3334
3335 bytes = PyBytes_FromString(str);
3336 PyMem_Free(str);
3337 }
3338 else {
3339 size_t len, len2;
3340
3341 len = wcstombs(NULL, wstr, 0);
3342 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003343 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003344 goto encode_error;
3345 }
3346
3347 bytes = PyBytes_FromStringAndSize(NULL, len);
3348 if (bytes == NULL) {
3349 PyMem_Free(wstr);
3350 return NULL;
3351 }
3352
3353 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3354 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003355 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003356 goto encode_error;
3357 }
3358 PyMem_Free(wstr);
3359 }
3360 return bytes;
3361
3362encode_error:
3363 errmsg = strerror(errno);
3364 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003365
3366 if (error_pos == (size_t)-1)
3367 error_pos = wcstombs_errorpos(wstr);
3368
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003369 PyMem_Free(wstr);
3370 Py_XDECREF(bytes);
3371
Victor Stinner2f197072011-12-17 07:08:30 +01003372 if (errmsg != NULL) {
3373 size_t errlen;
3374 wstr = _Py_char2wchar(errmsg, &errlen);
3375 if (wstr != NULL) {
3376 reason = PyUnicode_FromWideChar(wstr, errlen);
3377 PyMem_Free(wstr);
3378 } else
3379 errmsg = NULL;
3380 }
3381 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003382 reason = PyUnicode_FromString(
3383 "wcstombs() encountered an unencodable "
3384 "wide character");
3385 if (reason == NULL)
3386 return NULL;
3387
3388 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3389 "locale", unicode,
3390 (Py_ssize_t)error_pos,
3391 (Py_ssize_t)(error_pos+1),
3392 reason);
3393 Py_DECREF(reason);
3394 if (exc != NULL) {
3395 PyCodec_StrictErrors(exc);
3396 Py_XDECREF(exc);
3397 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003398 return NULL;
3399}
3400
Victor Stinnerad158722010-10-27 00:25:46 +00003401PyObject *
3402PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003403{
Victor Stinner99b95382011-07-04 14:23:54 +02003404#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003405 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003406#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003407 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003408#else
Victor Stinner793b5312011-04-27 00:24:21 +02003409 PyInterpreterState *interp = PyThreadState_GET()->interp;
3410 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3411 cannot use it to encode and decode filenames before it is loaded. Load
3412 the Python codec requires to encode at least its own filename. Use the C
3413 version of the locale codec until the codec registry is initialized and
3414 the Python codec is loaded.
3415
3416 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3417 cannot only rely on it: check also interp->fscodec_initialized for
3418 subinterpreters. */
3419 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003420 return PyUnicode_AsEncodedString(unicode,
3421 Py_FileSystemDefaultEncoding,
3422 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003423 }
3424 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003425 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003426 }
Victor Stinnerad158722010-10-27 00:25:46 +00003427#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003428}
3429
Alexander Belopolsky40018472011-02-26 01:02:56 +00003430PyObject *
3431PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003432 const char *encoding,
3433 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003434{
3435 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003436 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003437
Guido van Rossumd57fd912000-03-10 22:53:23 +00003438 if (!PyUnicode_Check(unicode)) {
3439 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003440 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003441 }
Fred Drakee4315f52000-05-09 19:53:39 +00003442
Fred Drakee4315f52000-05-09 19:53:39 +00003443 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003444 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003445 if ((strcmp(lower, "utf-8") == 0) ||
3446 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003447 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003448 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003449 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003450 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003451 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003452 }
Victor Stinner37296e82010-06-10 13:36:23 +00003453 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003454 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003455 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003456 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003457#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003458 else if (strcmp(lower, "mbcs") == 0)
3459 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003460#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003461 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003462 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003463 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003464
3465 /* Encode via the codec registry */
3466 v = PyCodec_Encode(unicode, encoding, errors);
3467 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003468 return NULL;
3469
3470 /* The normal path */
3471 if (PyBytes_Check(v))
3472 return v;
3473
3474 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003475 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003476 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003477 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003478
3479 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3480 "encoder %s returned bytearray instead of bytes",
3481 encoding);
3482 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003483 Py_DECREF(v);
3484 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003485 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003486
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003487 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3488 Py_DECREF(v);
3489 return b;
3490 }
3491
3492 PyErr_Format(PyExc_TypeError,
3493 "encoder did not return a bytes object (type=%.400s)",
3494 Py_TYPE(v)->tp_name);
3495 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003496 return NULL;
3497}
3498
Alexander Belopolsky40018472011-02-26 01:02:56 +00003499PyObject *
3500PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003501 const char *encoding,
3502 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003503{
3504 PyObject *v;
3505
3506 if (!PyUnicode_Check(unicode)) {
3507 PyErr_BadArgument();
3508 goto onError;
3509 }
3510
3511 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003512 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003513
3514 /* Encode via the codec registry */
3515 v = PyCodec_Encode(unicode, encoding, errors);
3516 if (v == NULL)
3517 goto onError;
3518 if (!PyUnicode_Check(v)) {
3519 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003520 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003521 Py_TYPE(v)->tp_name);
3522 Py_DECREF(v);
3523 goto onError;
3524 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003525 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003526
Benjamin Peterson29060642009-01-31 22:14:21 +00003527 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003528 return NULL;
3529}
3530
Victor Stinner2f197072011-12-17 07:08:30 +01003531static size_t
3532mbstowcs_errorpos(const char *str, size_t len)
3533{
3534#ifdef HAVE_MBRTOWC
3535 const char *start = str;
3536 mbstate_t mbs;
3537 size_t converted;
3538 wchar_t ch;
3539
3540 memset(&mbs, 0, sizeof mbs);
3541 while (len)
3542 {
3543 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3544 if (converted == 0)
3545 /* Reached end of string */
3546 break;
3547 if (converted == (size_t)-1 || converted == (size_t)-2) {
3548 /* Conversion error or incomplete character */
3549 return str - start;
3550 }
3551 else {
3552 str += converted;
3553 len -= converted;
3554 }
3555 }
3556 /* failed to find the undecodable byte sequence */
3557 return 0;
3558#endif
3559 return 0;
3560}
3561
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003562PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003563PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003564 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003565{
3566 wchar_t smallbuf[256];
3567 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3568 wchar_t *wstr;
3569 size_t wlen, wlen2;
3570 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003571 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003572 size_t error_pos;
3573 char *errmsg;
3574 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003575
3576 if (locale_error_handler(errors, &surrogateescape) < 0)
3577 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003578
3579 if (str[len] != '\0' || len != strlen(str)) {
3580 PyErr_SetString(PyExc_TypeError, "embedded null character");
3581 return NULL;
3582 }
3583
3584 if (surrogateescape)
3585 {
3586 wstr = _Py_char2wchar(str, &wlen);
3587 if (wstr == NULL) {
3588 if (wlen == (size_t)-1)
3589 PyErr_NoMemory();
3590 else
3591 PyErr_SetFromErrno(PyExc_OSError);
3592 return NULL;
3593 }
3594
3595 unicode = PyUnicode_FromWideChar(wstr, wlen);
3596 PyMem_Free(wstr);
3597 }
3598 else {
3599#ifndef HAVE_BROKEN_MBSTOWCS
3600 wlen = mbstowcs(NULL, str, 0);
3601#else
3602 wlen = len;
3603#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003604 if (wlen == (size_t)-1)
3605 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003606 if (wlen+1 <= smallbuf_len) {
3607 wstr = smallbuf;
3608 }
3609 else {
3610 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3611 return PyErr_NoMemory();
3612
3613 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3614 if (!wstr)
3615 return PyErr_NoMemory();
3616 }
3617
3618 /* This shouldn't fail now */
3619 wlen2 = mbstowcs(wstr, str, wlen+1);
3620 if (wlen2 == (size_t)-1) {
3621 if (wstr != smallbuf)
3622 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003623 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003624 }
3625#ifdef HAVE_BROKEN_MBSTOWCS
3626 assert(wlen2 == wlen);
3627#endif
3628 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3629 if (wstr != smallbuf)
3630 PyMem_Free(wstr);
3631 }
3632 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003633
3634decode_error:
3635 errmsg = strerror(errno);
3636 assert(errmsg != NULL);
3637
3638 error_pos = mbstowcs_errorpos(str, len);
3639 if (errmsg != NULL) {
3640 size_t errlen;
3641 wstr = _Py_char2wchar(errmsg, &errlen);
3642 if (wstr != NULL) {
3643 reason = PyUnicode_FromWideChar(wstr, errlen);
3644 PyMem_Free(wstr);
3645 } else
3646 errmsg = NULL;
3647 }
3648 if (errmsg == NULL)
3649 reason = PyUnicode_FromString(
3650 "mbstowcs() encountered an invalid multibyte sequence");
3651 if (reason == NULL)
3652 return NULL;
3653
3654 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3655 "locale", str, len,
3656 (Py_ssize_t)error_pos,
3657 (Py_ssize_t)(error_pos+1),
3658 reason);
3659 Py_DECREF(reason);
3660 if (exc != NULL) {
3661 PyCodec_StrictErrors(exc);
3662 Py_XDECREF(exc);
3663 }
3664 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003665}
3666
3667PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003668PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003669{
3670 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003671 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003672}
3673
3674
3675PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003676PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003677 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003678 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3679}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003680
Christian Heimes5894ba72007-11-04 11:43:14 +00003681PyObject*
3682PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3683{
Victor Stinner99b95382011-07-04 14:23:54 +02003684#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003685 return PyUnicode_DecodeMBCS(s, size, NULL);
3686#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003687 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003688#else
Victor Stinner793b5312011-04-27 00:24:21 +02003689 PyInterpreterState *interp = PyThreadState_GET()->interp;
3690 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3691 cannot use it to encode and decode filenames before it is loaded. Load
3692 the Python codec requires to encode at least its own filename. Use the C
3693 version of the locale codec until the codec registry is initialized and
3694 the Python codec is loaded.
3695
3696 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3697 cannot only rely on it: check also interp->fscodec_initialized for
3698 subinterpreters. */
3699 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003700 return PyUnicode_Decode(s, size,
3701 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003702 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003703 }
3704 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003705 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003706 }
Victor Stinnerad158722010-10-27 00:25:46 +00003707#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003708}
3709
Martin v. Löwis011e8422009-05-05 04:43:17 +00003710
3711int
Antoine Pitrou13348842012-01-29 18:36:34 +01003712_PyUnicode_HasNULChars(PyObject* s)
3713{
3714 static PyObject *nul = NULL;
3715
3716 if (nul == NULL)
3717 nul = PyUnicode_FromStringAndSize("\0", 1);
3718 if (nul == NULL)
3719 return -1;
3720 return PyUnicode_Contains(s, nul);
3721}
3722
3723
3724int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003725PyUnicode_FSConverter(PyObject* arg, void* addr)
3726{
3727 PyObject *output = NULL;
3728 Py_ssize_t size;
3729 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003730 if (arg == NULL) {
3731 Py_DECREF(*(PyObject**)addr);
3732 return 1;
3733 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003734 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003735 output = arg;
3736 Py_INCREF(output);
3737 }
3738 else {
3739 arg = PyUnicode_FromObject(arg);
3740 if (!arg)
3741 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003742 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003743 Py_DECREF(arg);
3744 if (!output)
3745 return 0;
3746 if (!PyBytes_Check(output)) {
3747 Py_DECREF(output);
3748 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3749 return 0;
3750 }
3751 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003752 size = PyBytes_GET_SIZE(output);
3753 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003754 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003755 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003756 Py_DECREF(output);
3757 return 0;
3758 }
3759 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003760 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003761}
3762
3763
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003764int
3765PyUnicode_FSDecoder(PyObject* arg, void* addr)
3766{
3767 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003768 if (arg == NULL) {
3769 Py_DECREF(*(PyObject**)addr);
3770 return 1;
3771 }
3772 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003773 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003774 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003775 output = arg;
3776 Py_INCREF(output);
3777 }
3778 else {
3779 arg = PyBytes_FromObject(arg);
3780 if (!arg)
3781 return 0;
3782 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3783 PyBytes_GET_SIZE(arg));
3784 Py_DECREF(arg);
3785 if (!output)
3786 return 0;
3787 if (!PyUnicode_Check(output)) {
3788 Py_DECREF(output);
3789 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3790 return 0;
3791 }
3792 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003793 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003794 Py_DECREF(output);
3795 return 0;
3796 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003797 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003798 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003799 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3800 Py_DECREF(output);
3801 return 0;
3802 }
3803 *(PyObject**)addr = output;
3804 return Py_CLEANUP_SUPPORTED;
3805}
3806
3807
Martin v. Löwis5b222132007-06-10 09:51:05 +00003808char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003809PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003810{
Christian Heimesf3863112007-11-22 07:46:41 +00003811 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003812
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003813 if (!PyUnicode_Check(unicode)) {
3814 PyErr_BadArgument();
3815 return NULL;
3816 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003817 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003818 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003819
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003820 if (PyUnicode_UTF8(unicode) == NULL) {
3821 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003822 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3823 if (bytes == NULL)
3824 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003825 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3826 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003827 Py_DECREF(bytes);
3828 return NULL;
3829 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003830 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3831 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3832 PyBytes_AS_STRING(bytes),
3833 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003834 Py_DECREF(bytes);
3835 }
3836
3837 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003838 *psize = PyUnicode_UTF8_LENGTH(unicode);
3839 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003840}
3841
3842char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003843PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003844{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003845 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3846}
3847
3848#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003849static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003850#endif
3851
3852
3853Py_UNICODE *
3854PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3855{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003856 const unsigned char *one_byte;
3857#if SIZEOF_WCHAR_T == 4
3858 const Py_UCS2 *two_bytes;
3859#else
3860 const Py_UCS4 *four_bytes;
3861 const Py_UCS4 *ucs4_end;
3862 Py_ssize_t num_surrogates;
3863#endif
3864 wchar_t *w;
3865 wchar_t *wchar_end;
3866
3867 if (!PyUnicode_Check(unicode)) {
3868 PyErr_BadArgument();
3869 return NULL;
3870 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003871 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003872 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003873 assert(_PyUnicode_KIND(unicode) != 0);
3874 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003875
3876#ifdef Py_DEBUG
3877 ++unicode_as_unicode_calls;
3878#endif
3879
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003880 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003881#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003882 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3883 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003884 num_surrogates = 0;
3885
3886 for (; four_bytes < ucs4_end; ++four_bytes) {
3887 if (*four_bytes > 0xFFFF)
3888 ++num_surrogates;
3889 }
3890
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003891 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3892 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3893 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003894 PyErr_NoMemory();
3895 return NULL;
3896 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003897 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003898
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003899 w = _PyUnicode_WSTR(unicode);
3900 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3901 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003902 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3903 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003904 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003905 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003906 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3907 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003908 }
3909 else
3910 *w = *four_bytes;
3911
3912 if (w > wchar_end) {
3913 assert(0 && "Miscalculated string end");
3914 }
3915 }
3916 *w = 0;
3917#else
3918 /* sizeof(wchar_t) == 4 */
3919 Py_FatalError("Impossible unicode object state, wstr and str "
3920 "should share memory already.");
3921 return NULL;
3922#endif
3923 }
3924 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003925 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3926 (_PyUnicode_LENGTH(unicode) + 1));
3927 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003928 PyErr_NoMemory();
3929 return NULL;
3930 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003931 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3932 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3933 w = _PyUnicode_WSTR(unicode);
3934 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003935
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003936 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3937 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003938 for (; w < wchar_end; ++one_byte, ++w)
3939 *w = *one_byte;
3940 /* null-terminate the wstr */
3941 *w = 0;
3942 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003943 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003944#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003945 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003946 for (; w < wchar_end; ++two_bytes, ++w)
3947 *w = *two_bytes;
3948 /* null-terminate the wstr */
3949 *w = 0;
3950#else
3951 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003952 PyObject_FREE(_PyUnicode_WSTR(unicode));
3953 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003954 Py_FatalError("Impossible unicode object state, wstr "
3955 "and str should share memory already.");
3956 return NULL;
3957#endif
3958 }
3959 else {
3960 assert(0 && "This should never happen.");
3961 }
3962 }
3963 }
3964 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003965 *size = PyUnicode_WSTR_LENGTH(unicode);
3966 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003967}
3968
Alexander Belopolsky40018472011-02-26 01:02:56 +00003969Py_UNICODE *
3970PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003971{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003972 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003973}
3974
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003975
Alexander Belopolsky40018472011-02-26 01:02:56 +00003976Py_ssize_t
3977PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003978{
3979 if (!PyUnicode_Check(unicode)) {
3980 PyErr_BadArgument();
3981 goto onError;
3982 }
3983 return PyUnicode_GET_SIZE(unicode);
3984
Benjamin Peterson29060642009-01-31 22:14:21 +00003985 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003986 return -1;
3987}
3988
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003989Py_ssize_t
3990PyUnicode_GetLength(PyObject *unicode)
3991{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003992 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003993 PyErr_BadArgument();
3994 return -1;
3995 }
3996
3997 return PyUnicode_GET_LENGTH(unicode);
3998}
3999
4000Py_UCS4
4001PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4002{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004003 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4004 PyErr_BadArgument();
4005 return (Py_UCS4)-1;
4006 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004007 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004008 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004009 return (Py_UCS4)-1;
4010 }
4011 return PyUnicode_READ_CHAR(unicode, index);
4012}
4013
4014int
4015PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4016{
4017 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004018 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004019 return -1;
4020 }
Victor Stinner488fa492011-12-12 00:01:39 +01004021 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004022 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004023 PyErr_SetString(PyExc_IndexError, "string index out of range");
4024 return -1;
4025 }
Victor Stinner488fa492011-12-12 00:01:39 +01004026 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004027 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004028 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4029 PyErr_SetString(PyExc_ValueError, "character out of range");
4030 return -1;
4031 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004032 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4033 index, ch);
4034 return 0;
4035}
4036
Alexander Belopolsky40018472011-02-26 01:02:56 +00004037const char *
4038PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004039{
Victor Stinner42cb4622010-09-01 19:39:01 +00004040 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004041}
4042
Victor Stinner554f3f02010-06-16 23:33:54 +00004043/* create or adjust a UnicodeDecodeError */
4044static void
4045make_decode_exception(PyObject **exceptionObject,
4046 const char *encoding,
4047 const char *input, Py_ssize_t length,
4048 Py_ssize_t startpos, Py_ssize_t endpos,
4049 const char *reason)
4050{
4051 if (*exceptionObject == NULL) {
4052 *exceptionObject = PyUnicodeDecodeError_Create(
4053 encoding, input, length, startpos, endpos, reason);
4054 }
4055 else {
4056 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4057 goto onError;
4058 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4059 goto onError;
4060 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4061 goto onError;
4062 }
4063 return;
4064
4065onError:
4066 Py_DECREF(*exceptionObject);
4067 *exceptionObject = NULL;
4068}
4069
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004070/* error handling callback helper:
4071 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004072 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004073 and adjust various state variables.
4074 return 0 on success, -1 on error
4075*/
4076
Alexander Belopolsky40018472011-02-26 01:02:56 +00004077static int
4078unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004079 const char *encoding, const char *reason,
4080 const char **input, const char **inend, Py_ssize_t *startinpos,
4081 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004082 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004083{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004084 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004085
4086 PyObject *restuple = NULL;
4087 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004088 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004089 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004090 Py_ssize_t requiredsize;
4091 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004092 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004093 int res = -1;
4094
Victor Stinner596a6c42011-11-09 00:02:18 +01004095 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4096 outsize = PyUnicode_GET_LENGTH(*output);
4097 else
4098 outsize = _PyUnicode_WSTR_LENGTH(*output);
4099
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004100 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004101 *errorHandler = PyCodec_LookupError(errors);
4102 if (*errorHandler == NULL)
4103 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004104 }
4105
Victor Stinner554f3f02010-06-16 23:33:54 +00004106 make_decode_exception(exceptionObject,
4107 encoding,
4108 *input, *inend - *input,
4109 *startinpos, *endinpos,
4110 reason);
4111 if (*exceptionObject == NULL)
4112 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004113
4114 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4115 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004116 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004117 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004118 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004119 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004120 }
4121 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004122 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004123 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004124 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004125
4126 /* Copy back the bytes variables, which might have been modified by the
4127 callback */
4128 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4129 if (!inputobj)
4130 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004131 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004132 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004133 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004134 *input = PyBytes_AS_STRING(inputobj);
4135 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004136 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004137 /* we can DECREF safely, as the exception has another reference,
4138 so the object won't go away. */
4139 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004140
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004141 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004142 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004143 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004144 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4145 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004146 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004147
Victor Stinner596a6c42011-11-09 00:02:18 +01004148 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4149 /* need more space? (at least enough for what we
4150 have+the replacement+the rest of the string (starting
4151 at the new input position), so we won't have to check space
4152 when there are no errors in the rest of the string) */
4153 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4154 requiredsize = *outpos + replen + insize-newpos;
4155 if (requiredsize > outsize) {
4156 if (requiredsize<2*outsize)
4157 requiredsize = 2*outsize;
4158 if (unicode_resize(output, requiredsize) < 0)
4159 goto onError;
4160 }
Victor Stinner1b487b42012-05-03 12:29:04 +02004161 if (unicode_widen(output, *outpos,
4162 PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004163 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004164 _PyUnicode_FastCopyCharacters(*output, *outpos, repunicode, 0, replen);
Victor Stinner596a6c42011-11-09 00:02:18 +01004165 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004166 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004167 else {
4168 wchar_t *repwstr;
4169 Py_ssize_t repwlen;
4170 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4171 if (repwstr == NULL)
4172 goto onError;
4173 /* need more space? (at least enough for what we
4174 have+the replacement+the rest of the string (starting
4175 at the new input position), so we won't have to check space
4176 when there are no errors in the rest of the string) */
4177 requiredsize = *outpos + repwlen + insize-newpos;
4178 if (requiredsize > outsize) {
4179 if (requiredsize < 2*outsize)
4180 requiredsize = 2*outsize;
4181 if (unicode_resize(output, requiredsize) < 0)
4182 goto onError;
4183 }
4184 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4185 *outpos += repwlen;
4186 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004187 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004188 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004189
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004190 /* we made it! */
4191 res = 0;
4192
Benjamin Peterson29060642009-01-31 22:14:21 +00004193 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004194 Py_XDECREF(restuple);
4195 return res;
4196}
4197
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004198/* --- UTF-7 Codec -------------------------------------------------------- */
4199
Antoine Pitrou244651a2009-05-04 18:56:13 +00004200/* See RFC2152 for details. We encode conservatively and decode liberally. */
4201
4202/* Three simple macros defining base-64. */
4203
4204/* Is c a base-64 character? */
4205
4206#define IS_BASE64(c) \
4207 (((c) >= 'A' && (c) <= 'Z') || \
4208 ((c) >= 'a' && (c) <= 'z') || \
4209 ((c) >= '0' && (c) <= '9') || \
4210 (c) == '+' || (c) == '/')
4211
4212/* given that c is a base-64 character, what is its base-64 value? */
4213
4214#define FROM_BASE64(c) \
4215 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4216 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4217 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4218 (c) == '+' ? 62 : 63)
4219
4220/* What is the base-64 character of the bottom 6 bits of n? */
4221
4222#define TO_BASE64(n) \
4223 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4224
4225/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4226 * decoded as itself. We are permissive on decoding; the only ASCII
4227 * byte not decoding to itself is the + which begins a base64
4228 * string. */
4229
4230#define DECODE_DIRECT(c) \
4231 ((c) <= 127 && (c) != '+')
4232
4233/* The UTF-7 encoder treats ASCII characters differently according to
4234 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4235 * the above). See RFC2152. This array identifies these different
4236 * sets:
4237 * 0 : "Set D"
4238 * alphanumeric and '(),-./:?
4239 * 1 : "Set O"
4240 * !"#$%&*;<=>@[]^_`{|}
4241 * 2 : "whitespace"
4242 * ht nl cr sp
4243 * 3 : special (must be base64 encoded)
4244 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4245 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004246
Tim Petersced69f82003-09-16 20:30:58 +00004247static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004248char utf7_category[128] = {
4249/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4250 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4251/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4252 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4253/* sp ! " # $ % & ' ( ) * + , - . / */
4254 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4255/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4256 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4257/* @ A B C D E F G H I J K L M N O */
4258 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4259/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4260 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4261/* ` a b c d e f g h i j k l m n o */
4262 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4263/* p q r s t u v w x y z { | } ~ del */
4264 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004265};
4266
Antoine Pitrou244651a2009-05-04 18:56:13 +00004267/* ENCODE_DIRECT: this character should be encoded as itself. The
4268 * answer depends on whether we are encoding set O as itself, and also
4269 * on whether we are encoding whitespace as itself. RFC2152 makes it
4270 * clear that the answers to these questions vary between
4271 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004272
Antoine Pitrou244651a2009-05-04 18:56:13 +00004273#define ENCODE_DIRECT(c, directO, directWS) \
4274 ((c) < 128 && (c) > 0 && \
4275 ((utf7_category[(c)] == 0) || \
4276 (directWS && (utf7_category[(c)] == 2)) || \
4277 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004278
Alexander Belopolsky40018472011-02-26 01:02:56 +00004279PyObject *
4280PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004281 Py_ssize_t size,
4282 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004283{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004284 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4285}
4286
Antoine Pitrou244651a2009-05-04 18:56:13 +00004287/* The decoder. The only state we preserve is our read position,
4288 * i.e. how many characters we have consumed. So if we end in the
4289 * middle of a shift sequence we have to back off the read position
4290 * and the output to the beginning of the sequence, otherwise we lose
4291 * all the shift state (seen bits, number of bits seen, high
4292 * surrogate). */
4293
Alexander Belopolsky40018472011-02-26 01:02:56 +00004294PyObject *
4295PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004296 Py_ssize_t size,
4297 const char *errors,
4298 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004299{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004300 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004301 Py_ssize_t startinpos;
4302 Py_ssize_t endinpos;
4303 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004304 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004305 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004306 const char *errmsg = "";
4307 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004308 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004309 unsigned int base64bits = 0;
4310 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004311 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004312 PyObject *errorHandler = NULL;
4313 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004314
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004315 /* Start off assuming it's all ASCII. Widen later as necessary. */
4316 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004317 if (!unicode)
4318 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004319 if (size == 0) {
4320 if (consumed)
4321 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004322 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004323 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004324
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004325 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004326 e = s + size;
4327
4328 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004329 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004330 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004331 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004332
Antoine Pitrou244651a2009-05-04 18:56:13 +00004333 if (inShift) { /* in a base-64 section */
4334 if (IS_BASE64(ch)) { /* consume a base-64 character */
4335 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4336 base64bits += 6;
4337 s++;
4338 if (base64bits >= 16) {
4339 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004340 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004341 base64bits -= 16;
4342 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4343 if (surrogate) {
4344 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004345 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4346 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004347 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4348 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004349 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004350 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004351 }
4352 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004353 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4354 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004355 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004356 }
4357 }
Victor Stinner551ac952011-11-29 22:58:13 +01004358 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004359 /* first surrogate */
4360 surrogate = outCh;
4361 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004362 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004363 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4364 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004365 }
4366 }
4367 }
4368 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004369 inShift = 0;
4370 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004371 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004372 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4373 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004374 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004375 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004376 if (base64bits > 0) { /* left-over bits */
4377 if (base64bits >= 6) {
4378 /* We've seen at least one base-64 character */
4379 errmsg = "partial character in shift sequence";
4380 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004381 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004382 else {
4383 /* Some bits remain; they should be zero */
4384 if (base64buffer != 0) {
4385 errmsg = "non-zero padding bits in shift sequence";
4386 goto utf7Error;
4387 }
4388 }
4389 }
4390 if (ch != '-') {
4391 /* '-' is absorbed; other terminating
4392 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004393 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4394 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004395 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004396 }
4397 }
4398 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004399 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004400 s++; /* consume '+' */
4401 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004402 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004403 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4404 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004405 }
4406 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004407 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004408 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004409 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004410 }
4411 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004412 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004413 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4414 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004415 s++;
4416 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004417 else {
4418 startinpos = s-starts;
4419 s++;
4420 errmsg = "unexpected special character";
4421 goto utf7Error;
4422 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004423 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004424utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004425 endinpos = s-starts;
4426 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004427 errors, &errorHandler,
4428 "utf7", errmsg,
4429 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004430 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004431 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004432 }
4433
Antoine Pitrou244651a2009-05-04 18:56:13 +00004434 /* end of string */
4435
4436 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4437 /* if we're in an inconsistent state, that's an error */
4438 if (surrogate ||
4439 (base64bits >= 6) ||
4440 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004441 endinpos = size;
4442 if (unicode_decode_call_errorhandler(
4443 errors, &errorHandler,
4444 "utf7", "unterminated shift sequence",
4445 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004446 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004447 goto onError;
4448 if (s < e)
4449 goto restart;
4450 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004451 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004452
4453 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004454 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004455 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004456 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004457 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004458 }
4459 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004460 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004461 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004462 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004463
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004464 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004465 goto onError;
4466
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004467 Py_XDECREF(errorHandler);
4468 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004469 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004470
Benjamin Peterson29060642009-01-31 22:14:21 +00004471 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004472 Py_XDECREF(errorHandler);
4473 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004474 Py_DECREF(unicode);
4475 return NULL;
4476}
4477
4478
Alexander Belopolsky40018472011-02-26 01:02:56 +00004479PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004480_PyUnicode_EncodeUTF7(PyObject *str,
4481 int base64SetO,
4482 int base64WhiteSpace,
4483 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004484{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004485 int kind;
4486 void *data;
4487 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004488 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004489 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004490 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004491 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004492 unsigned int base64bits = 0;
4493 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004494 char * out;
4495 char * start;
4496
Benjamin Petersonbac79492012-01-14 13:34:47 -05004497 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004498 return NULL;
4499 kind = PyUnicode_KIND(str);
4500 data = PyUnicode_DATA(str);
4501 len = PyUnicode_GET_LENGTH(str);
4502
4503 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004504 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004505
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004506 /* It might be possible to tighten this worst case */
4507 allocated = 8 * len;
4508 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004509 return PyErr_NoMemory();
4510
Antoine Pitrou244651a2009-05-04 18:56:13 +00004511 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004512 if (v == NULL)
4513 return NULL;
4514
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004515 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004516 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004517 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004518
Antoine Pitrou244651a2009-05-04 18:56:13 +00004519 if (inShift) {
4520 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4521 /* shifting out */
4522 if (base64bits) { /* output remaining bits */
4523 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4524 base64buffer = 0;
4525 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004526 }
4527 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004528 /* Characters not in the BASE64 set implicitly unshift the sequence
4529 so no '-' is required, except if the character is itself a '-' */
4530 if (IS_BASE64(ch) || ch == '-') {
4531 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004532 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004533 *out++ = (char) ch;
4534 }
4535 else {
4536 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004537 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004538 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004539 else { /* not in a shift sequence */
4540 if (ch == '+') {
4541 *out++ = '+';
4542 *out++ = '-';
4543 }
4544 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4545 *out++ = (char) ch;
4546 }
4547 else {
4548 *out++ = '+';
4549 inShift = 1;
4550 goto encode_char;
4551 }
4552 }
4553 continue;
4554encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004555 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004556 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004557
Antoine Pitrou244651a2009-05-04 18:56:13 +00004558 /* code first surrogate */
4559 base64bits += 16;
4560 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4561 while (base64bits >= 6) {
4562 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4563 base64bits -= 6;
4564 }
4565 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004566 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004567 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004568 base64bits += 16;
4569 base64buffer = (base64buffer << 16) | ch;
4570 while (base64bits >= 6) {
4571 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4572 base64bits -= 6;
4573 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004574 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004575 if (base64bits)
4576 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4577 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004578 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004579 if (_PyBytes_Resize(&v, out - start) < 0)
4580 return NULL;
4581 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004582}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004583PyObject *
4584PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4585 Py_ssize_t size,
4586 int base64SetO,
4587 int base64WhiteSpace,
4588 const char *errors)
4589{
4590 PyObject *result;
4591 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4592 if (tmp == NULL)
4593 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004594 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004595 base64WhiteSpace, errors);
4596 Py_DECREF(tmp);
4597 return result;
4598}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004599
Antoine Pitrou244651a2009-05-04 18:56:13 +00004600#undef IS_BASE64
4601#undef FROM_BASE64
4602#undef TO_BASE64
4603#undef DECODE_DIRECT
4604#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004605
Guido van Rossumd57fd912000-03-10 22:53:23 +00004606/* --- UTF-8 Codec -------------------------------------------------------- */
4607
Alexander Belopolsky40018472011-02-26 01:02:56 +00004608PyObject *
4609PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004610 Py_ssize_t size,
4611 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004612{
Walter Dörwald69652032004-09-07 20:24:22 +00004613 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4614}
4615
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004616#include "stringlib/asciilib.h"
4617#include "stringlib/codecs.h"
4618#include "stringlib/undef.h"
4619
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004620#include "stringlib/ucs1lib.h"
4621#include "stringlib/codecs.h"
4622#include "stringlib/undef.h"
4623
4624#include "stringlib/ucs2lib.h"
4625#include "stringlib/codecs.h"
4626#include "stringlib/undef.h"
4627
4628#include "stringlib/ucs4lib.h"
4629#include "stringlib/codecs.h"
4630#include "stringlib/undef.h"
4631
Antoine Pitrouab868312009-01-10 15:40:25 +00004632/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4633#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4634
4635/* Mask to quickly check whether a C 'long' contains a
4636 non-ASCII, UTF8-encoded char. */
4637#if (SIZEOF_LONG == 8)
4638# define ASCII_CHAR_MASK 0x8080808080808080L
4639#elif (SIZEOF_LONG == 4)
4640# define ASCII_CHAR_MASK 0x80808080L
4641#else
4642# error C 'long' size should be either 4 or 8!
4643#endif
4644
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004645static Py_ssize_t
4646ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004647{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004648 const char *p = start;
4649 const char *aligned_end = (const char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004650
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004651#if SIZEOF_LONG <= SIZEOF_VOID_P
4652 assert(!((size_t) dest & LONG_PTR_MASK));
4653 if (!((size_t) p & LONG_PTR_MASK)) {
4654 /* Fast path, see in STRINGLIB(utf8_decode) for
4655 an explanation. */
4656 /* Help register allocation */
4657 register const char *_p = p;
4658 register Py_UCS1 * q = dest;
4659 while (_p < aligned_end) {
4660 unsigned long value = *(const unsigned long *) _p;
4661 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004662 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004663 *((unsigned long *)q) = value;
4664 _p += SIZEOF_LONG;
4665 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004666 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004667 p = _p;
4668 while (p < end) {
4669 if ((unsigned char)*p & 0x80)
4670 break;
4671 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004672 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004673 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004674 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004675#endif
4676 while (p < end) {
4677 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4678 for an explanation. */
4679 if (!((size_t) p & LONG_PTR_MASK)) {
4680 /* Help register allocation */
4681 register const char *_p = p;
4682 while (_p < aligned_end) {
4683 unsigned long value = *(unsigned long *) _p;
4684 if (value & ASCII_CHAR_MASK)
4685 break;
4686 _p += SIZEOF_LONG;
4687 }
4688 p = _p;
4689 if (_p == end)
4690 break;
4691 }
4692 if ((unsigned char)*p & 0x80)
4693 break;
4694 ++p;
4695 }
4696 memcpy(dest, start, p - start);
4697 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004698}
Antoine Pitrouab868312009-01-10 15:40:25 +00004699
Victor Stinner785938e2011-12-11 20:09:03 +01004700PyObject *
4701PyUnicode_DecodeUTF8Stateful(const char *s,
4702 Py_ssize_t size,
4703 const char *errors,
4704 Py_ssize_t *consumed)
4705{
Victor Stinner785938e2011-12-11 20:09:03 +01004706 PyObject *unicode;
Victor Stinner785938e2011-12-11 20:09:03 +01004707 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004708 const char *end = s + size;
4709 Py_ssize_t outpos;
4710
4711 Py_ssize_t startinpos;
4712 Py_ssize_t endinpos;
4713 const char *errmsg = "";
4714 PyObject *errorHandler = NULL;
4715 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004716
4717 if (size == 0) {
4718 if (consumed)
4719 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004720 Py_INCREF(unicode_empty);
4721 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004722 }
4723
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004724 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4725 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004726 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004727 *consumed = 1;
4728 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004729 }
4730
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004731 unicode = PyUnicode_New(size, 127);
Victor Stinner785938e2011-12-11 20:09:03 +01004732 if (!unicode)
4733 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004734
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004735 outpos = ascii_decode(s, end, PyUnicode_1BYTE_DATA(unicode));
4736 s += outpos;
4737 while (s < end) {
4738 Py_UCS4 ch;
4739 int kind = PyUnicode_KIND(unicode);
4740 if (kind == PyUnicode_1BYTE_KIND) {
4741 if (PyUnicode_IS_ASCII(unicode))
4742 ch = asciilib_utf8_decode(&s, end,
4743 PyUnicode_1BYTE_DATA(unicode), &outpos);
4744 else
4745 ch = ucs1lib_utf8_decode(&s, end,
4746 PyUnicode_1BYTE_DATA(unicode), &outpos);
4747 } else if (kind == PyUnicode_2BYTE_KIND) {
4748 ch = ucs2lib_utf8_decode(&s, end,
4749 PyUnicode_2BYTE_DATA(unicode), &outpos);
4750 } else {
4751 assert(kind == PyUnicode_4BYTE_KIND);
4752 ch = ucs4lib_utf8_decode(&s, end,
4753 PyUnicode_4BYTE_DATA(unicode), &outpos);
4754 }
4755
4756 switch (ch) {
4757 case 0:
4758 if (s == end || consumed)
4759 goto End;
4760 errmsg = "unexpected end of data";
4761 startinpos = s - starts;
4762 endinpos = startinpos + 1;
4763 while (endinpos < size && (starts[endinpos] & 0xC0) == 0x80)
4764 endinpos++;
4765 break;
4766 case 1:
4767 errmsg = "invalid start byte";
4768 startinpos = s - starts;
4769 endinpos = startinpos + 1;
4770 break;
4771 case 2:
4772 errmsg = "invalid continuation byte";
4773 startinpos = s - starts;
4774 endinpos = startinpos + 1;
4775 while (endinpos < size && (starts[endinpos] & 0xC0) == 0x80)
4776 endinpos++;
4777 break;
4778 default:
4779 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4780 goto onError;
4781 continue;
4782 }
4783
4784 if (unicode_decode_call_errorhandler(
4785 errors, &errorHandler,
4786 "utf-8", errmsg,
4787 &starts, &end, &startinpos, &endinpos, &exc, &s,
4788 &unicode, &outpos))
4789 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004790 }
4791
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004792End:
4793 if (unicode_resize(&unicode, outpos) < 0)
4794 goto onError;
4795
4796 if (consumed)
4797 *consumed = s - starts;
4798
4799 Py_XDECREF(errorHandler);
4800 Py_XDECREF(exc);
4801 assert(_PyUnicode_CheckConsistency(unicode, 1));
4802 return unicode;
4803
4804onError:
4805 Py_XDECREF(errorHandler);
4806 Py_XDECREF(exc);
4807 Py_XDECREF(unicode);
4808 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004809}
4810
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004811#ifdef __APPLE__
4812
4813/* Simplified UTF-8 decoder using surrogateescape error handler,
4814 used to decode the command line arguments on Mac OS X. */
4815
4816wchar_t*
4817_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4818{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004819 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004820 wchar_t *unicode;
4821 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004822
4823 /* Note: size will always be longer than the resulting Unicode
4824 character count */
4825 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4826 PyErr_NoMemory();
4827 return NULL;
4828 }
4829 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4830 if (!unicode)
4831 return NULL;
4832
4833 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004834 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004835 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004836 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004837 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004838#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004839 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004840#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004841 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004842#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004843 if (ch > 0xFF) {
4844#if SIZEOF_WCHAR_T == 4
4845 assert(0);
4846#else
4847 assert(Py_UNICODE_IS_SURROGATE(ch));
4848 /* compute and append the two surrogates: */
4849 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4850 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4851#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004852 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004853 else {
4854 if (!ch && s == e)
4855 break;
4856 /* surrogateescape */
4857 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4858 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004859 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004860 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004861 return unicode;
4862}
4863
4864#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004865
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004866/* Primary internal function which creates utf8 encoded bytes objects.
4867
4868 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004869 and allocate exactly as much space needed at the end. Else allocate the
4870 maximum possible needed (4 result bytes per Unicode character), and return
4871 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004872*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004873PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004874_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004875{
Victor Stinner6099a032011-12-18 14:22:26 +01004876 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004877 void *data;
4878 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004879
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004880 if (!PyUnicode_Check(unicode)) {
4881 PyErr_BadArgument();
4882 return NULL;
4883 }
4884
4885 if (PyUnicode_READY(unicode) == -1)
4886 return NULL;
4887
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004888 if (PyUnicode_UTF8(unicode))
4889 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4890 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004891
4892 kind = PyUnicode_KIND(unicode);
4893 data = PyUnicode_DATA(unicode);
4894 size = PyUnicode_GET_LENGTH(unicode);
4895
Benjamin Petersonead6b532011-12-20 17:23:42 -06004896 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004897 default:
4898 assert(0);
4899 case PyUnicode_1BYTE_KIND:
4900 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4901 assert(!PyUnicode_IS_ASCII(unicode));
4902 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4903 case PyUnicode_2BYTE_KIND:
4904 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4905 case PyUnicode_4BYTE_KIND:
4906 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004907 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004908}
4909
Alexander Belopolsky40018472011-02-26 01:02:56 +00004910PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004911PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4912 Py_ssize_t size,
4913 const char *errors)
4914{
4915 PyObject *v, *unicode;
4916
4917 unicode = PyUnicode_FromUnicode(s, size);
4918 if (unicode == NULL)
4919 return NULL;
4920 v = _PyUnicode_AsUTF8String(unicode, errors);
4921 Py_DECREF(unicode);
4922 return v;
4923}
4924
4925PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004926PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004927{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004928 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004929}
4930
Walter Dörwald41980ca2007-08-16 21:55:45 +00004931/* --- UTF-32 Codec ------------------------------------------------------- */
4932
4933PyObject *
4934PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004935 Py_ssize_t size,
4936 const char *errors,
4937 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004938{
4939 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4940}
4941
4942PyObject *
4943PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004944 Py_ssize_t size,
4945 const char *errors,
4946 int *byteorder,
4947 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004948{
4949 const char *starts = s;
4950 Py_ssize_t startinpos;
4951 Py_ssize_t endinpos;
4952 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004953 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004954 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004955 int bo = 0; /* assume native ordering by default */
4956 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004957 /* Offsets from q for retrieving bytes in the right order. */
4958#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4959 int iorder[] = {0, 1, 2, 3};
4960#else
4961 int iorder[] = {3, 2, 1, 0};
4962#endif
4963 PyObject *errorHandler = NULL;
4964 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004965
Walter Dörwald41980ca2007-08-16 21:55:45 +00004966 q = (unsigned char *)s;
4967 e = q + size;
4968
4969 if (byteorder)
4970 bo = *byteorder;
4971
4972 /* Check for BOM marks (U+FEFF) in the input and adjust current
4973 byte order setting accordingly. In native mode, the leading BOM
4974 mark is skipped, in all other modes, it is copied to the output
4975 stream as-is (giving a ZWNBSP character). */
4976 if (bo == 0) {
4977 if (size >= 4) {
4978 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004979 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004980#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004981 if (bom == 0x0000FEFF) {
4982 q += 4;
4983 bo = -1;
4984 }
4985 else if (bom == 0xFFFE0000) {
4986 q += 4;
4987 bo = 1;
4988 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004989#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004990 if (bom == 0x0000FEFF) {
4991 q += 4;
4992 bo = 1;
4993 }
4994 else if (bom == 0xFFFE0000) {
4995 q += 4;
4996 bo = -1;
4997 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004998#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004999 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005000 }
5001
5002 if (bo == -1) {
5003 /* force LE */
5004 iorder[0] = 0;
5005 iorder[1] = 1;
5006 iorder[2] = 2;
5007 iorder[3] = 3;
5008 }
5009 else if (bo == 1) {
5010 /* force BE */
5011 iorder[0] = 3;
5012 iorder[1] = 2;
5013 iorder[2] = 1;
5014 iorder[3] = 0;
5015 }
5016
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005017 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005018 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005019 if (!unicode)
5020 return NULL;
5021 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005022 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005023 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005024
Walter Dörwald41980ca2007-08-16 21:55:45 +00005025 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005026 Py_UCS4 ch;
5027 /* remaining bytes at the end? (size should be divisible by 4) */
5028 if (e-q<4) {
5029 if (consumed)
5030 break;
5031 errmsg = "truncated data";
5032 startinpos = ((const char *)q)-starts;
5033 endinpos = ((const char *)e)-starts;
5034 goto utf32Error;
5035 /* The remaining input chars are ignored if the callback
5036 chooses to skip the input */
5037 }
5038 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5039 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005040
Benjamin Peterson29060642009-01-31 22:14:21 +00005041 if (ch >= 0x110000)
5042 {
5043 errmsg = "codepoint not in range(0x110000)";
5044 startinpos = ((const char *)q)-starts;
5045 endinpos = startinpos+4;
5046 goto utf32Error;
5047 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005048 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5049 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005050 q += 4;
5051 continue;
5052 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005053 if (unicode_decode_call_errorhandler(
5054 errors, &errorHandler,
5055 "utf32", errmsg,
5056 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005057 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005058 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005059 }
5060
5061 if (byteorder)
5062 *byteorder = bo;
5063
5064 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005065 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005066
5067 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005068 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005069 goto onError;
5070
5071 Py_XDECREF(errorHandler);
5072 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005073 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005074
Benjamin Peterson29060642009-01-31 22:14:21 +00005075 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005076 Py_DECREF(unicode);
5077 Py_XDECREF(errorHandler);
5078 Py_XDECREF(exc);
5079 return NULL;
5080}
5081
5082PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005083_PyUnicode_EncodeUTF32(PyObject *str,
5084 const char *errors,
5085 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005086{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005087 int kind;
5088 void *data;
5089 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005090 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005091 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005092 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005093 /* Offsets from p for storing byte pairs in the right order. */
5094#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5095 int iorder[] = {0, 1, 2, 3};
5096#else
5097 int iorder[] = {3, 2, 1, 0};
5098#endif
5099
Benjamin Peterson29060642009-01-31 22:14:21 +00005100#define STORECHAR(CH) \
5101 do { \
5102 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5103 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5104 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5105 p[iorder[0]] = (CH) & 0xff; \
5106 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005107 } while(0)
5108
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005109 if (!PyUnicode_Check(str)) {
5110 PyErr_BadArgument();
5111 return NULL;
5112 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005113 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005114 return NULL;
5115 kind = PyUnicode_KIND(str);
5116 data = PyUnicode_DATA(str);
5117 len = PyUnicode_GET_LENGTH(str);
5118
5119 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005120 bytesize = nsize * 4;
5121 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005122 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005123 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005124 if (v == NULL)
5125 return NULL;
5126
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005127 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005128 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005129 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005130 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005131 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005132
5133 if (byteorder == -1) {
5134 /* force LE */
5135 iorder[0] = 0;
5136 iorder[1] = 1;
5137 iorder[2] = 2;
5138 iorder[3] = 3;
5139 }
5140 else if (byteorder == 1) {
5141 /* force BE */
5142 iorder[0] = 3;
5143 iorder[1] = 2;
5144 iorder[2] = 1;
5145 iorder[3] = 0;
5146 }
5147
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005148 for (i = 0; i < len; i++)
5149 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005150
5151 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005152 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005153#undef STORECHAR
5154}
5155
Alexander Belopolsky40018472011-02-26 01:02:56 +00005156PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005157PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5158 Py_ssize_t size,
5159 const char *errors,
5160 int byteorder)
5161{
5162 PyObject *result;
5163 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5164 if (tmp == NULL)
5165 return NULL;
5166 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5167 Py_DECREF(tmp);
5168 return result;
5169}
5170
5171PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005172PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005173{
Victor Stinnerb960b342011-11-20 19:12:52 +01005174 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005175}
5176
Guido van Rossumd57fd912000-03-10 22:53:23 +00005177/* --- UTF-16 Codec ------------------------------------------------------- */
5178
Tim Peters772747b2001-08-09 22:21:55 +00005179PyObject *
5180PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005181 Py_ssize_t size,
5182 const char *errors,
5183 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005184{
Walter Dörwald69652032004-09-07 20:24:22 +00005185 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5186}
5187
5188PyObject *
5189PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005190 Py_ssize_t size,
5191 const char *errors,
5192 int *byteorder,
5193 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005194{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005195 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005196 Py_ssize_t startinpos;
5197 Py_ssize_t endinpos;
5198 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005199 PyObject *unicode;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005200 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005201 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005202 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005203 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005204 PyObject *errorHandler = NULL;
5205 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005206
Tim Peters772747b2001-08-09 22:21:55 +00005207 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005208 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005209
5210 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005211 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005212
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005213 /* Check for BOM marks (U+FEFF) in the input and adjust current
5214 byte order setting accordingly. In native mode, the leading BOM
5215 mark is skipped, in all other modes, it is copied to the output
5216 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005217 if (bo == 0 && size >= 2) {
5218 const Py_UCS4 bom = (q[1] << 8) | q[0];
5219 if (bom == 0xFEFF) {
5220 q += 2;
5221 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005222 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005223 else if (bom == 0xFFFE) {
5224 q += 2;
5225 bo = 1;
5226 }
5227 if (byteorder)
5228 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005229 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005230
Antoine Pitrou63065d72012-05-15 23:48:04 +02005231 if (q == e) {
5232 if (consumed)
5233 *consumed = size;
5234 Py_INCREF(unicode_empty);
5235 return unicode_empty;
Tim Peters772747b2001-08-09 22:21:55 +00005236 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005237
Antoine Pitrouab868312009-01-10 15:40:25 +00005238#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005239 native_ordering = bo <= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005240#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005241 native_ordering = bo >= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005242#endif
Tim Peters772747b2001-08-09 22:21:55 +00005243
Antoine Pitrou63065d72012-05-15 23:48:04 +02005244 /* Note: size will always be longer than the resulting Unicode
5245 character count */
5246 unicode = PyUnicode_New((e - q + 1) / 2, 127);
5247 if (!unicode)
5248 return NULL;
5249
5250 outpos = 0;
5251 while (1) {
5252 Py_UCS4 ch = 0;
5253 if (e - q >= 2) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005254 int kind = PyUnicode_KIND(unicode);
Antoine Pitrou63065d72012-05-15 23:48:04 +02005255 if (kind == PyUnicode_1BYTE_KIND) {
5256 if (PyUnicode_IS_ASCII(unicode))
5257 ch = asciilib_utf16_decode(&q, e,
5258 PyUnicode_1BYTE_DATA(unicode), &outpos,
5259 native_ordering);
5260 else
5261 ch = ucs1lib_utf16_decode(&q, e,
5262 PyUnicode_1BYTE_DATA(unicode), &outpos,
5263 native_ordering);
5264 } else if (kind == PyUnicode_2BYTE_KIND) {
5265 ch = ucs2lib_utf16_decode(&q, e,
5266 PyUnicode_2BYTE_DATA(unicode), &outpos,
5267 native_ordering);
5268 } else {
5269 assert(kind == PyUnicode_4BYTE_KIND);
5270 ch = ucs4lib_utf16_decode(&q, e,
5271 PyUnicode_4BYTE_DATA(unicode), &outpos,
5272 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005273 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005274 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005275
Antoine Pitrou63065d72012-05-15 23:48:04 +02005276 switch (ch)
5277 {
5278 case 0:
5279 /* remaining byte at the end? (size should be even) */
5280 if (q == e || consumed)
5281 goto End;
5282 errmsg = "truncated data";
5283 startinpos = ((const char *)q) - starts;
5284 endinpos = ((const char *)e) - starts;
5285 break;
5286 /* The remaining input chars are ignored if the callback
5287 chooses to skip the input */
5288 case 1:
5289 errmsg = "unexpected end of data";
5290 startinpos = ((const char *)q) - 2 - starts;
5291 endinpos = ((const char *)e) - starts;
5292 break;
5293 case 2:
5294 errmsg = "illegal encoding";
5295 startinpos = ((const char *)q) - 2 - starts;
5296 endinpos = startinpos + 2;
5297 break;
5298 case 3:
5299 errmsg = "illegal UTF-16 surrogate";
5300 startinpos = ((const char *)q) - 4 - starts;
5301 endinpos = startinpos + 2;
5302 break;
5303 default:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005304 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5305 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005306 continue;
5307 }
5308
Benjamin Peterson29060642009-01-31 22:14:21 +00005309 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005310 errors,
5311 &errorHandler,
5312 "utf16", errmsg,
5313 &starts,
5314 (const char **)&e,
5315 &startinpos,
5316 &endinpos,
5317 &exc,
5318 (const char **)&q,
5319 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005320 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005321 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005322 }
5323
Antoine Pitrou63065d72012-05-15 23:48:04 +02005324End:
Walter Dörwald69652032004-09-07 20:24:22 +00005325 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005326 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005327
Guido van Rossumd57fd912000-03-10 22:53:23 +00005328 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005329 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005330 goto onError;
5331
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005332 Py_XDECREF(errorHandler);
5333 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005334 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005335
Benjamin Peterson29060642009-01-31 22:14:21 +00005336 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005337 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005338 Py_XDECREF(errorHandler);
5339 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005340 return NULL;
5341}
5342
Tim Peters772747b2001-08-09 22:21:55 +00005343PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005344_PyUnicode_EncodeUTF16(PyObject *str,
5345 const char *errors,
5346 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005347{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005348 enum PyUnicode_Kind kind;
5349 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005350 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005351 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005352 unsigned short *out;
5353 Py_ssize_t bytesize;
5354 Py_ssize_t pairs;
5355#ifdef WORDS_BIGENDIAN
5356 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005357#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005358 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005359#endif
5360
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005361 if (!PyUnicode_Check(str)) {
5362 PyErr_BadArgument();
5363 return NULL;
5364 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005365 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005366 return NULL;
5367 kind = PyUnicode_KIND(str);
5368 data = PyUnicode_DATA(str);
5369 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005370
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005371 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005372 if (kind == PyUnicode_4BYTE_KIND) {
5373 const Py_UCS4 *in = (const Py_UCS4 *)data;
5374 const Py_UCS4 *end = in + len;
5375 while (in < end)
5376 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005377 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005378 }
5379 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005380 return PyErr_NoMemory();
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005381 bytesize = (len + pairs + (byteorder == 0)) * 2;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005382 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005383 if (v == NULL)
5384 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005385
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005386 /* output buffer is 2-bytes aligned */
5387 assert(((Py_uintptr_t)PyBytes_AS_STRING(v) & 1) == 0);
5388 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005389 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005390 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005391 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005392 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005393
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005394 switch (kind) {
5395 case PyUnicode_1BYTE_KIND: {
5396 ucs1lib_utf16_encode(out, (const Py_UCS1 *)data, len, native_ordering);
5397 break;
Tim Peters772747b2001-08-09 22:21:55 +00005398 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005399 case PyUnicode_2BYTE_KIND: {
5400 ucs2lib_utf16_encode(out, (const Py_UCS2 *)data, len, native_ordering);
5401 break;
Tim Peters772747b2001-08-09 22:21:55 +00005402 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005403 case PyUnicode_4BYTE_KIND: {
5404 ucs4lib_utf16_encode(out, (const Py_UCS4 *)data, len, native_ordering);
5405 break;
5406 }
5407 default:
5408 assert(0);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005409 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005410
5411 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005412 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005413}
5414
Alexander Belopolsky40018472011-02-26 01:02:56 +00005415PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005416PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5417 Py_ssize_t size,
5418 const char *errors,
5419 int byteorder)
5420{
5421 PyObject *result;
5422 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5423 if (tmp == NULL)
5424 return NULL;
5425 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5426 Py_DECREF(tmp);
5427 return result;
5428}
5429
5430PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005431PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005432{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005433 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005434}
5435
5436/* --- Unicode Escape Codec ----------------------------------------------- */
5437
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005438/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5439 if all the escapes in the string make it still a valid ASCII string.
5440 Returns -1 if any escapes were found which cause the string to
5441 pop out of ASCII range. Otherwise returns the length of the
5442 required buffer to hold the string.
5443 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005444static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005445length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5446{
5447 const unsigned char *p = (const unsigned char *)s;
5448 const unsigned char *end = p + size;
5449 Py_ssize_t length = 0;
5450
5451 if (size < 0)
5452 return -1;
5453
5454 for (; p < end; ++p) {
5455 if (*p > 127) {
5456 /* Non-ASCII */
5457 return -1;
5458 }
5459 else if (*p != '\\') {
5460 /* Normal character */
5461 ++length;
5462 }
5463 else {
5464 /* Backslash-escape, check next char */
5465 ++p;
5466 /* Escape sequence reaches till end of string or
5467 non-ASCII follow-up. */
5468 if (p >= end || *p > 127)
5469 return -1;
5470 switch (*p) {
5471 case '\n':
5472 /* backslash + \n result in zero characters */
5473 break;
5474 case '\\': case '\'': case '\"':
5475 case 'b': case 'f': case 't':
5476 case 'n': case 'r': case 'v': case 'a':
5477 ++length;
5478 break;
5479 case '0': case '1': case '2': case '3':
5480 case '4': case '5': case '6': case '7':
5481 case 'x': case 'u': case 'U': case 'N':
5482 /* these do not guarantee ASCII characters */
5483 return -1;
5484 default:
5485 /* count the backslash + the other character */
5486 length += 2;
5487 }
5488 }
5489 }
5490 return length;
5491}
5492
Fredrik Lundh06d12682001-01-24 07:59:11 +00005493static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005494
Alexander Belopolsky40018472011-02-26 01:02:56 +00005495PyObject *
5496PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005497 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005498 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005499{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005500 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005501 Py_ssize_t startinpos;
5502 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005503 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005504 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005505 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005506 char* message;
5507 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005508 PyObject *errorHandler = NULL;
5509 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005510 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005511 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005512
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005513 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005514
5515 /* After length_of_escaped_ascii_string() there are two alternatives,
5516 either the string is pure ASCII with named escapes like \n, etc.
5517 and we determined it's exact size (common case)
5518 or it contains \x, \u, ... escape sequences. then we create a
5519 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005520 if (len >= 0) {
5521 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005522 if (!v)
5523 goto onError;
5524 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005525 }
5526 else {
5527 /* Escaped strings will always be longer than the resulting
5528 Unicode string, so we start with size here and then reduce the
5529 length after conversion to the true value.
5530 (but if the error callback returns a long replacement string
5531 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005532 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005533 if (!v)
5534 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005535 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005536 }
5537
Guido van Rossumd57fd912000-03-10 22:53:23 +00005538 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005539 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005540 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005541 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005542
Guido van Rossumd57fd912000-03-10 22:53:23 +00005543 while (s < end) {
5544 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005545 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005546 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005547
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005548 /* The only case in which i == ascii_length is a backslash
5549 followed by a newline. */
5550 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005551
Guido van Rossumd57fd912000-03-10 22:53:23 +00005552 /* Non-escape characters are interpreted as Unicode ordinals */
5553 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005554 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5555 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005556 continue;
5557 }
5558
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005559 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005560 /* \ - Escapes */
5561 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005562 c = *s++;
5563 if (s > end)
5564 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005565
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005566 /* The only case in which i == ascii_length is a backslash
5567 followed by a newline. */
5568 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005569
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005570 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005571
Benjamin Peterson29060642009-01-31 22:14:21 +00005572 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005573#define WRITECHAR(ch) \
5574 do { \
5575 if (unicode_putchar(&v, &i, ch) < 0) \
5576 goto onError; \
5577 }while(0)
5578
Guido van Rossumd57fd912000-03-10 22:53:23 +00005579 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005580 case '\\': WRITECHAR('\\'); break;
5581 case '\'': WRITECHAR('\''); break;
5582 case '\"': WRITECHAR('\"'); break;
5583 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005584 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005585 case 'f': WRITECHAR('\014'); break;
5586 case 't': WRITECHAR('\t'); break;
5587 case 'n': WRITECHAR('\n'); break;
5588 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005589 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005590 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005591 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005592 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005593
Benjamin Peterson29060642009-01-31 22:14:21 +00005594 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005595 case '0': case '1': case '2': case '3':
5596 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005597 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005598 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005599 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005600 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005601 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005602 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005603 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005604 break;
5605
Benjamin Peterson29060642009-01-31 22:14:21 +00005606 /* hex escapes */
5607 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005608 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005609 digits = 2;
5610 message = "truncated \\xXX escape";
5611 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005612
Benjamin Peterson29060642009-01-31 22:14:21 +00005613 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005614 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005615 digits = 4;
5616 message = "truncated \\uXXXX escape";
5617 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005618
Benjamin Peterson29060642009-01-31 22:14:21 +00005619 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005620 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005621 digits = 8;
5622 message = "truncated \\UXXXXXXXX escape";
5623 hexescape:
5624 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005625 if (s+digits>end) {
5626 endinpos = size;
5627 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005628 errors, &errorHandler,
5629 "unicodeescape", "end of string in escape sequence",
5630 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005631 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005632 goto onError;
5633 goto nextByte;
5634 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005635 for (j = 0; j < digits; ++j) {
5636 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005637 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005638 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005639 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005640 errors, &errorHandler,
5641 "unicodeescape", message,
5642 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005643 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005644 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005645 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005646 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005647 }
5648 chr = (chr<<4) & ~0xF;
5649 if (c >= '0' && c <= '9')
5650 chr += c - '0';
5651 else if (c >= 'a' && c <= 'f')
5652 chr += 10 + c - 'a';
5653 else
5654 chr += 10 + c - 'A';
5655 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005656 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005657 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005658 /* _decoding_error will have already written into the
5659 target buffer. */
5660 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005661 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005662 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005663 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005664 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005665 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005666 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005667 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005668 errors, &errorHandler,
5669 "unicodeescape", "illegal Unicode character",
5670 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005671 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005672 goto onError;
5673 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005674 break;
5675
Benjamin Peterson29060642009-01-31 22:14:21 +00005676 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005677 case 'N':
5678 message = "malformed \\N character escape";
5679 if (ucnhash_CAPI == NULL) {
5680 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005681 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5682 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005683 if (ucnhash_CAPI == NULL)
5684 goto ucnhashError;
5685 }
5686 if (*s == '{') {
5687 const char *start = s+1;
5688 /* look for the closing brace */
5689 while (*s != '}' && s < end)
5690 s++;
5691 if (s > start && s < end && *s == '}') {
5692 /* found a name. look it up in the unicode database */
5693 message = "unknown Unicode character name";
5694 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005695 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005696 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005697 goto store;
5698 }
5699 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005700 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005701 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005702 errors, &errorHandler,
5703 "unicodeescape", message,
5704 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005705 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005706 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005707 break;
5708
5709 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005710 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005711 message = "\\ at end of string";
5712 s--;
5713 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005714 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005715 errors, &errorHandler,
5716 "unicodeescape", message,
5717 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005718 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005719 goto onError;
5720 }
5721 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005722 WRITECHAR('\\');
5723 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005724 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005725 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005726 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005727 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005728 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005729 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005730#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005731
Victor Stinner16e6a802011-12-12 13:24:15 +01005732 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005733 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005734 Py_XDECREF(errorHandler);
5735 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005736 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005737
Benjamin Peterson29060642009-01-31 22:14:21 +00005738 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005739 PyErr_SetString(
5740 PyExc_UnicodeError,
5741 "\\N escapes not supported (can't load unicodedata module)"
5742 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005743 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005744 Py_XDECREF(errorHandler);
5745 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005746 return NULL;
5747
Benjamin Peterson29060642009-01-31 22:14:21 +00005748 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005749 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005750 Py_XDECREF(errorHandler);
5751 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005752 return NULL;
5753}
5754
5755/* Return a Unicode-Escape string version of the Unicode object.
5756
5757 If quotes is true, the string is enclosed in u"" or u'' quotes as
5758 appropriate.
5759
5760*/
5761
Alexander Belopolsky40018472011-02-26 01:02:56 +00005762PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005763PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005764{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005765 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005766 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005767 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005768 int kind;
5769 void *data;
5770 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005771
Thomas Wouters89f507f2006-12-13 04:49:30 +00005772 /* Initial allocation is based on the longest-possible unichr
5773 escape.
5774
5775 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5776 unichr, so in this case it's the longest unichr escape. In
5777 narrow (UTF-16) builds this is five chars per source unichr
5778 since there are two unichrs in the surrogate pair, so in narrow
5779 (UTF-16) builds it's not the longest unichr escape.
5780
5781 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5782 so in the narrow (UTF-16) build case it's the longest unichr
5783 escape.
5784 */
5785
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005786 if (!PyUnicode_Check(unicode)) {
5787 PyErr_BadArgument();
5788 return NULL;
5789 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005790 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005791 return NULL;
5792 len = PyUnicode_GET_LENGTH(unicode);
5793 kind = PyUnicode_KIND(unicode);
5794 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005795 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005796 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5797 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5798 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5799 }
5800
5801 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005802 return PyBytes_FromStringAndSize(NULL, 0);
5803
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005804 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005805 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005806
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005807 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005808 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005809 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005810 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005811 if (repr == NULL)
5812 return NULL;
5813
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005814 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005815
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005816 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005817 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005818
Walter Dörwald79e913e2007-05-12 11:08:06 +00005819 /* Escape backslashes */
5820 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005821 *p++ = '\\';
5822 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005823 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005824 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005825
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005826 /* Map 21-bit characters to '\U00xxxxxx' */
5827 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005828 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005829 *p++ = '\\';
5830 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005831 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5832 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5833 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5834 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5835 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5836 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5837 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5838 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005839 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005840 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005841
Guido van Rossumd57fd912000-03-10 22:53:23 +00005842 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005843 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005844 *p++ = '\\';
5845 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005846 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5847 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5848 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5849 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005850 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005851
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005852 /* Map special whitespace to '\t', \n', '\r' */
5853 else if (ch == '\t') {
5854 *p++ = '\\';
5855 *p++ = 't';
5856 }
5857 else if (ch == '\n') {
5858 *p++ = '\\';
5859 *p++ = 'n';
5860 }
5861 else if (ch == '\r') {
5862 *p++ = '\\';
5863 *p++ = 'r';
5864 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005865
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005866 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005867 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005868 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005869 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005870 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5871 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005872 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005873
Guido van Rossumd57fd912000-03-10 22:53:23 +00005874 /* Copy everything else as-is */
5875 else
5876 *p++ = (char) ch;
5877 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005878
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005879 assert(p - PyBytes_AS_STRING(repr) > 0);
5880 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5881 return NULL;
5882 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005883}
5884
Alexander Belopolsky40018472011-02-26 01:02:56 +00005885PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005886PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5887 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005888{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005889 PyObject *result;
5890 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5891 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005892 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005893 result = PyUnicode_AsUnicodeEscapeString(tmp);
5894 Py_DECREF(tmp);
5895 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005896}
5897
5898/* --- Raw Unicode Escape Codec ------------------------------------------- */
5899
Alexander Belopolsky40018472011-02-26 01:02:56 +00005900PyObject *
5901PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005902 Py_ssize_t size,
5903 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005904{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005905 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005906 Py_ssize_t startinpos;
5907 Py_ssize_t endinpos;
5908 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005909 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005910 const char *end;
5911 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005912 PyObject *errorHandler = NULL;
5913 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005914
Guido van Rossumd57fd912000-03-10 22:53:23 +00005915 /* Escaped strings will always be longer than the resulting
5916 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005917 length after conversion to the true value. (But decoding error
5918 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005919 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005920 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005921 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005922 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005923 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005924 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005925 end = s + size;
5926 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005927 unsigned char c;
5928 Py_UCS4 x;
5929 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005930 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005931
Benjamin Peterson29060642009-01-31 22:14:21 +00005932 /* Non-escape characters are interpreted as Unicode ordinals */
5933 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005934 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5935 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005936 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005937 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005938 startinpos = s-starts;
5939
5940 /* \u-escapes are only interpreted iff the number of leading
5941 backslashes if odd */
5942 bs = s;
5943 for (;s < end;) {
5944 if (*s != '\\')
5945 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005946 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5947 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005948 }
5949 if (((s - bs) & 1) == 0 ||
5950 s >= end ||
5951 (*s != 'u' && *s != 'U')) {
5952 continue;
5953 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005954 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00005955 count = *s=='u' ? 4 : 8;
5956 s++;
5957
5958 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00005959 for (x = 0, i = 0; i < count; ++i, ++s) {
5960 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005961 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005962 endinpos = s-starts;
5963 if (unicode_decode_call_errorhandler(
5964 errors, &errorHandler,
5965 "rawunicodeescape", "truncated \\uXXXX",
5966 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005967 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005968 goto onError;
5969 goto nextByte;
5970 }
5971 x = (x<<4) & ~0xF;
5972 if (c >= '0' && c <= '9')
5973 x += c - '0';
5974 else if (c >= 'a' && c <= 'f')
5975 x += 10 + c - 'a';
5976 else
5977 x += 10 + c - 'A';
5978 }
Victor Stinner8faf8212011-12-08 22:14:11 +01005979 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005980 if (unicode_putchar(&v, &outpos, x) < 0)
5981 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005982 } else {
5983 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005984 if (unicode_decode_call_errorhandler(
5985 errors, &errorHandler,
5986 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005987 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005988 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005989 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005990 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005991 nextByte:
5992 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005993 }
Victor Stinner16e6a802011-12-12 13:24:15 +01005994 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005995 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005996 Py_XDECREF(errorHandler);
5997 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005998 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00005999
Benjamin Peterson29060642009-01-31 22:14:21 +00006000 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006001 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006002 Py_XDECREF(errorHandler);
6003 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006004 return NULL;
6005}
6006
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006007
Alexander Belopolsky40018472011-02-26 01:02:56 +00006008PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006009PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006010{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006011 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006012 char *p;
6013 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006014 Py_ssize_t expandsize, pos;
6015 int kind;
6016 void *data;
6017 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006018
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006019 if (!PyUnicode_Check(unicode)) {
6020 PyErr_BadArgument();
6021 return NULL;
6022 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006023 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006024 return NULL;
6025 kind = PyUnicode_KIND(unicode);
6026 data = PyUnicode_DATA(unicode);
6027 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006028 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6029 bytes, and 1 byte characters 4. */
6030 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006031
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006032 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006033 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006034
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006035 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006036 if (repr == NULL)
6037 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006038 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006039 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006040
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006041 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006042 for (pos = 0; pos < len; pos++) {
6043 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006044 /* Map 32-bit characters to '\Uxxxxxxxx' */
6045 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006046 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006047 *p++ = '\\';
6048 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006049 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6050 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6051 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6052 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6053 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6054 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6055 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6056 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006057 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006058 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006059 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006060 *p++ = '\\';
6061 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006062 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6063 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6064 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6065 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006066 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006067 /* Copy everything else as-is */
6068 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006069 *p++ = (char) ch;
6070 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006071
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006072 assert(p > q);
6073 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006074 return NULL;
6075 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006076}
6077
Alexander Belopolsky40018472011-02-26 01:02:56 +00006078PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006079PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6080 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006081{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006082 PyObject *result;
6083 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6084 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006085 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006086 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6087 Py_DECREF(tmp);
6088 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006089}
6090
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006091/* --- Unicode Internal Codec ------------------------------------------- */
6092
Alexander Belopolsky40018472011-02-26 01:02:56 +00006093PyObject *
6094_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006095 Py_ssize_t size,
6096 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006097{
6098 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006099 Py_ssize_t startinpos;
6100 Py_ssize_t endinpos;
6101 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006102 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006103 const char *end;
6104 const char *reason;
6105 PyObject *errorHandler = NULL;
6106 PyObject *exc = NULL;
6107
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006108 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006109 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006110 1))
6111 return NULL;
6112
Thomas Wouters89f507f2006-12-13 04:49:30 +00006113 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006114 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006115 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006116 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006117 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006118 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006119 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006120 end = s + size;
6121
6122 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006123 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006124 Py_UCS4 ch;
6125 /* We copy the raw representation one byte at a time because the
6126 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006127 ((char *) &uch)[0] = s[0];
6128 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006129#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006130 ((char *) &uch)[2] = s[2];
6131 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006132#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006133 ch = uch;
6134
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006135 /* We have to sanity check the raw data, otherwise doom looms for
6136 some malformed UCS-4 data. */
6137 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006138#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006139 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006140#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006141 end-s < Py_UNICODE_SIZE
6142 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006143 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006144 startinpos = s - starts;
6145 if (end-s < Py_UNICODE_SIZE) {
6146 endinpos = end-starts;
6147 reason = "truncated input";
6148 }
6149 else {
6150 endinpos = s - starts + Py_UNICODE_SIZE;
6151 reason = "illegal code point (> 0x10FFFF)";
6152 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006153 if (unicode_decode_call_errorhandler(
6154 errors, &errorHandler,
6155 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006156 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006157 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006158 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006159 continue;
6160 }
6161
6162 s += Py_UNICODE_SIZE;
6163#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006164 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006165 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006166 Py_UNICODE uch2;
6167 ((char *) &uch2)[0] = s[0];
6168 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006169 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006170 {
Victor Stinner551ac952011-11-29 22:58:13 +01006171 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006172 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006173 }
6174 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006175#endif
6176
6177 if (unicode_putchar(&v, &outpos, ch) < 0)
6178 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006179 }
6180
Victor Stinner16e6a802011-12-12 13:24:15 +01006181 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006182 goto onError;
6183 Py_XDECREF(errorHandler);
6184 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006185 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006186
Benjamin Peterson29060642009-01-31 22:14:21 +00006187 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006188 Py_XDECREF(v);
6189 Py_XDECREF(errorHandler);
6190 Py_XDECREF(exc);
6191 return NULL;
6192}
6193
Guido van Rossumd57fd912000-03-10 22:53:23 +00006194/* --- Latin-1 Codec ------------------------------------------------------ */
6195
Alexander Belopolsky40018472011-02-26 01:02:56 +00006196PyObject *
6197PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006198 Py_ssize_t size,
6199 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006200{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006201 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006202 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006203}
6204
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006205/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006206static void
6207make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006208 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006209 PyObject *unicode,
6210 Py_ssize_t startpos, Py_ssize_t endpos,
6211 const char *reason)
6212{
6213 if (*exceptionObject == NULL) {
6214 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006215 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006216 encoding, unicode, startpos, endpos, reason);
6217 }
6218 else {
6219 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6220 goto onError;
6221 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6222 goto onError;
6223 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6224 goto onError;
6225 return;
6226 onError:
6227 Py_DECREF(*exceptionObject);
6228 *exceptionObject = NULL;
6229 }
6230}
6231
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006232/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006233static void
6234raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006235 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006236 PyObject *unicode,
6237 Py_ssize_t startpos, Py_ssize_t endpos,
6238 const char *reason)
6239{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006240 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006241 encoding, unicode, startpos, endpos, reason);
6242 if (*exceptionObject != NULL)
6243 PyCodec_StrictErrors(*exceptionObject);
6244}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006245
6246/* error handling callback helper:
6247 build arguments, call the callback and check the arguments,
6248 put the result into newpos and return the replacement string, which
6249 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006250static PyObject *
6251unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006252 PyObject **errorHandler,
6253 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006254 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006255 Py_ssize_t startpos, Py_ssize_t endpos,
6256 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006257{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006258 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006259 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006260 PyObject *restuple;
6261 PyObject *resunicode;
6262
6263 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006264 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006265 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006266 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006267 }
6268
Benjamin Petersonbac79492012-01-14 13:34:47 -05006269 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006270 return NULL;
6271 len = PyUnicode_GET_LENGTH(unicode);
6272
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006273 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006274 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006275 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006276 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006277
6278 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006279 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006280 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006281 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006282 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006283 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006284 Py_DECREF(restuple);
6285 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006286 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006287 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006288 &resunicode, newpos)) {
6289 Py_DECREF(restuple);
6290 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006291 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006292 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6293 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6294 Py_DECREF(restuple);
6295 return NULL;
6296 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006297 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006298 *newpos = len + *newpos;
6299 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006300 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6301 Py_DECREF(restuple);
6302 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006303 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006304 Py_INCREF(resunicode);
6305 Py_DECREF(restuple);
6306 return resunicode;
6307}
6308
Alexander Belopolsky40018472011-02-26 01:02:56 +00006309static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006310unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006311 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006312 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006313{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006314 /* input state */
6315 Py_ssize_t pos=0, size;
6316 int kind;
6317 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006318 /* output object */
6319 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006320 /* pointer into the output */
6321 char *str;
6322 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006323 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006324 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6325 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006326 PyObject *errorHandler = NULL;
6327 PyObject *exc = NULL;
6328 /* the following variable is used for caching string comparisons
6329 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6330 int known_errorHandler = -1;
6331
Benjamin Petersonbac79492012-01-14 13:34:47 -05006332 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006333 return NULL;
6334 size = PyUnicode_GET_LENGTH(unicode);
6335 kind = PyUnicode_KIND(unicode);
6336 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006337 /* allocate enough for a simple encoding without
6338 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006339 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006340 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006341 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006342 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006343 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006344 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006345 ressize = size;
6346
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006347 while (pos < size) {
6348 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006349
Benjamin Peterson29060642009-01-31 22:14:21 +00006350 /* can we encode this? */
6351 if (c<limit) {
6352 /* no overflow check, because we know that the space is enough */
6353 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006354 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006355 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006356 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006357 Py_ssize_t requiredsize;
6358 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006359 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006360 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006361 Py_ssize_t collstart = pos;
6362 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006363 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006364 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006365 ++collend;
6366 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6367 if (known_errorHandler==-1) {
6368 if ((errors==NULL) || (!strcmp(errors, "strict")))
6369 known_errorHandler = 1;
6370 else if (!strcmp(errors, "replace"))
6371 known_errorHandler = 2;
6372 else if (!strcmp(errors, "ignore"))
6373 known_errorHandler = 3;
6374 else if (!strcmp(errors, "xmlcharrefreplace"))
6375 known_errorHandler = 4;
6376 else
6377 known_errorHandler = 0;
6378 }
6379 switch (known_errorHandler) {
6380 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006381 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006382 goto onError;
6383 case 2: /* replace */
6384 while (collstart++<collend)
6385 *str++ = '?'; /* fall through */
6386 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006387 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006388 break;
6389 case 4: /* xmlcharrefreplace */
6390 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006391 /* determine replacement size */
6392 for (i = collstart, repsize = 0; i < collend; ++i) {
6393 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6394 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006395 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006396 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006397 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006398 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006399 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006400 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006401 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006402 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006403 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006404 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006405 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006406 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006407 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006408 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006409 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006410 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006411 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006412 if (requiredsize > ressize) {
6413 if (requiredsize<2*ressize)
6414 requiredsize = 2*ressize;
6415 if (_PyBytes_Resize(&res, requiredsize))
6416 goto onError;
6417 str = PyBytes_AS_STRING(res) + respos;
6418 ressize = requiredsize;
6419 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006420 /* generate replacement */
6421 for (i = collstart; i < collend; ++i) {
6422 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006423 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006424 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006425 break;
6426 default:
6427 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006428 encoding, reason, unicode, &exc,
6429 collstart, collend, &newpos);
6430 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006431 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006432 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006433 if (PyBytes_Check(repunicode)) {
6434 /* Directly copy bytes result to output. */
6435 repsize = PyBytes_Size(repunicode);
6436 if (repsize > 1) {
6437 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006438 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006439 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6440 Py_DECREF(repunicode);
6441 goto onError;
6442 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006443 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006444 ressize += repsize-1;
6445 }
6446 memcpy(str, PyBytes_AsString(repunicode), repsize);
6447 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006448 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006449 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006450 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006451 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006452 /* need more space? (at least enough for what we
6453 have+the replacement+the rest of the string, so
6454 we won't have to check space for encodable characters) */
6455 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006456 repsize = PyUnicode_GET_LENGTH(repunicode);
6457 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006458 if (requiredsize > ressize) {
6459 if (requiredsize<2*ressize)
6460 requiredsize = 2*ressize;
6461 if (_PyBytes_Resize(&res, requiredsize)) {
6462 Py_DECREF(repunicode);
6463 goto onError;
6464 }
6465 str = PyBytes_AS_STRING(res) + respos;
6466 ressize = requiredsize;
6467 }
6468 /* check if there is anything unencodable in the replacement
6469 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006470 for (i = 0; repsize-->0; ++i, ++str) {
6471 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006472 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006473 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006474 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006475 Py_DECREF(repunicode);
6476 goto onError;
6477 }
6478 *str = (char)c;
6479 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006480 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006481 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006482 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006483 }
6484 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006485 /* Resize if we allocated to much */
6486 size = str - PyBytes_AS_STRING(res);
6487 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006488 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006489 if (_PyBytes_Resize(&res, size) < 0)
6490 goto onError;
6491 }
6492
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006493 Py_XDECREF(errorHandler);
6494 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006495 return res;
6496
6497 onError:
6498 Py_XDECREF(res);
6499 Py_XDECREF(errorHandler);
6500 Py_XDECREF(exc);
6501 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006502}
6503
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006504/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006505PyObject *
6506PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006507 Py_ssize_t size,
6508 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006509{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006510 PyObject *result;
6511 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6512 if (unicode == NULL)
6513 return NULL;
6514 result = unicode_encode_ucs1(unicode, errors, 256);
6515 Py_DECREF(unicode);
6516 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006517}
6518
Alexander Belopolsky40018472011-02-26 01:02:56 +00006519PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006520_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006521{
6522 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006523 PyErr_BadArgument();
6524 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006525 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006526 if (PyUnicode_READY(unicode) == -1)
6527 return NULL;
6528 /* Fast path: if it is a one-byte string, construct
6529 bytes object directly. */
6530 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6531 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6532 PyUnicode_GET_LENGTH(unicode));
6533 /* Non-Latin-1 characters present. Defer to above function to
6534 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006535 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006536}
6537
6538PyObject*
6539PyUnicode_AsLatin1String(PyObject *unicode)
6540{
6541 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006542}
6543
6544/* --- 7-bit ASCII Codec -------------------------------------------------- */
6545
Alexander Belopolsky40018472011-02-26 01:02:56 +00006546PyObject *
6547PyUnicode_DecodeASCII(const char *s,
6548 Py_ssize_t size,
6549 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006550{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006551 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006552 PyObject *unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006553 int kind;
6554 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006555 Py_ssize_t startinpos;
6556 Py_ssize_t endinpos;
6557 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006558 const char *e;
6559 PyObject *errorHandler = NULL;
6560 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006561
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006562 if (size == 0) {
6563 Py_INCREF(unicode_empty);
6564 return unicode_empty;
6565 }
6566
Guido van Rossumd57fd912000-03-10 22:53:23 +00006567 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006568 if (size == 1 && (unsigned char)s[0] < 128)
6569 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006570
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006571 unicode = PyUnicode_New(size, 127);
6572 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006573 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006574
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006575 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006576 data = PyUnicode_1BYTE_DATA(unicode);
6577 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
6578 if (outpos == size)
6579 return unicode;
6580
6581 s += outpos;
6582 kind = PyUnicode_1BYTE_KIND;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006583 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006584 register unsigned char c = (unsigned char)*s;
6585 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006586 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006587 ++s;
6588 }
6589 else {
6590 startinpos = s-starts;
6591 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006592 if (unicode_decode_call_errorhandler(
6593 errors, &errorHandler,
6594 "ascii", "ordinal not in range(128)",
6595 &starts, &e, &startinpos, &endinpos, &exc, &s,
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006596 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006597 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006598 kind = PyUnicode_KIND(unicode);
6599 data = PyUnicode_DATA(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00006600 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006601 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006602 if (unicode_resize(&unicode, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006603 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006604 Py_XDECREF(errorHandler);
6605 Py_XDECREF(exc);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006606 assert(_PyUnicode_CheckConsistency(unicode, 1));
6607 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00006608
Benjamin Peterson29060642009-01-31 22:14:21 +00006609 onError:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006610 Py_XDECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006611 Py_XDECREF(errorHandler);
6612 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006613 return NULL;
6614}
6615
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006616/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006617PyObject *
6618PyUnicode_EncodeASCII(const Py_UNICODE *p,
6619 Py_ssize_t size,
6620 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006621{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006622 PyObject *result;
6623 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6624 if (unicode == NULL)
6625 return NULL;
6626 result = unicode_encode_ucs1(unicode, errors, 128);
6627 Py_DECREF(unicode);
6628 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006629}
6630
Alexander Belopolsky40018472011-02-26 01:02:56 +00006631PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006632_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006633{
6634 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006635 PyErr_BadArgument();
6636 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006637 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006638 if (PyUnicode_READY(unicode) == -1)
6639 return NULL;
6640 /* Fast path: if it is an ASCII-only string, construct bytes object
6641 directly. Else defer to above function to raise the exception. */
6642 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6643 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6644 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006645 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006646}
6647
6648PyObject *
6649PyUnicode_AsASCIIString(PyObject *unicode)
6650{
6651 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006652}
6653
Victor Stinner99b95382011-07-04 14:23:54 +02006654#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006655
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006656/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006657
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006658#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006659#define NEED_RETRY
6660#endif
6661
Victor Stinner3a50e702011-10-18 21:21:00 +02006662#ifndef WC_ERR_INVALID_CHARS
6663# define WC_ERR_INVALID_CHARS 0x0080
6664#endif
6665
6666static char*
6667code_page_name(UINT code_page, PyObject **obj)
6668{
6669 *obj = NULL;
6670 if (code_page == CP_ACP)
6671 return "mbcs";
6672 if (code_page == CP_UTF7)
6673 return "CP_UTF7";
6674 if (code_page == CP_UTF8)
6675 return "CP_UTF8";
6676
6677 *obj = PyBytes_FromFormat("cp%u", code_page);
6678 if (*obj == NULL)
6679 return NULL;
6680 return PyBytes_AS_STRING(*obj);
6681}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006682
Alexander Belopolsky40018472011-02-26 01:02:56 +00006683static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006684is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006685{
6686 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006687 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006688
Victor Stinner3a50e702011-10-18 21:21:00 +02006689 if (!IsDBCSLeadByteEx(code_page, *curr))
6690 return 0;
6691
6692 prev = CharPrevExA(code_page, s, curr, 0);
6693 if (prev == curr)
6694 return 1;
6695 /* FIXME: This code is limited to "true" double-byte encodings,
6696 as it assumes an incomplete character consists of a single
6697 byte. */
6698 if (curr - prev == 2)
6699 return 1;
6700 if (!IsDBCSLeadByteEx(code_page, *prev))
6701 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006702 return 0;
6703}
6704
Victor Stinner3a50e702011-10-18 21:21:00 +02006705static DWORD
6706decode_code_page_flags(UINT code_page)
6707{
6708 if (code_page == CP_UTF7) {
6709 /* The CP_UTF7 decoder only supports flags=0 */
6710 return 0;
6711 }
6712 else
6713 return MB_ERR_INVALID_CHARS;
6714}
6715
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006716/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006717 * Decode a byte string from a Windows code page into unicode object in strict
6718 * mode.
6719 *
6720 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6721 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006722 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006723static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006724decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006725 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006726 const char *in,
6727 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006728{
Victor Stinner3a50e702011-10-18 21:21:00 +02006729 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006730 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006731 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006732
6733 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006734 assert(insize > 0);
6735 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6736 if (outsize <= 0)
6737 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006738
6739 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006740 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006741 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006742 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006743 if (*v == NULL)
6744 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006745 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006746 }
6747 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006748 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006749 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006750 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006751 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006752 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006753 }
6754
6755 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006756 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6757 if (outsize <= 0)
6758 goto error;
6759 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006760
Victor Stinner3a50e702011-10-18 21:21:00 +02006761error:
6762 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6763 return -2;
6764 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006765 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006766}
6767
Victor Stinner3a50e702011-10-18 21:21:00 +02006768/*
6769 * Decode a byte string from a code page into unicode object with an error
6770 * handler.
6771 *
6772 * Returns consumed size if succeed, or raise a WindowsError or
6773 * UnicodeDecodeError exception and returns -1 on error.
6774 */
6775static int
6776decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006777 PyObject **v,
6778 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006779 const char *errors)
6780{
6781 const char *startin = in;
6782 const char *endin = in + size;
6783 const DWORD flags = decode_code_page_flags(code_page);
6784 /* Ideally, we should get reason from FormatMessage. This is the Windows
6785 2000 English version of the message. */
6786 const char *reason = "No mapping for the Unicode character exists "
6787 "in the target code page.";
6788 /* each step cannot decode more than 1 character, but a character can be
6789 represented as a surrogate pair */
6790 wchar_t buffer[2], *startout, *out;
6791 int insize, outsize;
6792 PyObject *errorHandler = NULL;
6793 PyObject *exc = NULL;
6794 PyObject *encoding_obj = NULL;
6795 char *encoding;
6796 DWORD err;
6797 int ret = -1;
6798
6799 assert(size > 0);
6800
6801 encoding = code_page_name(code_page, &encoding_obj);
6802 if (encoding == NULL)
6803 return -1;
6804
6805 if (errors == NULL || strcmp(errors, "strict") == 0) {
6806 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6807 UnicodeDecodeError. */
6808 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6809 if (exc != NULL) {
6810 PyCodec_StrictErrors(exc);
6811 Py_CLEAR(exc);
6812 }
6813 goto error;
6814 }
6815
6816 if (*v == NULL) {
6817 /* Create unicode object */
6818 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6819 PyErr_NoMemory();
6820 goto error;
6821 }
Victor Stinnerab595942011-12-17 04:59:06 +01006822 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006823 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006824 if (*v == NULL)
6825 goto error;
6826 startout = PyUnicode_AS_UNICODE(*v);
6827 }
6828 else {
6829 /* Extend unicode object */
6830 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6831 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6832 PyErr_NoMemory();
6833 goto error;
6834 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006835 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006836 goto error;
6837 startout = PyUnicode_AS_UNICODE(*v) + n;
6838 }
6839
6840 /* Decode the byte string character per character */
6841 out = startout;
6842 while (in < endin)
6843 {
6844 /* Decode a character */
6845 insize = 1;
6846 do
6847 {
6848 outsize = MultiByteToWideChar(code_page, flags,
6849 in, insize,
6850 buffer, Py_ARRAY_LENGTH(buffer));
6851 if (outsize > 0)
6852 break;
6853 err = GetLastError();
6854 if (err != ERROR_NO_UNICODE_TRANSLATION
6855 && err != ERROR_INSUFFICIENT_BUFFER)
6856 {
6857 PyErr_SetFromWindowsErr(0);
6858 goto error;
6859 }
6860 insize++;
6861 }
6862 /* 4=maximum length of a UTF-8 sequence */
6863 while (insize <= 4 && (in + insize) <= endin);
6864
6865 if (outsize <= 0) {
6866 Py_ssize_t startinpos, endinpos, outpos;
6867
6868 startinpos = in - startin;
6869 endinpos = startinpos + 1;
6870 outpos = out - PyUnicode_AS_UNICODE(*v);
6871 if (unicode_decode_call_errorhandler(
6872 errors, &errorHandler,
6873 encoding, reason,
6874 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006875 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006876 {
6877 goto error;
6878 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006879 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006880 }
6881 else {
6882 in += insize;
6883 memcpy(out, buffer, outsize * sizeof(wchar_t));
6884 out += outsize;
6885 }
6886 }
6887
6888 /* write a NUL character at the end */
6889 *out = 0;
6890
6891 /* Extend unicode object */
6892 outsize = out - startout;
6893 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006894 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006895 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01006896 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006897
6898error:
6899 Py_XDECREF(encoding_obj);
6900 Py_XDECREF(errorHandler);
6901 Py_XDECREF(exc);
6902 return ret;
6903}
6904
Victor Stinner3a50e702011-10-18 21:21:00 +02006905static PyObject *
6906decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006907 const char *s, Py_ssize_t size,
6908 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006909{
Victor Stinner76a31a62011-11-04 00:05:13 +01006910 PyObject *v = NULL;
6911 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006912
Victor Stinner3a50e702011-10-18 21:21:00 +02006913 if (code_page < 0) {
6914 PyErr_SetString(PyExc_ValueError, "invalid code page number");
6915 return NULL;
6916 }
6917
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006918 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006919 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006920
Victor Stinner76a31a62011-11-04 00:05:13 +01006921 do
6922 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006923#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01006924 if (size > INT_MAX) {
6925 chunk_size = INT_MAX;
6926 final = 0;
6927 done = 0;
6928 }
6929 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006930#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01006931 {
6932 chunk_size = (int)size;
6933 final = (consumed == NULL);
6934 done = 1;
6935 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006936
Victor Stinner76a31a62011-11-04 00:05:13 +01006937 /* Skip trailing lead-byte unless 'final' is set */
6938 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
6939 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006940
Victor Stinner76a31a62011-11-04 00:05:13 +01006941 if (chunk_size == 0 && done) {
6942 if (v != NULL)
6943 break;
6944 Py_INCREF(unicode_empty);
6945 return unicode_empty;
6946 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006947
Victor Stinner76a31a62011-11-04 00:05:13 +01006948
6949 converted = decode_code_page_strict(code_page, &v,
6950 s, chunk_size);
6951 if (converted == -2)
6952 converted = decode_code_page_errors(code_page, &v,
6953 s, chunk_size,
6954 errors);
6955 assert(converted != 0);
6956
6957 if (converted < 0) {
6958 Py_XDECREF(v);
6959 return NULL;
6960 }
6961
6962 if (consumed)
6963 *consumed += converted;
6964
6965 s += converted;
6966 size -= converted;
6967 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02006968
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006969 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006970}
6971
Alexander Belopolsky40018472011-02-26 01:02:56 +00006972PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02006973PyUnicode_DecodeCodePageStateful(int code_page,
6974 const char *s,
6975 Py_ssize_t size,
6976 const char *errors,
6977 Py_ssize_t *consumed)
6978{
6979 return decode_code_page_stateful(code_page, s, size, errors, consumed);
6980}
6981
6982PyObject *
6983PyUnicode_DecodeMBCSStateful(const char *s,
6984 Py_ssize_t size,
6985 const char *errors,
6986 Py_ssize_t *consumed)
6987{
6988 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
6989}
6990
6991PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006992PyUnicode_DecodeMBCS(const char *s,
6993 Py_ssize_t size,
6994 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006995{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006996 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6997}
6998
Victor Stinner3a50e702011-10-18 21:21:00 +02006999static DWORD
7000encode_code_page_flags(UINT code_page, const char *errors)
7001{
7002 if (code_page == CP_UTF8) {
7003 if (winver.dwMajorVersion >= 6)
7004 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7005 and later */
7006 return WC_ERR_INVALID_CHARS;
7007 else
7008 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7009 return 0;
7010 }
7011 else if (code_page == CP_UTF7) {
7012 /* CP_UTF7 only supports flags=0 */
7013 return 0;
7014 }
7015 else {
7016 if (errors != NULL && strcmp(errors, "replace") == 0)
7017 return 0;
7018 else
7019 return WC_NO_BEST_FIT_CHARS;
7020 }
7021}
7022
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007023/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007024 * Encode a Unicode string to a Windows code page into a byte string in strict
7025 * mode.
7026 *
7027 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7028 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007029 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007030static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007031encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007032 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007033 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007034{
Victor Stinner554f3f02010-06-16 23:33:54 +00007035 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007036 BOOL *pusedDefaultChar = &usedDefaultChar;
7037 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007038 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007039 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007040 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007041 const DWORD flags = encode_code_page_flags(code_page, NULL);
7042 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007043 /* Create a substring so that we can get the UTF-16 representation
7044 of just the slice under consideration. */
7045 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007046
Martin v. Löwis3d325192011-11-04 18:23:06 +01007047 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007048
Victor Stinner3a50e702011-10-18 21:21:00 +02007049 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007050 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007051 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007052 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007053
Victor Stinner2fc507f2011-11-04 20:06:39 +01007054 substring = PyUnicode_Substring(unicode, offset, offset+len);
7055 if (substring == NULL)
7056 return -1;
7057 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7058 if (p == NULL) {
7059 Py_DECREF(substring);
7060 return -1;
7061 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007062
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007063 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007064 outsize = WideCharToMultiByte(code_page, flags,
7065 p, size,
7066 NULL, 0,
7067 NULL, pusedDefaultChar);
7068 if (outsize <= 0)
7069 goto error;
7070 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007071 if (pusedDefaultChar && *pusedDefaultChar) {
7072 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007073 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007074 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007075
Victor Stinner3a50e702011-10-18 21:21:00 +02007076 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007077 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007078 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007079 if (*outbytes == NULL) {
7080 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007081 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007082 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007083 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007084 }
7085 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007086 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007087 const Py_ssize_t n = PyBytes_Size(*outbytes);
7088 if (outsize > PY_SSIZE_T_MAX - n) {
7089 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007090 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007091 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007092 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007093 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7094 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007095 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007096 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007097 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007098 }
7099
7100 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007101 outsize = WideCharToMultiByte(code_page, flags,
7102 p, size,
7103 out, outsize,
7104 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007105 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007106 if (outsize <= 0)
7107 goto error;
7108 if (pusedDefaultChar && *pusedDefaultChar)
7109 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007110 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007111
Victor Stinner3a50e702011-10-18 21:21:00 +02007112error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007113 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007114 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7115 return -2;
7116 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007117 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007118}
7119
Victor Stinner3a50e702011-10-18 21:21:00 +02007120/*
7121 * Encode a Unicode string to a Windows code page into a byte string using a
7122 * error handler.
7123 *
7124 * Returns consumed characters if succeed, or raise a WindowsError and returns
7125 * -1 on other error.
7126 */
7127static int
7128encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007129 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007130 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007131{
Victor Stinner3a50e702011-10-18 21:21:00 +02007132 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007133 Py_ssize_t pos = unicode_offset;
7134 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007135 /* Ideally, we should get reason from FormatMessage. This is the Windows
7136 2000 English version of the message. */
7137 const char *reason = "invalid character";
7138 /* 4=maximum length of a UTF-8 sequence */
7139 char buffer[4];
7140 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7141 Py_ssize_t outsize;
7142 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007143 PyObject *errorHandler = NULL;
7144 PyObject *exc = NULL;
7145 PyObject *encoding_obj = NULL;
7146 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007147 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007148 PyObject *rep;
7149 int ret = -1;
7150
7151 assert(insize > 0);
7152
7153 encoding = code_page_name(code_page, &encoding_obj);
7154 if (encoding == NULL)
7155 return -1;
7156
7157 if (errors == NULL || strcmp(errors, "strict") == 0) {
7158 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7159 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007160 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007161 if (exc != NULL) {
7162 PyCodec_StrictErrors(exc);
7163 Py_DECREF(exc);
7164 }
7165 Py_XDECREF(encoding_obj);
7166 return -1;
7167 }
7168
7169 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7170 pusedDefaultChar = &usedDefaultChar;
7171 else
7172 pusedDefaultChar = NULL;
7173
7174 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7175 PyErr_NoMemory();
7176 goto error;
7177 }
7178 outsize = insize * Py_ARRAY_LENGTH(buffer);
7179
7180 if (*outbytes == NULL) {
7181 /* Create string object */
7182 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7183 if (*outbytes == NULL)
7184 goto error;
7185 out = PyBytes_AS_STRING(*outbytes);
7186 }
7187 else {
7188 /* Extend string object */
7189 Py_ssize_t n = PyBytes_Size(*outbytes);
7190 if (n > PY_SSIZE_T_MAX - outsize) {
7191 PyErr_NoMemory();
7192 goto error;
7193 }
7194 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7195 goto error;
7196 out = PyBytes_AS_STRING(*outbytes) + n;
7197 }
7198
7199 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007200 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007201 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007202 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7203 wchar_t chars[2];
7204 int charsize;
7205 if (ch < 0x10000) {
7206 chars[0] = (wchar_t)ch;
7207 charsize = 1;
7208 }
7209 else {
7210 ch -= 0x10000;
7211 chars[0] = 0xd800 + (ch >> 10);
7212 chars[1] = 0xdc00 + (ch & 0x3ff);
7213 charsize = 2;
7214 }
7215
Victor Stinner3a50e702011-10-18 21:21:00 +02007216 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007217 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007218 buffer, Py_ARRAY_LENGTH(buffer),
7219 NULL, pusedDefaultChar);
7220 if (outsize > 0) {
7221 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7222 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007223 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007224 memcpy(out, buffer, outsize);
7225 out += outsize;
7226 continue;
7227 }
7228 }
7229 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7230 PyErr_SetFromWindowsErr(0);
7231 goto error;
7232 }
7233
Victor Stinner3a50e702011-10-18 21:21:00 +02007234 rep = unicode_encode_call_errorhandler(
7235 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007236 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007237 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007238 if (rep == NULL)
7239 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007240 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007241
7242 if (PyBytes_Check(rep)) {
7243 outsize = PyBytes_GET_SIZE(rep);
7244 if (outsize != 1) {
7245 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7246 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7247 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7248 Py_DECREF(rep);
7249 goto error;
7250 }
7251 out = PyBytes_AS_STRING(*outbytes) + offset;
7252 }
7253 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7254 out += outsize;
7255 }
7256 else {
7257 Py_ssize_t i;
7258 enum PyUnicode_Kind kind;
7259 void *data;
7260
Benjamin Petersonbac79492012-01-14 13:34:47 -05007261 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007262 Py_DECREF(rep);
7263 goto error;
7264 }
7265
7266 outsize = PyUnicode_GET_LENGTH(rep);
7267 if (outsize != 1) {
7268 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7269 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7270 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7271 Py_DECREF(rep);
7272 goto error;
7273 }
7274 out = PyBytes_AS_STRING(*outbytes) + offset;
7275 }
7276 kind = PyUnicode_KIND(rep);
7277 data = PyUnicode_DATA(rep);
7278 for (i=0; i < outsize; i++) {
7279 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7280 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007281 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007282 encoding, unicode,
7283 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007284 "unable to encode error handler result to ASCII");
7285 Py_DECREF(rep);
7286 goto error;
7287 }
7288 *out = (unsigned char)ch;
7289 out++;
7290 }
7291 }
7292 Py_DECREF(rep);
7293 }
7294 /* write a NUL byte */
7295 *out = 0;
7296 outsize = out - PyBytes_AS_STRING(*outbytes);
7297 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7298 if (_PyBytes_Resize(outbytes, outsize) < 0)
7299 goto error;
7300 ret = 0;
7301
7302error:
7303 Py_XDECREF(encoding_obj);
7304 Py_XDECREF(errorHandler);
7305 Py_XDECREF(exc);
7306 return ret;
7307}
7308
Victor Stinner3a50e702011-10-18 21:21:00 +02007309static PyObject *
7310encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007311 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007312 const char *errors)
7313{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007314 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007315 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007316 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007317 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007318
Benjamin Petersonbac79492012-01-14 13:34:47 -05007319 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007320 return NULL;
7321 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007322
Victor Stinner3a50e702011-10-18 21:21:00 +02007323 if (code_page < 0) {
7324 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7325 return NULL;
7326 }
7327
Martin v. Löwis3d325192011-11-04 18:23:06 +01007328 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007329 return PyBytes_FromStringAndSize(NULL, 0);
7330
Victor Stinner7581cef2011-11-03 22:32:33 +01007331 offset = 0;
7332 do
7333 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007334#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007335 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007336 chunks. */
7337 if (len > INT_MAX/2) {
7338 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007339 done = 0;
7340 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007341 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007342#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007343 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007344 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007345 done = 1;
7346 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007347
Victor Stinner76a31a62011-11-04 00:05:13 +01007348 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007349 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007350 errors);
7351 if (ret == -2)
7352 ret = encode_code_page_errors(code_page, &outbytes,
7353 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007354 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007355 if (ret < 0) {
7356 Py_XDECREF(outbytes);
7357 return NULL;
7358 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007359
Victor Stinner7581cef2011-11-03 22:32:33 +01007360 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007361 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007362 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007363
Victor Stinner3a50e702011-10-18 21:21:00 +02007364 return outbytes;
7365}
7366
7367PyObject *
7368PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7369 Py_ssize_t size,
7370 const char *errors)
7371{
Victor Stinner7581cef2011-11-03 22:32:33 +01007372 PyObject *unicode, *res;
7373 unicode = PyUnicode_FromUnicode(p, size);
7374 if (unicode == NULL)
7375 return NULL;
7376 res = encode_code_page(CP_ACP, unicode, errors);
7377 Py_DECREF(unicode);
7378 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007379}
7380
7381PyObject *
7382PyUnicode_EncodeCodePage(int code_page,
7383 PyObject *unicode,
7384 const char *errors)
7385{
Victor Stinner7581cef2011-11-03 22:32:33 +01007386 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007387}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007388
Alexander Belopolsky40018472011-02-26 01:02:56 +00007389PyObject *
7390PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007391{
7392 if (!PyUnicode_Check(unicode)) {
7393 PyErr_BadArgument();
7394 return NULL;
7395 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007396 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007397}
7398
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007399#undef NEED_RETRY
7400
Victor Stinner99b95382011-07-04 14:23:54 +02007401#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007402
Guido van Rossumd57fd912000-03-10 22:53:23 +00007403/* --- Character Mapping Codec -------------------------------------------- */
7404
Alexander Belopolsky40018472011-02-26 01:02:56 +00007405PyObject *
7406PyUnicode_DecodeCharmap(const char *s,
7407 Py_ssize_t size,
7408 PyObject *mapping,
7409 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007410{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007411 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007412 Py_ssize_t startinpos;
7413 Py_ssize_t endinpos;
7414 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007415 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007416 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007417 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007418 PyObject *errorHandler = NULL;
7419 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007420
Guido van Rossumd57fd912000-03-10 22:53:23 +00007421 /* Default to Latin-1 */
7422 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007423 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007424
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007425 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007426 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007427 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007428 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007429 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007430 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007431 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007432 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007433 Py_ssize_t maplen;
7434 enum PyUnicode_Kind kind;
7435 void *data;
7436 Py_UCS4 x;
7437
Benjamin Petersonbac79492012-01-14 13:34:47 -05007438 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007439 return NULL;
7440
7441 maplen = PyUnicode_GET_LENGTH(mapping);
7442 data = PyUnicode_DATA(mapping);
7443 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007444 while (s < e) {
7445 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007446
Benjamin Peterson29060642009-01-31 22:14:21 +00007447 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007448 x = PyUnicode_READ(kind, data, ch);
7449 else
7450 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007451
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007452 if (x == 0xfffe)
7453 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007454 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007455 startinpos = s-starts;
7456 endinpos = startinpos+1;
7457 if (unicode_decode_call_errorhandler(
7458 errors, &errorHandler,
7459 "charmap", "character maps to <undefined>",
7460 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007461 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007462 goto onError;
7463 }
7464 continue;
7465 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007466
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007467 if (unicode_putchar(&v, &outpos, x) < 0)
7468 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007469 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007470 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007471 }
7472 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007473 while (s < e) {
7474 unsigned char ch = *s;
7475 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007476
Benjamin Peterson29060642009-01-31 22:14:21 +00007477 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7478 w = PyLong_FromLong((long)ch);
7479 if (w == NULL)
7480 goto onError;
7481 x = PyObject_GetItem(mapping, w);
7482 Py_DECREF(w);
7483 if (x == NULL) {
7484 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7485 /* No mapping found means: mapping is undefined. */
7486 PyErr_Clear();
7487 x = Py_None;
7488 Py_INCREF(x);
7489 } else
7490 goto onError;
7491 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007492
Benjamin Peterson29060642009-01-31 22:14:21 +00007493 /* Apply mapping */
7494 if (PyLong_Check(x)) {
7495 long value = PyLong_AS_LONG(x);
7496 if (value < 0 || value > 65535) {
7497 PyErr_SetString(PyExc_TypeError,
7498 "character mapping must be in range(65536)");
7499 Py_DECREF(x);
7500 goto onError;
7501 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007502 if (unicode_putchar(&v, &outpos, value) < 0)
7503 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007504 }
7505 else if (x == Py_None) {
7506 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007507 startinpos = s-starts;
7508 endinpos = startinpos+1;
7509 if (unicode_decode_call_errorhandler(
7510 errors, &errorHandler,
7511 "charmap", "character maps to <undefined>",
7512 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007513 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007514 Py_DECREF(x);
7515 goto onError;
7516 }
7517 Py_DECREF(x);
7518 continue;
7519 }
7520 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007521 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007522
Benjamin Petersonbac79492012-01-14 13:34:47 -05007523 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007524 goto onError;
7525 targetsize = PyUnicode_GET_LENGTH(x);
7526
7527 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007528 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007529 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007530 PyUnicode_READ_CHAR(x, 0)) < 0)
7531 goto onError;
7532 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007533 else if (targetsize > 1) {
7534 /* 1-n mapping */
7535 if (targetsize > extrachars) {
7536 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007537 Py_ssize_t needed = (targetsize - extrachars) + \
7538 (targetsize << 2);
7539 extrachars += needed;
7540 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007541 if (unicode_resize(&v,
7542 PyUnicode_GET_LENGTH(v) + needed) < 0)
7543 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007544 Py_DECREF(x);
7545 goto onError;
7546 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007547 }
Victor Stinner1b487b42012-05-03 12:29:04 +02007548 if (unicode_widen(&v, outpos, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007549 goto onError;
7550 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7551 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007552 extrachars -= targetsize;
7553 }
7554 /* 1-0 mapping: skip the character */
7555 }
7556 else {
7557 /* wrong return value */
7558 PyErr_SetString(PyExc_TypeError,
7559 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007560 Py_DECREF(x);
7561 goto onError;
7562 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007563 Py_DECREF(x);
7564 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007565 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007566 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007567 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007568 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007569 Py_XDECREF(errorHandler);
7570 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007571 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007572
Benjamin Peterson29060642009-01-31 22:14:21 +00007573 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007574 Py_XDECREF(errorHandler);
7575 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007576 Py_XDECREF(v);
7577 return NULL;
7578}
7579
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007580/* Charmap encoding: the lookup table */
7581
Alexander Belopolsky40018472011-02-26 01:02:56 +00007582struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007583 PyObject_HEAD
7584 unsigned char level1[32];
7585 int count2, count3;
7586 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007587};
7588
7589static PyObject*
7590encoding_map_size(PyObject *obj, PyObject* args)
7591{
7592 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007593 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007594 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007595}
7596
7597static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007598 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007599 PyDoc_STR("Return the size (in bytes) of this object") },
7600 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007601};
7602
7603static void
7604encoding_map_dealloc(PyObject* o)
7605{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007606 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007607}
7608
7609static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007610 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007611 "EncodingMap", /*tp_name*/
7612 sizeof(struct encoding_map), /*tp_basicsize*/
7613 0, /*tp_itemsize*/
7614 /* methods */
7615 encoding_map_dealloc, /*tp_dealloc*/
7616 0, /*tp_print*/
7617 0, /*tp_getattr*/
7618 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007619 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007620 0, /*tp_repr*/
7621 0, /*tp_as_number*/
7622 0, /*tp_as_sequence*/
7623 0, /*tp_as_mapping*/
7624 0, /*tp_hash*/
7625 0, /*tp_call*/
7626 0, /*tp_str*/
7627 0, /*tp_getattro*/
7628 0, /*tp_setattro*/
7629 0, /*tp_as_buffer*/
7630 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7631 0, /*tp_doc*/
7632 0, /*tp_traverse*/
7633 0, /*tp_clear*/
7634 0, /*tp_richcompare*/
7635 0, /*tp_weaklistoffset*/
7636 0, /*tp_iter*/
7637 0, /*tp_iternext*/
7638 encoding_map_methods, /*tp_methods*/
7639 0, /*tp_members*/
7640 0, /*tp_getset*/
7641 0, /*tp_base*/
7642 0, /*tp_dict*/
7643 0, /*tp_descr_get*/
7644 0, /*tp_descr_set*/
7645 0, /*tp_dictoffset*/
7646 0, /*tp_init*/
7647 0, /*tp_alloc*/
7648 0, /*tp_new*/
7649 0, /*tp_free*/
7650 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007651};
7652
7653PyObject*
7654PyUnicode_BuildEncodingMap(PyObject* string)
7655{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007656 PyObject *result;
7657 struct encoding_map *mresult;
7658 int i;
7659 int need_dict = 0;
7660 unsigned char level1[32];
7661 unsigned char level2[512];
7662 unsigned char *mlevel1, *mlevel2, *mlevel3;
7663 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007664 int kind;
7665 void *data;
7666 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007667
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007668 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007669 PyErr_BadArgument();
7670 return NULL;
7671 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007672 kind = PyUnicode_KIND(string);
7673 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007674 memset(level1, 0xFF, sizeof level1);
7675 memset(level2, 0xFF, sizeof level2);
7676
7677 /* If there isn't a one-to-one mapping of NULL to \0,
7678 or if there are non-BMP characters, we need to use
7679 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007680 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007681 need_dict = 1;
7682 for (i = 1; i < 256; i++) {
7683 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007684 ch = PyUnicode_READ(kind, data, i);
7685 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007686 need_dict = 1;
7687 break;
7688 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007689 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007690 /* unmapped character */
7691 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007692 l1 = ch >> 11;
7693 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007694 if (level1[l1] == 0xFF)
7695 level1[l1] = count2++;
7696 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007697 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007698 }
7699
7700 if (count2 >= 0xFF || count3 >= 0xFF)
7701 need_dict = 1;
7702
7703 if (need_dict) {
7704 PyObject *result = PyDict_New();
7705 PyObject *key, *value;
7706 if (!result)
7707 return NULL;
7708 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007709 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007710 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007711 if (!key || !value)
7712 goto failed1;
7713 if (PyDict_SetItem(result, key, value) == -1)
7714 goto failed1;
7715 Py_DECREF(key);
7716 Py_DECREF(value);
7717 }
7718 return result;
7719 failed1:
7720 Py_XDECREF(key);
7721 Py_XDECREF(value);
7722 Py_DECREF(result);
7723 return NULL;
7724 }
7725
7726 /* Create a three-level trie */
7727 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7728 16*count2 + 128*count3 - 1);
7729 if (!result)
7730 return PyErr_NoMemory();
7731 PyObject_Init(result, &EncodingMapType);
7732 mresult = (struct encoding_map*)result;
7733 mresult->count2 = count2;
7734 mresult->count3 = count3;
7735 mlevel1 = mresult->level1;
7736 mlevel2 = mresult->level23;
7737 mlevel3 = mresult->level23 + 16*count2;
7738 memcpy(mlevel1, level1, 32);
7739 memset(mlevel2, 0xFF, 16*count2);
7740 memset(mlevel3, 0, 128*count3);
7741 count3 = 0;
7742 for (i = 1; i < 256; i++) {
7743 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007744 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007745 /* unmapped character */
7746 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007747 o1 = PyUnicode_READ(kind, data, i)>>11;
7748 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007749 i2 = 16*mlevel1[o1] + o2;
7750 if (mlevel2[i2] == 0xFF)
7751 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007752 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007753 i3 = 128*mlevel2[i2] + o3;
7754 mlevel3[i3] = i;
7755 }
7756 return result;
7757}
7758
7759static int
Victor Stinner22168992011-11-20 17:09:18 +01007760encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007761{
7762 struct encoding_map *map = (struct encoding_map*)mapping;
7763 int l1 = c>>11;
7764 int l2 = (c>>7) & 0xF;
7765 int l3 = c & 0x7F;
7766 int i;
7767
Victor Stinner22168992011-11-20 17:09:18 +01007768 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007769 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007770 if (c == 0)
7771 return 0;
7772 /* level 1*/
7773 i = map->level1[l1];
7774 if (i == 0xFF) {
7775 return -1;
7776 }
7777 /* level 2*/
7778 i = map->level23[16*i+l2];
7779 if (i == 0xFF) {
7780 return -1;
7781 }
7782 /* level 3 */
7783 i = map->level23[16*map->count2 + 128*i + l3];
7784 if (i == 0) {
7785 return -1;
7786 }
7787 return i;
7788}
7789
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007790/* Lookup the character ch in the mapping. If the character
7791 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007792 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007793static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007794charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007795{
Christian Heimes217cfd12007-12-02 14:31:20 +00007796 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007797 PyObject *x;
7798
7799 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007800 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007801 x = PyObject_GetItem(mapping, w);
7802 Py_DECREF(w);
7803 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007804 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7805 /* No mapping found means: mapping is undefined. */
7806 PyErr_Clear();
7807 x = Py_None;
7808 Py_INCREF(x);
7809 return x;
7810 } else
7811 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007812 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007813 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007814 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007815 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007816 long value = PyLong_AS_LONG(x);
7817 if (value < 0 || value > 255) {
7818 PyErr_SetString(PyExc_TypeError,
7819 "character mapping must be in range(256)");
7820 Py_DECREF(x);
7821 return NULL;
7822 }
7823 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007824 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007825 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007826 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007827 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007828 /* wrong return value */
7829 PyErr_Format(PyExc_TypeError,
7830 "character mapping must return integer, bytes or None, not %.400s",
7831 x->ob_type->tp_name);
7832 Py_DECREF(x);
7833 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007834 }
7835}
7836
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007837static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007838charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007839{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007840 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7841 /* exponentially overallocate to minimize reallocations */
7842 if (requiredsize < 2*outsize)
7843 requiredsize = 2*outsize;
7844 if (_PyBytes_Resize(outobj, requiredsize))
7845 return -1;
7846 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007847}
7848
Benjamin Peterson14339b62009-01-31 16:36:08 +00007849typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007850 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007851} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007852/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007853 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007854 space is available. Return a new reference to the object that
7855 was put in the output buffer, or Py_None, if the mapping was undefined
7856 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007857 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007858static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01007859charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007860 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007861{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007862 PyObject *rep;
7863 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007864 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007865
Christian Heimes90aa7642007-12-19 02:45:37 +00007866 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007867 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007868 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007869 if (res == -1)
7870 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007871 if (outsize<requiredsize)
7872 if (charmapencode_resize(outobj, outpos, requiredsize))
7873 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007874 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007875 outstart[(*outpos)++] = (char)res;
7876 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007877 }
7878
7879 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007880 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007881 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007882 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007883 Py_DECREF(rep);
7884 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007885 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007886 if (PyLong_Check(rep)) {
7887 Py_ssize_t requiredsize = *outpos+1;
7888 if (outsize<requiredsize)
7889 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7890 Py_DECREF(rep);
7891 return enc_EXCEPTION;
7892 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007893 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007894 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007895 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007896 else {
7897 const char *repchars = PyBytes_AS_STRING(rep);
7898 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7899 Py_ssize_t requiredsize = *outpos+repsize;
7900 if (outsize<requiredsize)
7901 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7902 Py_DECREF(rep);
7903 return enc_EXCEPTION;
7904 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007905 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007906 memcpy(outstart + *outpos, repchars, repsize);
7907 *outpos += repsize;
7908 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007909 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007910 Py_DECREF(rep);
7911 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007912}
7913
7914/* handle an error in PyUnicode_EncodeCharmap
7915 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007916static int
7917charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007918 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007919 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007920 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007921 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007922{
7923 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007924 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007925 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007926 enum PyUnicode_Kind kind;
7927 void *data;
7928 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007929 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007930 Py_ssize_t collstartpos = *inpos;
7931 Py_ssize_t collendpos = *inpos+1;
7932 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007933 char *encoding = "charmap";
7934 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007935 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007936 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05007937 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007938
Benjamin Petersonbac79492012-01-14 13:34:47 -05007939 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007940 return -1;
7941 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007942 /* find all unencodable characters */
7943 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007944 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007945 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007946 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05007947 val = encoding_map_lookup(ch, mapping);
7948 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007949 break;
7950 ++collendpos;
7951 continue;
7952 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007953
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007954 ch = PyUnicode_READ_CHAR(unicode, collendpos);
7955 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007956 if (rep==NULL)
7957 return -1;
7958 else if (rep!=Py_None) {
7959 Py_DECREF(rep);
7960 break;
7961 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007962 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007963 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007964 }
7965 /* cache callback name lookup
7966 * (if not done yet, i.e. it's the first error) */
7967 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007968 if ((errors==NULL) || (!strcmp(errors, "strict")))
7969 *known_errorHandler = 1;
7970 else if (!strcmp(errors, "replace"))
7971 *known_errorHandler = 2;
7972 else if (!strcmp(errors, "ignore"))
7973 *known_errorHandler = 3;
7974 else if (!strcmp(errors, "xmlcharrefreplace"))
7975 *known_errorHandler = 4;
7976 else
7977 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007978 }
7979 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007980 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007981 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007982 return -1;
7983 case 2: /* replace */
7984 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007985 x = charmapencode_output('?', mapping, res, respos);
7986 if (x==enc_EXCEPTION) {
7987 return -1;
7988 }
7989 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007990 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00007991 return -1;
7992 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007993 }
7994 /* fall through */
7995 case 3: /* ignore */
7996 *inpos = collendpos;
7997 break;
7998 case 4: /* xmlcharrefreplace */
7999 /* generate replacement (temporarily (mis)uses p) */
8000 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008001 char buffer[2+29+1+1];
8002 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008003 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008004 for (cp = buffer; *cp; ++cp) {
8005 x = charmapencode_output(*cp, mapping, res, respos);
8006 if (x==enc_EXCEPTION)
8007 return -1;
8008 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008009 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008010 return -1;
8011 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008012 }
8013 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008014 *inpos = collendpos;
8015 break;
8016 default:
8017 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008018 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008019 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008020 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008021 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008022 if (PyBytes_Check(repunicode)) {
8023 /* Directly copy bytes result to output. */
8024 Py_ssize_t outsize = PyBytes_Size(*res);
8025 Py_ssize_t requiredsize;
8026 repsize = PyBytes_Size(repunicode);
8027 requiredsize = *respos + repsize;
8028 if (requiredsize > outsize)
8029 /* Make room for all additional bytes. */
8030 if (charmapencode_resize(res, respos, requiredsize)) {
8031 Py_DECREF(repunicode);
8032 return -1;
8033 }
8034 memcpy(PyBytes_AsString(*res) + *respos,
8035 PyBytes_AsString(repunicode), repsize);
8036 *respos += repsize;
8037 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008038 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008039 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008040 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008041 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008042 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008043 Py_DECREF(repunicode);
8044 return -1;
8045 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008046 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008047 data = PyUnicode_DATA(repunicode);
8048 kind = PyUnicode_KIND(repunicode);
8049 for (index = 0; index < repsize; index++) {
8050 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8051 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008052 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008053 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008054 return -1;
8055 }
8056 else if (x==enc_FAILED) {
8057 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008058 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008059 return -1;
8060 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008061 }
8062 *inpos = newpos;
8063 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008064 }
8065 return 0;
8066}
8067
Alexander Belopolsky40018472011-02-26 01:02:56 +00008068PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008069_PyUnicode_EncodeCharmap(PyObject *unicode,
8070 PyObject *mapping,
8071 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008072{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008073 /* output object */
8074 PyObject *res = NULL;
8075 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008076 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008077 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008078 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008079 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008080 PyObject *errorHandler = NULL;
8081 PyObject *exc = NULL;
8082 /* the following variable is used for caching string comparisons
8083 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8084 * 3=ignore, 4=xmlcharrefreplace */
8085 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008086
Benjamin Petersonbac79492012-01-14 13:34:47 -05008087 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008088 return NULL;
8089 size = PyUnicode_GET_LENGTH(unicode);
8090
Guido van Rossumd57fd912000-03-10 22:53:23 +00008091 /* Default to Latin-1 */
8092 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008093 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008094
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008095 /* allocate enough for a simple encoding without
8096 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008097 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008098 if (res == NULL)
8099 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008100 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008101 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008102
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008103 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008104 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008105 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008106 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008107 if (x==enc_EXCEPTION) /* error */
8108 goto onError;
8109 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008110 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008111 &exc,
8112 &known_errorHandler, &errorHandler, errors,
8113 &res, &respos)) {
8114 goto onError;
8115 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008116 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008117 else
8118 /* done with this character => adjust input position */
8119 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008120 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008121
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008122 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008123 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008124 if (_PyBytes_Resize(&res, respos) < 0)
8125 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008126
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008127 Py_XDECREF(exc);
8128 Py_XDECREF(errorHandler);
8129 return res;
8130
Benjamin Peterson29060642009-01-31 22:14:21 +00008131 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008132 Py_XDECREF(res);
8133 Py_XDECREF(exc);
8134 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008135 return NULL;
8136}
8137
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008138/* Deprecated */
8139PyObject *
8140PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8141 Py_ssize_t size,
8142 PyObject *mapping,
8143 const char *errors)
8144{
8145 PyObject *result;
8146 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8147 if (unicode == NULL)
8148 return NULL;
8149 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8150 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008151 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008152}
8153
Alexander Belopolsky40018472011-02-26 01:02:56 +00008154PyObject *
8155PyUnicode_AsCharmapString(PyObject *unicode,
8156 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008157{
8158 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008159 PyErr_BadArgument();
8160 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008161 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008162 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008163}
8164
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008165/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008166static void
8167make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008168 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008169 Py_ssize_t startpos, Py_ssize_t endpos,
8170 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008171{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008172 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008173 *exceptionObject = _PyUnicodeTranslateError_Create(
8174 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008175 }
8176 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008177 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8178 goto onError;
8179 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8180 goto onError;
8181 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8182 goto onError;
8183 return;
8184 onError:
8185 Py_DECREF(*exceptionObject);
8186 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008187 }
8188}
8189
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008190/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008191static void
8192raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008193 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008194 Py_ssize_t startpos, Py_ssize_t endpos,
8195 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008196{
8197 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008198 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008199 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008200 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008201}
8202
8203/* error handling callback helper:
8204 build arguments, call the callback and check the arguments,
8205 put the result into newpos and return the replacement string, which
8206 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008207static PyObject *
8208unicode_translate_call_errorhandler(const char *errors,
8209 PyObject **errorHandler,
8210 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008211 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008212 Py_ssize_t startpos, Py_ssize_t endpos,
8213 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008214{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008215 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008216
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008217 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008218 PyObject *restuple;
8219 PyObject *resunicode;
8220
8221 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008222 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008223 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008224 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008225 }
8226
8227 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008228 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008229 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008230 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008231
8232 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008233 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008234 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008235 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008236 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008237 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008238 Py_DECREF(restuple);
8239 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008240 }
8241 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008242 &resunicode, &i_newpos)) {
8243 Py_DECREF(restuple);
8244 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008245 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008246 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008247 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008248 else
8249 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008250 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008251 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8252 Py_DECREF(restuple);
8253 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008254 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008255 Py_INCREF(resunicode);
8256 Py_DECREF(restuple);
8257 return resunicode;
8258}
8259
8260/* Lookup the character ch in the mapping and put the result in result,
8261 which must be decrefed by the caller.
8262 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008263static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008264charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008265{
Christian Heimes217cfd12007-12-02 14:31:20 +00008266 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008267 PyObject *x;
8268
8269 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008270 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008271 x = PyObject_GetItem(mapping, w);
8272 Py_DECREF(w);
8273 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008274 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8275 /* No mapping found means: use 1:1 mapping. */
8276 PyErr_Clear();
8277 *result = NULL;
8278 return 0;
8279 } else
8280 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008281 }
8282 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008283 *result = x;
8284 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008285 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008286 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008287 long value = PyLong_AS_LONG(x);
8288 long max = PyUnicode_GetMax();
8289 if (value < 0 || value > max) {
8290 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008291 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008292 Py_DECREF(x);
8293 return -1;
8294 }
8295 *result = x;
8296 return 0;
8297 }
8298 else if (PyUnicode_Check(x)) {
8299 *result = x;
8300 return 0;
8301 }
8302 else {
8303 /* wrong return value */
8304 PyErr_SetString(PyExc_TypeError,
8305 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008306 Py_DECREF(x);
8307 return -1;
8308 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008309}
8310/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008311 if not reallocate and adjust various state variables.
8312 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008313static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008314charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008315 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008316{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008317 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008318 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008319 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008320 /* exponentially overallocate to minimize reallocations */
8321 if (requiredsize < 2 * oldsize)
8322 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008323 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8324 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008325 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008326 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008327 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008328 }
8329 return 0;
8330}
8331/* lookup the character, put the result in the output string and adjust
8332 various state variables. Return a new reference to the object that
8333 was put in the output buffer in *result, or Py_None, if the mapping was
8334 undefined (in which case no character was written).
8335 The called must decref result.
8336 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008337static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008338charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8339 PyObject *mapping, Py_UCS4 **output,
8340 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008341 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008342{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008343 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8344 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008345 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008346 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008347 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008348 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008349 }
8350 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008351 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008352 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008353 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008354 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008355 }
8356 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008357 Py_ssize_t repsize;
8358 if (PyUnicode_READY(*res) == -1)
8359 return -1;
8360 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008361 if (repsize==1) {
8362 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008363 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008364 }
8365 else if (repsize!=0) {
8366 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008367 Py_ssize_t requiredsize = *opos +
8368 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008369 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008370 Py_ssize_t i;
8371 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008372 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008373 for(i = 0; i < repsize; i++)
8374 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008375 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008376 }
8377 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008378 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008379 return 0;
8380}
8381
Alexander Belopolsky40018472011-02-26 01:02:56 +00008382PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008383_PyUnicode_TranslateCharmap(PyObject *input,
8384 PyObject *mapping,
8385 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008386{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008387 /* input object */
8388 char *idata;
8389 Py_ssize_t size, i;
8390 int kind;
8391 /* output buffer */
8392 Py_UCS4 *output = NULL;
8393 Py_ssize_t osize;
8394 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008395 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008396 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008397 char *reason = "character maps to <undefined>";
8398 PyObject *errorHandler = NULL;
8399 PyObject *exc = NULL;
8400 /* the following variable is used for caching string comparisons
8401 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8402 * 3=ignore, 4=xmlcharrefreplace */
8403 int known_errorHandler = -1;
8404
Guido van Rossumd57fd912000-03-10 22:53:23 +00008405 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008406 PyErr_BadArgument();
8407 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008408 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008409
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008410 if (PyUnicode_READY(input) == -1)
8411 return NULL;
8412 idata = (char*)PyUnicode_DATA(input);
8413 kind = PyUnicode_KIND(input);
8414 size = PyUnicode_GET_LENGTH(input);
8415 i = 0;
8416
8417 if (size == 0) {
8418 Py_INCREF(input);
8419 return input;
8420 }
8421
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008422 /* allocate enough for a simple 1:1 translation without
8423 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008424 osize = size;
8425 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8426 opos = 0;
8427 if (output == NULL) {
8428 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008429 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008430 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008431
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008432 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008433 /* try to encode it */
8434 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008435 if (charmaptranslate_output(input, i, mapping,
8436 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 Py_XDECREF(x);
8438 goto onError;
8439 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008440 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008441 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008442 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008443 else { /* untranslatable character */
8444 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8445 Py_ssize_t repsize;
8446 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008447 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008448 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008449 Py_ssize_t collstart = i;
8450 Py_ssize_t collend = i+1;
8451 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008452
Benjamin Peterson29060642009-01-31 22:14:21 +00008453 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008454 while (collend < size) {
8455 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008456 goto onError;
8457 Py_XDECREF(x);
8458 if (x!=Py_None)
8459 break;
8460 ++collend;
8461 }
8462 /* cache callback name lookup
8463 * (if not done yet, i.e. it's the first error) */
8464 if (known_errorHandler==-1) {
8465 if ((errors==NULL) || (!strcmp(errors, "strict")))
8466 known_errorHandler = 1;
8467 else if (!strcmp(errors, "replace"))
8468 known_errorHandler = 2;
8469 else if (!strcmp(errors, "ignore"))
8470 known_errorHandler = 3;
8471 else if (!strcmp(errors, "xmlcharrefreplace"))
8472 known_errorHandler = 4;
8473 else
8474 known_errorHandler = 0;
8475 }
8476 switch (known_errorHandler) {
8477 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008478 raise_translate_exception(&exc, input, collstart,
8479 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008480 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008481 case 2: /* replace */
8482 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008483 for (coll = collstart; coll<collend; coll++)
8484 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008485 /* fall through */
8486 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008487 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008488 break;
8489 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008490 /* generate replacement (temporarily (mis)uses i) */
8491 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008492 char buffer[2+29+1+1];
8493 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008494 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8495 if (charmaptranslate_makespace(&output, &osize,
8496 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008497 goto onError;
8498 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008499 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008500 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008501 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 break;
8503 default:
8504 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008505 reason, input, &exc,
8506 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008507 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008508 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008509 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008510 Py_DECREF(repunicode);
8511 goto onError;
8512 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008513 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008514 repsize = PyUnicode_GET_LENGTH(repunicode);
8515 if (charmaptranslate_makespace(&output, &osize,
8516 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008517 Py_DECREF(repunicode);
8518 goto onError;
8519 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008520 for (uni2 = 0; repsize-->0; ++uni2)
8521 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8522 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008523 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008524 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008525 }
8526 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008527 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8528 if (!res)
8529 goto onError;
8530 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008531 Py_XDECREF(exc);
8532 Py_XDECREF(errorHandler);
8533 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008534
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008536 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008537 Py_XDECREF(exc);
8538 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008539 return NULL;
8540}
8541
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008542/* Deprecated. Use PyUnicode_Translate instead. */
8543PyObject *
8544PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8545 Py_ssize_t size,
8546 PyObject *mapping,
8547 const char *errors)
8548{
8549 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8550 if (!unicode)
8551 return NULL;
8552 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8553}
8554
Alexander Belopolsky40018472011-02-26 01:02:56 +00008555PyObject *
8556PyUnicode_Translate(PyObject *str,
8557 PyObject *mapping,
8558 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008559{
8560 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008561
Guido van Rossumd57fd912000-03-10 22:53:23 +00008562 str = PyUnicode_FromObject(str);
8563 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008564 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008565 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008566 Py_DECREF(str);
8567 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008568
Benjamin Peterson29060642009-01-31 22:14:21 +00008569 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008570 Py_XDECREF(str);
8571 return NULL;
8572}
Tim Petersced69f82003-09-16 20:30:58 +00008573
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008574static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008575fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008576{
8577 /* No need to call PyUnicode_READY(self) because this function is only
8578 called as a callback from fixup() which does it already. */
8579 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8580 const int kind = PyUnicode_KIND(self);
8581 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008582 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008583 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008584 Py_ssize_t i;
8585
8586 for (i = 0; i < len; ++i) {
8587 ch = PyUnicode_READ(kind, data, i);
8588 fixed = 0;
8589 if (ch > 127) {
8590 if (Py_UNICODE_ISSPACE(ch))
8591 fixed = ' ';
8592 else {
8593 const int decimal = Py_UNICODE_TODECIMAL(ch);
8594 if (decimal >= 0)
8595 fixed = '0' + decimal;
8596 }
8597 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008598 modified = 1;
Victor Stinnere6abb482012-05-02 01:15:40 +02008599 maxchar = MAX_MAXCHAR(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008600 PyUnicode_WRITE(kind, data, i, fixed);
8601 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008602 else
8603 maxchar = MAX_MAXCHAR(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008604 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008605 }
8606
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008607 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008608}
8609
8610PyObject *
8611_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8612{
8613 if (!PyUnicode_Check(unicode)) {
8614 PyErr_BadInternalCall();
8615 return NULL;
8616 }
8617 if (PyUnicode_READY(unicode) == -1)
8618 return NULL;
8619 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8620 /* If the string is already ASCII, just return the same string */
8621 Py_INCREF(unicode);
8622 return unicode;
8623 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008624 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008625}
8626
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008627PyObject *
8628PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8629 Py_ssize_t length)
8630{
Victor Stinnerf0124502011-11-21 23:12:56 +01008631 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008632 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008633 Py_UCS4 maxchar;
8634 enum PyUnicode_Kind kind;
8635 void *data;
8636
Victor Stinner99d7ad02012-02-22 13:37:39 +01008637 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008638 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008639 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008640 if (ch > 127) {
8641 int decimal = Py_UNICODE_TODECIMAL(ch);
8642 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008643 ch = '0' + decimal;
Victor Stinnere6abb482012-05-02 01:15:40 +02008644 maxchar = MAX_MAXCHAR(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008645 }
8646 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008647
8648 /* Copy to a new string */
8649 decimal = PyUnicode_New(length, maxchar);
8650 if (decimal == NULL)
8651 return decimal;
8652 kind = PyUnicode_KIND(decimal);
8653 data = PyUnicode_DATA(decimal);
8654 /* Iterate over code points */
8655 for (i = 0; i < length; i++) {
8656 Py_UNICODE ch = s[i];
8657 if (ch > 127) {
8658 int decimal = Py_UNICODE_TODECIMAL(ch);
8659 if (decimal >= 0)
8660 ch = '0' + decimal;
8661 }
8662 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008663 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008664 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008665}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008666/* --- Decimal Encoder ---------------------------------------------------- */
8667
Alexander Belopolsky40018472011-02-26 01:02:56 +00008668int
8669PyUnicode_EncodeDecimal(Py_UNICODE *s,
8670 Py_ssize_t length,
8671 char *output,
8672 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008673{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008674 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008675 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008676 enum PyUnicode_Kind kind;
8677 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008678
8679 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008680 PyErr_BadArgument();
8681 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008682 }
8683
Victor Stinner42bf7752011-11-21 22:52:58 +01008684 unicode = PyUnicode_FromUnicode(s, length);
8685 if (unicode == NULL)
8686 return -1;
8687
Benjamin Petersonbac79492012-01-14 13:34:47 -05008688 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008689 Py_DECREF(unicode);
8690 return -1;
8691 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008692 kind = PyUnicode_KIND(unicode);
8693 data = PyUnicode_DATA(unicode);
8694
Victor Stinnerb84d7232011-11-22 01:50:07 +01008695 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008696 PyObject *exc;
8697 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008698 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008699 Py_ssize_t startpos;
8700
8701 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008702
Benjamin Peterson29060642009-01-31 22:14:21 +00008703 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008704 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008705 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008706 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008707 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008708 decimal = Py_UNICODE_TODECIMAL(ch);
8709 if (decimal >= 0) {
8710 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008711 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008712 continue;
8713 }
8714 if (0 < ch && ch < 256) {
8715 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008716 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008717 continue;
8718 }
Victor Stinner6345be92011-11-25 20:09:01 +01008719
Victor Stinner42bf7752011-11-21 22:52:58 +01008720 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008721 exc = NULL;
8722 raise_encode_exception(&exc, "decimal", unicode,
8723 startpos, startpos+1,
8724 "invalid decimal Unicode string");
8725 Py_XDECREF(exc);
8726 Py_DECREF(unicode);
8727 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008728 }
8729 /* 0-terminate the output string */
8730 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008731 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008732 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008733}
8734
Guido van Rossumd57fd912000-03-10 22:53:23 +00008735/* --- Helpers ------------------------------------------------------------ */
8736
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008737static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008738any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008739 Py_ssize_t start,
8740 Py_ssize_t end)
8741{
8742 int kind1, kind2, kind;
8743 void *buf1, *buf2;
8744 Py_ssize_t len1, len2, result;
8745
8746 kind1 = PyUnicode_KIND(s1);
8747 kind2 = PyUnicode_KIND(s2);
8748 kind = kind1 > kind2 ? kind1 : kind2;
8749 buf1 = PyUnicode_DATA(s1);
8750 buf2 = PyUnicode_DATA(s2);
8751 if (kind1 != kind)
8752 buf1 = _PyUnicode_AsKind(s1, kind);
8753 if (!buf1)
8754 return -2;
8755 if (kind2 != kind)
8756 buf2 = _PyUnicode_AsKind(s2, kind);
8757 if (!buf2) {
8758 if (kind1 != kind) PyMem_Free(buf1);
8759 return -2;
8760 }
8761 len1 = PyUnicode_GET_LENGTH(s1);
8762 len2 = PyUnicode_GET_LENGTH(s2);
8763
Victor Stinner794d5672011-10-10 03:21:36 +02008764 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008765 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008766 case PyUnicode_1BYTE_KIND:
8767 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8768 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8769 else
8770 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8771 break;
8772 case PyUnicode_2BYTE_KIND:
8773 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8774 break;
8775 case PyUnicode_4BYTE_KIND:
8776 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8777 break;
8778 default:
8779 assert(0); result = -2;
8780 }
8781 }
8782 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008783 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008784 case PyUnicode_1BYTE_KIND:
8785 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8786 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8787 else
8788 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8789 break;
8790 case PyUnicode_2BYTE_KIND:
8791 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8792 break;
8793 case PyUnicode_4BYTE_KIND:
8794 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8795 break;
8796 default:
8797 assert(0); result = -2;
8798 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008799 }
8800
8801 if (kind1 != kind)
8802 PyMem_Free(buf1);
8803 if (kind2 != kind)
8804 PyMem_Free(buf2);
8805
8806 return result;
8807}
8808
8809Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01008810_PyUnicode_InsertThousandsGrouping(
8811 PyObject *unicode, Py_ssize_t index,
8812 Py_ssize_t n_buffer,
8813 void *digits, Py_ssize_t n_digits,
8814 Py_ssize_t min_width,
8815 const char *grouping, PyObject *thousands_sep,
8816 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008817{
Victor Stinner41a863c2012-02-24 00:37:51 +01008818 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008819 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01008820 Py_ssize_t thousands_sep_len;
8821 Py_ssize_t len;
8822
8823 if (unicode != NULL) {
8824 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008825 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01008826 }
8827 else {
8828 kind = PyUnicode_1BYTE_KIND;
8829 data = NULL;
8830 }
8831 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
8832 thousands_sep_data = PyUnicode_DATA(thousands_sep);
8833 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
8834 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01008835 if (thousands_sep_kind < kind) {
8836 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
8837 if (!thousands_sep_data)
8838 return -1;
8839 }
8840 else {
8841 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
8842 if (!data)
8843 return -1;
8844 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008845 }
8846
Benjamin Petersonead6b532011-12-20 17:23:42 -06008847 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008848 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008849 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01008850 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008851 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008852 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008853 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02008854 else
Victor Stinner41a863c2012-02-24 00:37:51 +01008855 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008856 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008857 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008858 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008859 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008860 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008861 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008862 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008863 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008864 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008865 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008866 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008867 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008868 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008869 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008870 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008871 break;
8872 default:
8873 assert(0);
8874 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008875 }
Victor Stinner90f50d42012-02-24 01:44:47 +01008876 if (unicode != NULL && thousands_sep_kind != kind) {
8877 if (thousands_sep_kind < kind)
8878 PyMem_Free(thousands_sep_data);
8879 else
8880 PyMem_Free(data);
8881 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008882 if (unicode == NULL) {
8883 *maxchar = 127;
8884 if (len != n_digits) {
Victor Stinnere6abb482012-05-02 01:15:40 +02008885 *maxchar = MAX_MAXCHAR(*maxchar,
8886 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01008887 }
8888 }
8889 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008890}
8891
8892
Thomas Wouters477c8d52006-05-27 19:21:47 +00008893/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008894#define ADJUST_INDICES(start, end, len) \
8895 if (end > len) \
8896 end = len; \
8897 else if (end < 0) { \
8898 end += len; \
8899 if (end < 0) \
8900 end = 0; \
8901 } \
8902 if (start < 0) { \
8903 start += len; \
8904 if (start < 0) \
8905 start = 0; \
8906 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008907
Alexander Belopolsky40018472011-02-26 01:02:56 +00008908Py_ssize_t
8909PyUnicode_Count(PyObject *str,
8910 PyObject *substr,
8911 Py_ssize_t start,
8912 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008913{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008914 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008915 PyObject* str_obj;
8916 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008917 int kind1, kind2, kind;
8918 void *buf1 = NULL, *buf2 = NULL;
8919 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008920
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008921 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008922 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008923 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008924 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008925 if (!sub_obj) {
8926 Py_DECREF(str_obj);
8927 return -1;
8928 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06008929 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06008930 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008931 Py_DECREF(str_obj);
8932 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008933 }
Tim Petersced69f82003-09-16 20:30:58 +00008934
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008935 kind1 = PyUnicode_KIND(str_obj);
8936 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008937 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008938 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008939 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008940 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02008941 if (kind2 > kind) {
8942 Py_DECREF(sub_obj);
8943 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008944 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02008945 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01008946 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008947 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008948 if (!buf2)
8949 goto onError;
8950 len1 = PyUnicode_GET_LENGTH(str_obj);
8951 len2 = PyUnicode_GET_LENGTH(sub_obj);
8952
8953 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06008954 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008955 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008956 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8957 result = asciilib_count(
8958 ((Py_UCS1*)buf1) + start, end - start,
8959 buf2, len2, PY_SSIZE_T_MAX
8960 );
8961 else
8962 result = ucs1lib_count(
8963 ((Py_UCS1*)buf1) + start, end - start,
8964 buf2, len2, PY_SSIZE_T_MAX
8965 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008966 break;
8967 case PyUnicode_2BYTE_KIND:
8968 result = ucs2lib_count(
8969 ((Py_UCS2*)buf1) + start, end - start,
8970 buf2, len2, PY_SSIZE_T_MAX
8971 );
8972 break;
8973 case PyUnicode_4BYTE_KIND:
8974 result = ucs4lib_count(
8975 ((Py_UCS4*)buf1) + start, end - start,
8976 buf2, len2, PY_SSIZE_T_MAX
8977 );
8978 break;
8979 default:
8980 assert(0); result = 0;
8981 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008982
8983 Py_DECREF(sub_obj);
8984 Py_DECREF(str_obj);
8985
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008986 if (kind2 != kind)
8987 PyMem_Free(buf2);
8988
Guido van Rossumd57fd912000-03-10 22:53:23 +00008989 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008990 onError:
8991 Py_DECREF(sub_obj);
8992 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008993 if (kind2 != kind && buf2)
8994 PyMem_Free(buf2);
8995 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008996}
8997
Alexander Belopolsky40018472011-02-26 01:02:56 +00008998Py_ssize_t
8999PyUnicode_Find(PyObject *str,
9000 PyObject *sub,
9001 Py_ssize_t start,
9002 Py_ssize_t end,
9003 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009004{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009005 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009006
Guido van Rossumd57fd912000-03-10 22:53:23 +00009007 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009008 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009009 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009010 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009011 if (!sub) {
9012 Py_DECREF(str);
9013 return -2;
9014 }
9015 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9016 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009017 Py_DECREF(str);
9018 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009019 }
Tim Petersced69f82003-09-16 20:30:58 +00009020
Victor Stinner794d5672011-10-10 03:21:36 +02009021 result = any_find_slice(direction,
9022 str, sub, start, end
9023 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009024
Guido van Rossumd57fd912000-03-10 22:53:23 +00009025 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009026 Py_DECREF(sub);
9027
Guido van Rossumd57fd912000-03-10 22:53:23 +00009028 return result;
9029}
9030
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009031Py_ssize_t
9032PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9033 Py_ssize_t start, Py_ssize_t end,
9034 int direction)
9035{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009036 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009037 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009038 if (PyUnicode_READY(str) == -1)
9039 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009040 if (start < 0 || end < 0) {
9041 PyErr_SetString(PyExc_IndexError, "string index out of range");
9042 return -2;
9043 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009044 if (end > PyUnicode_GET_LENGTH(str))
9045 end = PyUnicode_GET_LENGTH(str);
9046 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009047 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9048 kind, end-start, ch, direction);
9049 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009050 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009051 else
9052 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009053}
9054
Alexander Belopolsky40018472011-02-26 01:02:56 +00009055static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009056tailmatch(PyObject *self,
9057 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009058 Py_ssize_t start,
9059 Py_ssize_t end,
9060 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009061{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009062 int kind_self;
9063 int kind_sub;
9064 void *data_self;
9065 void *data_sub;
9066 Py_ssize_t offset;
9067 Py_ssize_t i;
9068 Py_ssize_t end_sub;
9069
9070 if (PyUnicode_READY(self) == -1 ||
9071 PyUnicode_READY(substring) == -1)
9072 return 0;
9073
9074 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009075 return 1;
9076
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009077 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9078 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009079 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009080 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009081
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009082 kind_self = PyUnicode_KIND(self);
9083 data_self = PyUnicode_DATA(self);
9084 kind_sub = PyUnicode_KIND(substring);
9085 data_sub = PyUnicode_DATA(substring);
9086 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9087
9088 if (direction > 0)
9089 offset = end;
9090 else
9091 offset = start;
9092
9093 if (PyUnicode_READ(kind_self, data_self, offset) ==
9094 PyUnicode_READ(kind_sub, data_sub, 0) &&
9095 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9096 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9097 /* If both are of the same kind, memcmp is sufficient */
9098 if (kind_self == kind_sub) {
9099 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009100 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009101 data_sub,
9102 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009103 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009104 }
9105 /* otherwise we have to compare each character by first accesing it */
9106 else {
9107 /* We do not need to compare 0 and len(substring)-1 because
9108 the if statement above ensured already that they are equal
9109 when we end up here. */
9110 // TODO: honor direction and do a forward or backwards search
9111 for (i = 1; i < end_sub; ++i) {
9112 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9113 PyUnicode_READ(kind_sub, data_sub, i))
9114 return 0;
9115 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009116 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009117 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009118 }
9119
9120 return 0;
9121}
9122
Alexander Belopolsky40018472011-02-26 01:02:56 +00009123Py_ssize_t
9124PyUnicode_Tailmatch(PyObject *str,
9125 PyObject *substr,
9126 Py_ssize_t start,
9127 Py_ssize_t end,
9128 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009129{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009130 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009131
Guido van Rossumd57fd912000-03-10 22:53:23 +00009132 str = PyUnicode_FromObject(str);
9133 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009134 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009135 substr = PyUnicode_FromObject(substr);
9136 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009137 Py_DECREF(str);
9138 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009139 }
Tim Petersced69f82003-09-16 20:30:58 +00009140
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009141 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009142 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009143 Py_DECREF(str);
9144 Py_DECREF(substr);
9145 return result;
9146}
9147
Guido van Rossumd57fd912000-03-10 22:53:23 +00009148/* Apply fixfct filter to the Unicode object self and return a
9149 reference to the modified object */
9150
Alexander Belopolsky40018472011-02-26 01:02:56 +00009151static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009152fixup(PyObject *self,
9153 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009154{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009155 PyObject *u;
9156 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009157 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009158
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009159 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009160 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009161 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009162 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009163
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009164 /* fix functions return the new maximum character in a string,
9165 if the kind of the resulting unicode object does not change,
9166 everything is fine. Otherwise we need to change the string kind
9167 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009168 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009169
9170 if (maxchar_new == 0) {
9171 /* no changes */;
9172 if (PyUnicode_CheckExact(self)) {
9173 Py_DECREF(u);
9174 Py_INCREF(self);
9175 return self;
9176 }
9177 else
9178 return u;
9179 }
9180
Victor Stinnere6abb482012-05-02 01:15:40 +02009181 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009182
Victor Stinnereaab6042011-12-11 22:22:39 +01009183 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009184 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009185
9186 /* In case the maximum character changed, we need to
9187 convert the string to the new category. */
9188 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9189 if (v == NULL) {
9190 Py_DECREF(u);
9191 return NULL;
9192 }
9193 if (maxchar_new > maxchar_old) {
9194 /* If the maxchar increased so that the kind changed, not all
9195 characters are representable anymore and we need to fix the
9196 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009197 _PyUnicode_FastCopyCharacters(v, 0,
9198 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009199 maxchar_old = fixfct(v);
9200 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009201 }
9202 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009203 _PyUnicode_FastCopyCharacters(v, 0,
9204 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009205 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009206 Py_DECREF(u);
9207 assert(_PyUnicode_CheckConsistency(v, 1));
9208 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009209}
9210
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009211static PyObject *
9212ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009213{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009214 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9215 char *resdata, *data = PyUnicode_DATA(self);
9216 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009217
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009218 res = PyUnicode_New(len, 127);
9219 if (res == NULL)
9220 return NULL;
9221 resdata = PyUnicode_DATA(res);
9222 if (lower)
9223 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009224 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009225 _Py_bytes_upper(resdata, data, len);
9226 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009227}
9228
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009229static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009230handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009231{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009232 Py_ssize_t j;
9233 int final_sigma;
9234 Py_UCS4 c;
9235 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009236
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009237 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9238
9239 where ! is a negation and \p{xxx} is a character with property xxx.
9240 */
9241 for (j = i - 1; j >= 0; j--) {
9242 c = PyUnicode_READ(kind, data, j);
9243 if (!_PyUnicode_IsCaseIgnorable(c))
9244 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009245 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009246 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9247 if (final_sigma) {
9248 for (j = i + 1; j < length; j++) {
9249 c = PyUnicode_READ(kind, data, j);
9250 if (!_PyUnicode_IsCaseIgnorable(c))
9251 break;
9252 }
9253 final_sigma = j == length || !_PyUnicode_IsCased(c);
9254 }
9255 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009256}
9257
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009258static int
9259lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9260 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009261{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009262 /* Obscure special case. */
9263 if (c == 0x3A3) {
9264 mapped[0] = handle_capital_sigma(kind, data, length, i);
9265 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009266 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009267 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009268}
9269
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009270static Py_ssize_t
9271do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009272{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009273 Py_ssize_t i, k = 0;
9274 int n_res, j;
9275 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009276
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009277 c = PyUnicode_READ(kind, data, 0);
9278 n_res = _PyUnicode_ToUpperFull(c, mapped);
9279 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009280 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009281 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009282 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009283 for (i = 1; i < length; i++) {
9284 c = PyUnicode_READ(kind, data, i);
9285 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9286 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009287 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009288 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009289 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009290 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009291 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009292}
9293
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009294static Py_ssize_t
9295do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9296 Py_ssize_t i, k = 0;
9297
9298 for (i = 0; i < length; i++) {
9299 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9300 int n_res, j;
9301 if (Py_UNICODE_ISUPPER(c)) {
9302 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9303 }
9304 else if (Py_UNICODE_ISLOWER(c)) {
9305 n_res = _PyUnicode_ToUpperFull(c, mapped);
9306 }
9307 else {
9308 n_res = 1;
9309 mapped[0] = c;
9310 }
9311 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009312 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009313 res[k++] = mapped[j];
9314 }
9315 }
9316 return k;
9317}
9318
9319static Py_ssize_t
9320do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9321 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009322{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009323 Py_ssize_t i, k = 0;
9324
9325 for (i = 0; i < length; i++) {
9326 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9327 int n_res, j;
9328 if (lower)
9329 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9330 else
9331 n_res = _PyUnicode_ToUpperFull(c, mapped);
9332 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009333 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009334 res[k++] = mapped[j];
9335 }
9336 }
9337 return k;
9338}
9339
9340static Py_ssize_t
9341do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9342{
9343 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9344}
9345
9346static Py_ssize_t
9347do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9348{
9349 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9350}
9351
Benjamin Petersone51757f2012-01-12 21:10:29 -05009352static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009353do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9354{
9355 Py_ssize_t i, k = 0;
9356
9357 for (i = 0; i < length; i++) {
9358 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9359 Py_UCS4 mapped[3];
9360 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9361 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009362 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009363 res[k++] = mapped[j];
9364 }
9365 }
9366 return k;
9367}
9368
9369static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009370do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9371{
9372 Py_ssize_t i, k = 0;
9373 int previous_is_cased;
9374
9375 previous_is_cased = 0;
9376 for (i = 0; i < length; i++) {
9377 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9378 Py_UCS4 mapped[3];
9379 int n_res, j;
9380
9381 if (previous_is_cased)
9382 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9383 else
9384 n_res = _PyUnicode_ToTitleFull(c, mapped);
9385
9386 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009387 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009388 res[k++] = mapped[j];
9389 }
9390
9391 previous_is_cased = _PyUnicode_IsCased(c);
9392 }
9393 return k;
9394}
9395
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009396static PyObject *
9397case_operation(PyObject *self,
9398 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9399{
9400 PyObject *res = NULL;
9401 Py_ssize_t length, newlength = 0;
9402 int kind, outkind;
9403 void *data, *outdata;
9404 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9405
Benjamin Petersoneea48462012-01-16 14:28:50 -05009406 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009407
9408 kind = PyUnicode_KIND(self);
9409 data = PyUnicode_DATA(self);
9410 length = PyUnicode_GET_LENGTH(self);
9411 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9412 if (tmp == NULL)
9413 return PyErr_NoMemory();
9414 newlength = perform(kind, data, length, tmp, &maxchar);
9415 res = PyUnicode_New(newlength, maxchar);
9416 if (res == NULL)
9417 goto leave;
9418 tmpend = tmp + newlength;
9419 outdata = PyUnicode_DATA(res);
9420 outkind = PyUnicode_KIND(res);
9421 switch (outkind) {
9422 case PyUnicode_1BYTE_KIND:
9423 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9424 break;
9425 case PyUnicode_2BYTE_KIND:
9426 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9427 break;
9428 case PyUnicode_4BYTE_KIND:
9429 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9430 break;
9431 default:
9432 assert(0);
9433 break;
9434 }
9435 leave:
9436 PyMem_FREE(tmp);
9437 return res;
9438}
9439
Tim Peters8ce9f162004-08-27 01:49:32 +00009440PyObject *
9441PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009442{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009443 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009444 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009445 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009446 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009447 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9448 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009449 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009450 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009451 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009452 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009453 int use_memcpy;
9454 unsigned char *res_data = NULL, *sep_data = NULL;
9455 PyObject *last_obj;
9456 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009457
Tim Peters05eba1f2004-08-27 21:32:02 +00009458 fseq = PySequence_Fast(seq, "");
9459 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009460 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009461 }
9462
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009463 /* NOTE: the following code can't call back into Python code,
9464 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009465 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009466
Tim Peters05eba1f2004-08-27 21:32:02 +00009467 seqlen = PySequence_Fast_GET_SIZE(fseq);
9468 /* If empty sequence, return u"". */
9469 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009470 Py_DECREF(fseq);
9471 Py_INCREF(unicode_empty);
9472 res = unicode_empty;
9473 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009474 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009475
Tim Peters05eba1f2004-08-27 21:32:02 +00009476 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009477 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009478 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009479 if (seqlen == 1) {
9480 if (PyUnicode_CheckExact(items[0])) {
9481 res = items[0];
9482 Py_INCREF(res);
9483 Py_DECREF(fseq);
9484 return res;
9485 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009486 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009487 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009488 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009489 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009490 /* Set up sep and seplen */
9491 if (separator == NULL) {
9492 /* fall back to a blank space separator */
9493 sep = PyUnicode_FromOrdinal(' ');
9494 if (!sep)
9495 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009496 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009497 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009498 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009499 else {
9500 if (!PyUnicode_Check(separator)) {
9501 PyErr_Format(PyExc_TypeError,
9502 "separator: expected str instance,"
9503 " %.80s found",
9504 Py_TYPE(separator)->tp_name);
9505 goto onError;
9506 }
9507 if (PyUnicode_READY(separator))
9508 goto onError;
9509 sep = separator;
9510 seplen = PyUnicode_GET_LENGTH(separator);
9511 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9512 /* inc refcount to keep this code path symmetric with the
9513 above case of a blank separator */
9514 Py_INCREF(sep);
9515 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009516 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009517 }
9518
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009519 /* There are at least two things to join, or else we have a subclass
9520 * of str in the sequence.
9521 * Do a pre-pass to figure out the total amount of space we'll
9522 * need (sz), and see whether all argument are strings.
9523 */
9524 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009525#ifdef Py_DEBUG
9526 use_memcpy = 0;
9527#else
9528 use_memcpy = 1;
9529#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009530 for (i = 0; i < seqlen; i++) {
9531 const Py_ssize_t old_sz = sz;
9532 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009533 if (!PyUnicode_Check(item)) {
9534 PyErr_Format(PyExc_TypeError,
9535 "sequence item %zd: expected str instance,"
9536 " %.80s found",
9537 i, Py_TYPE(item)->tp_name);
9538 goto onError;
9539 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009540 if (PyUnicode_READY(item) == -1)
9541 goto onError;
9542 sz += PyUnicode_GET_LENGTH(item);
9543 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnere6abb482012-05-02 01:15:40 +02009544 maxchar = MAX_MAXCHAR(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009545 if (i != 0)
9546 sz += seplen;
9547 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9548 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009549 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009550 goto onError;
9551 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009552 if (use_memcpy && last_obj != NULL) {
9553 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9554 use_memcpy = 0;
9555 }
9556 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009557 }
Tim Petersced69f82003-09-16 20:30:58 +00009558
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009559 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009560 if (res == NULL)
9561 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009562
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009563 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009564#ifdef Py_DEBUG
9565 use_memcpy = 0;
9566#else
9567 if (use_memcpy) {
9568 res_data = PyUnicode_1BYTE_DATA(res);
9569 kind = PyUnicode_KIND(res);
9570 if (seplen != 0)
9571 sep_data = PyUnicode_1BYTE_DATA(sep);
9572 }
9573#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009574 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009575 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009576 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009577 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009578 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009579 if (use_memcpy) {
9580 Py_MEMCPY(res_data,
9581 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009582 kind * seplen);
9583 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009584 }
9585 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009586 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009587 res_offset += seplen;
9588 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009589 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009590 itemlen = PyUnicode_GET_LENGTH(item);
9591 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009592 if (use_memcpy) {
9593 Py_MEMCPY(res_data,
9594 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009595 kind * itemlen);
9596 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009597 }
9598 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009599 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009600 res_offset += itemlen;
9601 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009602 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009603 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009604 if (use_memcpy)
9605 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009606 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009607 else
9608 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009609
Tim Peters05eba1f2004-08-27 21:32:02 +00009610 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009611 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009612 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009613 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009614
Benjamin Peterson29060642009-01-31 22:14:21 +00009615 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009616 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009617 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009618 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009619 return NULL;
9620}
9621
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009622#define FILL(kind, data, value, start, length) \
9623 do { \
9624 Py_ssize_t i_ = 0; \
9625 assert(kind != PyUnicode_WCHAR_KIND); \
9626 switch ((kind)) { \
9627 case PyUnicode_1BYTE_KIND: { \
9628 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009629 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009630 break; \
9631 } \
9632 case PyUnicode_2BYTE_KIND: { \
9633 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9634 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9635 break; \
9636 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009637 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009638 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9639 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9640 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009641 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009642 } \
9643 } \
9644 } while (0)
9645
Victor Stinnerd3f08822012-05-29 12:57:52 +02009646void
9647_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9648 Py_UCS4 fill_char)
9649{
9650 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9651 const void *data = PyUnicode_DATA(unicode);
9652 assert(PyUnicode_IS_READY(unicode));
9653 assert(unicode_modifiable(unicode));
9654 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9655 assert(start >= 0);
9656 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9657 FILL(kind, data, fill_char, start, length);
9658}
9659
Victor Stinner3fe55312012-01-04 00:33:50 +01009660Py_ssize_t
9661PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9662 Py_UCS4 fill_char)
9663{
9664 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009665
9666 if (!PyUnicode_Check(unicode)) {
9667 PyErr_BadInternalCall();
9668 return -1;
9669 }
9670 if (PyUnicode_READY(unicode) == -1)
9671 return -1;
9672 if (unicode_check_modifiable(unicode))
9673 return -1;
9674
Victor Stinnerd3f08822012-05-29 12:57:52 +02009675 if (start < 0) {
9676 PyErr_SetString(PyExc_IndexError, "string index out of range");
9677 return -1;
9678 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009679 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9680 PyErr_SetString(PyExc_ValueError,
9681 "fill character is bigger than "
9682 "the string maximum character");
9683 return -1;
9684 }
9685
9686 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9687 length = Py_MIN(maxlen, length);
9688 if (length <= 0)
9689 return 0;
9690
Victor Stinnerd3f08822012-05-29 12:57:52 +02009691 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009692 return length;
9693}
9694
Victor Stinner9310abb2011-10-05 00:59:23 +02009695static PyObject *
9696pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009697 Py_ssize_t left,
9698 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009699 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009700{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009701 PyObject *u;
9702 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009703 int kind;
9704 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009705
9706 if (left < 0)
9707 left = 0;
9708 if (right < 0)
9709 right = 0;
9710
Victor Stinnerc4b49542011-12-11 22:44:26 +01009711 if (left == 0 && right == 0)
9712 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009713
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009714 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9715 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009716 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9717 return NULL;
9718 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009719 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009720 maxchar = MAX_MAXCHAR(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009721 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009722 if (!u)
9723 return NULL;
9724
9725 kind = PyUnicode_KIND(u);
9726 data = PyUnicode_DATA(u);
9727 if (left)
9728 FILL(kind, data, fill, 0, left);
9729 if (right)
9730 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009731 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009732 assert(_PyUnicode_CheckConsistency(u, 1));
9733 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009734}
9735
Alexander Belopolsky40018472011-02-26 01:02:56 +00009736PyObject *
9737PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009738{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009739 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009740
9741 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009742 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009743 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009744 if (PyUnicode_READY(string) == -1) {
9745 Py_DECREF(string);
9746 return NULL;
9747 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009748
Benjamin Petersonead6b532011-12-20 17:23:42 -06009749 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009750 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009751 if (PyUnicode_IS_ASCII(string))
9752 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009753 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009754 PyUnicode_GET_LENGTH(string), keepends);
9755 else
9756 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009757 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009758 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009759 break;
9760 case PyUnicode_2BYTE_KIND:
9761 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009762 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009763 PyUnicode_GET_LENGTH(string), keepends);
9764 break;
9765 case PyUnicode_4BYTE_KIND:
9766 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009767 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009768 PyUnicode_GET_LENGTH(string), keepends);
9769 break;
9770 default:
9771 assert(0);
9772 list = 0;
9773 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009774 Py_DECREF(string);
9775 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009776}
9777
Alexander Belopolsky40018472011-02-26 01:02:56 +00009778static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009779split(PyObject *self,
9780 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009781 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009782{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009783 int kind1, kind2, kind;
9784 void *buf1, *buf2;
9785 Py_ssize_t len1, len2;
9786 PyObject* out;
9787
Guido van Rossumd57fd912000-03-10 22:53:23 +00009788 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009789 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009790
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009791 if (PyUnicode_READY(self) == -1)
9792 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009793
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009794 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009795 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009796 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009797 if (PyUnicode_IS_ASCII(self))
9798 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009799 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009800 PyUnicode_GET_LENGTH(self), maxcount
9801 );
9802 else
9803 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009804 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009805 PyUnicode_GET_LENGTH(self), maxcount
9806 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009807 case PyUnicode_2BYTE_KIND:
9808 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009809 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009810 PyUnicode_GET_LENGTH(self), maxcount
9811 );
9812 case PyUnicode_4BYTE_KIND:
9813 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009814 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009815 PyUnicode_GET_LENGTH(self), maxcount
9816 );
9817 default:
9818 assert(0);
9819 return NULL;
9820 }
9821
9822 if (PyUnicode_READY(substring) == -1)
9823 return NULL;
9824
9825 kind1 = PyUnicode_KIND(self);
9826 kind2 = PyUnicode_KIND(substring);
9827 kind = kind1 > kind2 ? kind1 : kind2;
9828 buf1 = PyUnicode_DATA(self);
9829 buf2 = PyUnicode_DATA(substring);
9830 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009831 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009832 if (!buf1)
9833 return NULL;
9834 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009835 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009836 if (!buf2) {
9837 if (kind1 != kind) PyMem_Free(buf1);
9838 return NULL;
9839 }
9840 len1 = PyUnicode_GET_LENGTH(self);
9841 len2 = PyUnicode_GET_LENGTH(substring);
9842
Benjamin Petersonead6b532011-12-20 17:23:42 -06009843 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009844 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009845 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9846 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009847 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009848 else
9849 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009850 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009851 break;
9852 case PyUnicode_2BYTE_KIND:
9853 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009854 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009855 break;
9856 case PyUnicode_4BYTE_KIND:
9857 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009858 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009859 break;
9860 default:
9861 out = NULL;
9862 }
9863 if (kind1 != kind)
9864 PyMem_Free(buf1);
9865 if (kind2 != kind)
9866 PyMem_Free(buf2);
9867 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009868}
9869
Alexander Belopolsky40018472011-02-26 01:02:56 +00009870static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009871rsplit(PyObject *self,
9872 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009873 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009874{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009875 int kind1, kind2, kind;
9876 void *buf1, *buf2;
9877 Py_ssize_t len1, len2;
9878 PyObject* out;
9879
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009880 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009881 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009882
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009883 if (PyUnicode_READY(self) == -1)
9884 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009885
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009886 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009887 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009888 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009889 if (PyUnicode_IS_ASCII(self))
9890 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009891 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009892 PyUnicode_GET_LENGTH(self), maxcount
9893 );
9894 else
9895 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009896 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009897 PyUnicode_GET_LENGTH(self), maxcount
9898 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009899 case PyUnicode_2BYTE_KIND:
9900 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009901 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009902 PyUnicode_GET_LENGTH(self), maxcount
9903 );
9904 case PyUnicode_4BYTE_KIND:
9905 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009906 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009907 PyUnicode_GET_LENGTH(self), maxcount
9908 );
9909 default:
9910 assert(0);
9911 return NULL;
9912 }
9913
9914 if (PyUnicode_READY(substring) == -1)
9915 return NULL;
9916
9917 kind1 = PyUnicode_KIND(self);
9918 kind2 = PyUnicode_KIND(substring);
9919 kind = kind1 > kind2 ? kind1 : kind2;
9920 buf1 = PyUnicode_DATA(self);
9921 buf2 = PyUnicode_DATA(substring);
9922 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009923 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009924 if (!buf1)
9925 return NULL;
9926 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009927 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009928 if (!buf2) {
9929 if (kind1 != kind) PyMem_Free(buf1);
9930 return NULL;
9931 }
9932 len1 = PyUnicode_GET_LENGTH(self);
9933 len2 = PyUnicode_GET_LENGTH(substring);
9934
Benjamin Petersonead6b532011-12-20 17:23:42 -06009935 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009936 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009937 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9938 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009939 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009940 else
9941 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009942 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009943 break;
9944 case PyUnicode_2BYTE_KIND:
9945 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009946 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009947 break;
9948 case PyUnicode_4BYTE_KIND:
9949 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009950 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009951 break;
9952 default:
9953 out = NULL;
9954 }
9955 if (kind1 != kind)
9956 PyMem_Free(buf1);
9957 if (kind2 != kind)
9958 PyMem_Free(buf2);
9959 return out;
9960}
9961
9962static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009963anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9964 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009965{
Benjamin Petersonead6b532011-12-20 17:23:42 -06009966 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009967 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009968 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9969 return asciilib_find(buf1, len1, buf2, len2, offset);
9970 else
9971 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009972 case PyUnicode_2BYTE_KIND:
9973 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9974 case PyUnicode_4BYTE_KIND:
9975 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9976 }
9977 assert(0);
9978 return -1;
9979}
9980
9981static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009982anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
9983 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009984{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -06009985 switch (kind) {
9986 case PyUnicode_1BYTE_KIND:
9987 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
9988 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
9989 else
9990 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
9991 case PyUnicode_2BYTE_KIND:
9992 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
9993 case PyUnicode_4BYTE_KIND:
9994 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
9995 }
9996 assert(0);
9997 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009998}
9999
Alexander Belopolsky40018472011-02-26 01:02:56 +000010000static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010001replace(PyObject *self, PyObject *str1,
10002 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010003{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010004 PyObject *u;
10005 char *sbuf = PyUnicode_DATA(self);
10006 char *buf1 = PyUnicode_DATA(str1);
10007 char *buf2 = PyUnicode_DATA(str2);
10008 int srelease = 0, release1 = 0, release2 = 0;
10009 int skind = PyUnicode_KIND(self);
10010 int kind1 = PyUnicode_KIND(str1);
10011 int kind2 = PyUnicode_KIND(str2);
10012 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10013 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10014 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010015 int mayshrink;
10016 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010017
10018 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010019 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010020 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010021 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010022
Victor Stinner59de0ee2011-10-07 10:01:28 +020010023 if (str1 == str2)
10024 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010025 if (skind < kind1)
10026 /* substring too wide to be present */
10027 goto nothing;
10028
Victor Stinner49a0a212011-10-12 23:46:10 +020010029 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10030 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10031 /* Replacing str1 with str2 may cause a maxchar reduction in the
10032 result string. */
10033 mayshrink = (maxchar_str2 < maxchar);
Victor Stinnere6abb482012-05-02 01:15:40 +020010034 maxchar = MAX_MAXCHAR(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010035
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010036 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010037 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010038 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010039 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010040 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010041 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010042 Py_UCS4 u1, u2;
10043 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010044 Py_ssize_t index, pos;
10045 char *src;
10046
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010047 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010048 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10049 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010050 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010051 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010052 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010053 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010054 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010055 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010056 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010057
10058 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10059 index = 0;
10060 src = sbuf;
10061 while (--maxcount)
10062 {
10063 pos++;
10064 src += pos * PyUnicode_KIND(self);
10065 slen -= pos;
10066 index += pos;
10067 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10068 if (pos < 0)
10069 break;
10070 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10071 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010072 }
10073 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010074 int rkind = skind;
10075 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010076 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010077
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 if (kind1 < rkind) {
10079 /* widen substring */
10080 buf1 = _PyUnicode_AsKind(str1, rkind);
10081 if (!buf1) goto error;
10082 release1 = 1;
10083 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010084 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010085 if (i < 0)
10086 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010087 if (rkind > kind2) {
10088 /* widen replacement */
10089 buf2 = _PyUnicode_AsKind(str2, rkind);
10090 if (!buf2) goto error;
10091 release2 = 1;
10092 }
10093 else if (rkind < kind2) {
10094 /* widen self and buf1 */
10095 rkind = kind2;
10096 if (release1) PyMem_Free(buf1);
10097 sbuf = _PyUnicode_AsKind(self, rkind);
10098 if (!sbuf) goto error;
10099 srelease = 1;
10100 buf1 = _PyUnicode_AsKind(str1, rkind);
10101 if (!buf1) goto error;
10102 release1 = 1;
10103 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010104 u = PyUnicode_New(slen, maxchar);
10105 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010106 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010107 assert(PyUnicode_KIND(u) == rkind);
10108 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010109
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010110 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010111 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010112 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010113 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010114 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010115 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010116
10117 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010118 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010119 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010120 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010121 if (i == -1)
10122 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010123 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010124 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010125 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010126 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010127 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010128 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010129 }
10130 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010131 Py_ssize_t n, i, j, ires;
10132 Py_ssize_t product, new_size;
10133 int rkind = skind;
10134 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010135
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010136 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010137 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 buf1 = _PyUnicode_AsKind(str1, rkind);
10139 if (!buf1) goto error;
10140 release1 = 1;
10141 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010142 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010143 if (n == 0)
10144 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010145 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010146 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 buf2 = _PyUnicode_AsKind(str2, rkind);
10148 if (!buf2) goto error;
10149 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010150 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010152 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 rkind = kind2;
10154 sbuf = _PyUnicode_AsKind(self, rkind);
10155 if (!sbuf) goto error;
10156 srelease = 1;
10157 if (release1) PyMem_Free(buf1);
10158 buf1 = _PyUnicode_AsKind(str1, rkind);
10159 if (!buf1) goto error;
10160 release1 = 1;
10161 }
10162 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10163 PyUnicode_GET_LENGTH(str1))); */
10164 product = n * (len2-len1);
10165 if ((product / (len2-len1)) != n) {
10166 PyErr_SetString(PyExc_OverflowError,
10167 "replace string is too long");
10168 goto error;
10169 }
10170 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010171 if (new_size == 0) {
10172 Py_INCREF(unicode_empty);
10173 u = unicode_empty;
10174 goto done;
10175 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010176 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10177 PyErr_SetString(PyExc_OverflowError,
10178 "replace string is too long");
10179 goto error;
10180 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010181 u = PyUnicode_New(new_size, maxchar);
10182 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010184 assert(PyUnicode_KIND(u) == rkind);
10185 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010186 ires = i = 0;
10187 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010188 while (n-- > 0) {
10189 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010190 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010191 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010192 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010193 if (j == -1)
10194 break;
10195 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010196 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010197 memcpy(res + rkind * ires,
10198 sbuf + rkind * i,
10199 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010200 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010201 }
10202 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010204 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010205 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010206 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010208 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010209 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010210 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010211 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010212 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010213 memcpy(res + rkind * ires,
10214 sbuf + rkind * i,
10215 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010216 }
10217 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010218 /* interleave */
10219 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010220 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010221 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010222 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010223 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010224 if (--n <= 0)
10225 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010226 memcpy(res + rkind * ires,
10227 sbuf + rkind * i,
10228 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 ires++;
10230 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010231 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010232 memcpy(res + rkind * ires,
10233 sbuf + rkind * i,
10234 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010235 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010236 }
10237
10238 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010239 unicode_adjust_maxchar(&u);
10240 if (u == NULL)
10241 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010242 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010243
10244 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010245 if (srelease)
10246 PyMem_FREE(sbuf);
10247 if (release1)
10248 PyMem_FREE(buf1);
10249 if (release2)
10250 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010251 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010252 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010253
Benjamin Peterson29060642009-01-31 22:14:21 +000010254 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010255 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010256 if (srelease)
10257 PyMem_FREE(sbuf);
10258 if (release1)
10259 PyMem_FREE(buf1);
10260 if (release2)
10261 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010262 return unicode_result_unchanged(self);
10263
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010264 error:
10265 if (srelease && sbuf)
10266 PyMem_FREE(sbuf);
10267 if (release1 && buf1)
10268 PyMem_FREE(buf1);
10269 if (release2 && buf2)
10270 PyMem_FREE(buf2);
10271 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010272}
10273
10274/* --- Unicode Object Methods --------------------------------------------- */
10275
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010276PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010277 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010278\n\
10279Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010280characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010281
10282static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010283unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010284{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010285 if (PyUnicode_READY(self) == -1)
10286 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010287 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010288}
10289
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010290PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010291 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010292\n\
10293Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010294have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010295
10296static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010297unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010298{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010299 if (PyUnicode_READY(self) == -1)
10300 return NULL;
10301 if (PyUnicode_GET_LENGTH(self) == 0)
10302 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010303 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010304}
10305
Benjamin Petersond5890c82012-01-14 13:23:30 -050010306PyDoc_STRVAR(casefold__doc__,
10307 "S.casefold() -> str\n\
10308\n\
10309Return a version of S suitable for caseless comparisons.");
10310
10311static PyObject *
10312unicode_casefold(PyObject *self)
10313{
10314 if (PyUnicode_READY(self) == -1)
10315 return NULL;
10316 if (PyUnicode_IS_ASCII(self))
10317 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010318 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010319}
10320
10321
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010322/* Argument converter. Coerces to a single unicode character */
10323
10324static int
10325convert_uc(PyObject *obj, void *addr)
10326{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010327 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010328 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010329
Benjamin Peterson14339b62009-01-31 16:36:08 +000010330 uniobj = PyUnicode_FromObject(obj);
10331 if (uniobj == NULL) {
10332 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010333 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010334 return 0;
10335 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010336 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010337 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010338 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010339 Py_DECREF(uniobj);
10340 return 0;
10341 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010343 Py_DECREF(uniobj);
10344 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010345}
10346
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010347PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010348 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010349\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010350Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010351done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010352
10353static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010354unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010355{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010356 Py_ssize_t marg, left;
10357 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010358 Py_UCS4 fillchar = ' ';
10359
Victor Stinnere9a29352011-10-01 02:14:59 +020010360 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010361 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010362
Benjamin Petersonbac79492012-01-14 13:34:47 -050010363 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010364 return NULL;
10365
Victor Stinnerc4b49542011-12-11 22:44:26 +010010366 if (PyUnicode_GET_LENGTH(self) >= width)
10367 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010368
Victor Stinnerc4b49542011-12-11 22:44:26 +010010369 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010370 left = marg / 2 + (marg & width & 1);
10371
Victor Stinner9310abb2011-10-05 00:59:23 +020010372 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010373}
10374
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010375/* This function assumes that str1 and str2 are readied by the caller. */
10376
Marc-André Lemburge5034372000-08-08 08:04:29 +000010377static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010378unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010379{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010380 int kind1, kind2;
10381 void *data1, *data2;
10382 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010383
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010384 kind1 = PyUnicode_KIND(str1);
10385 kind2 = PyUnicode_KIND(str2);
10386 data1 = PyUnicode_DATA(str1);
10387 data2 = PyUnicode_DATA(str2);
10388 len1 = PyUnicode_GET_LENGTH(str1);
10389 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010390
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010391 for (i = 0; i < len1 && i < len2; ++i) {
10392 Py_UCS4 c1, c2;
10393 c1 = PyUnicode_READ(kind1, data1, i);
10394 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010395
10396 if (c1 != c2)
10397 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010398 }
10399
10400 return (len1 < len2) ? -1 : (len1 != len2);
10401}
10402
Alexander Belopolsky40018472011-02-26 01:02:56 +000010403int
10404PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010405{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010406 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10407 if (PyUnicode_READY(left) == -1 ||
10408 PyUnicode_READY(right) == -1)
10409 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010410 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010411 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010412 PyErr_Format(PyExc_TypeError,
10413 "Can't compare %.100s and %.100s",
10414 left->ob_type->tp_name,
10415 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010416 return -1;
10417}
10418
Martin v. Löwis5b222132007-06-10 09:51:05 +000010419int
10420PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10421{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010422 Py_ssize_t i;
10423 int kind;
10424 void *data;
10425 Py_UCS4 chr;
10426
Victor Stinner910337b2011-10-03 03:20:16 +020010427 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010428 if (PyUnicode_READY(uni) == -1)
10429 return -1;
10430 kind = PyUnicode_KIND(uni);
10431 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010432 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010433 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10434 if (chr != str[i])
10435 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010436 /* This check keeps Python strings that end in '\0' from comparing equal
10437 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010438 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010439 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010440 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010441 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010442 return 0;
10443}
10444
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010445
Benjamin Peterson29060642009-01-31 22:14:21 +000010446#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010447 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010448
Alexander Belopolsky40018472011-02-26 01:02:56 +000010449PyObject *
10450PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010451{
10452 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010453
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010454 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10455 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010456 if (PyUnicode_READY(left) == -1 ||
10457 PyUnicode_READY(right) == -1)
10458 return NULL;
10459 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10460 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010461 if (op == Py_EQ) {
10462 Py_INCREF(Py_False);
10463 return Py_False;
10464 }
10465 if (op == Py_NE) {
10466 Py_INCREF(Py_True);
10467 return Py_True;
10468 }
10469 }
10470 if (left == right)
10471 result = 0;
10472 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010473 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010474
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010475 /* Convert the return value to a Boolean */
10476 switch (op) {
10477 case Py_EQ:
10478 v = TEST_COND(result == 0);
10479 break;
10480 case Py_NE:
10481 v = TEST_COND(result != 0);
10482 break;
10483 case Py_LE:
10484 v = TEST_COND(result <= 0);
10485 break;
10486 case Py_GE:
10487 v = TEST_COND(result >= 0);
10488 break;
10489 case Py_LT:
10490 v = TEST_COND(result == -1);
10491 break;
10492 case Py_GT:
10493 v = TEST_COND(result == 1);
10494 break;
10495 default:
10496 PyErr_BadArgument();
10497 return NULL;
10498 }
10499 Py_INCREF(v);
10500 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010501 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010502
Brian Curtindfc80e32011-08-10 20:28:54 -050010503 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010504}
10505
Alexander Belopolsky40018472011-02-26 01:02:56 +000010506int
10507PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010508{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010509 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010510 int kind1, kind2, kind;
10511 void *buf1, *buf2;
10512 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010513 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010514
10515 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010516 sub = PyUnicode_FromObject(element);
10517 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010518 PyErr_Format(PyExc_TypeError,
10519 "'in <string>' requires string as left operand, not %s",
10520 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010521 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010522 }
10523
Thomas Wouters477c8d52006-05-27 19:21:47 +000010524 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010525 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010526 Py_DECREF(sub);
10527 return -1;
10528 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010529 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10530 Py_DECREF(sub);
10531 Py_DECREF(str);
10532 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010533
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010534 kind1 = PyUnicode_KIND(str);
10535 kind2 = PyUnicode_KIND(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010536 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010537 buf1 = PyUnicode_DATA(str);
10538 buf2 = PyUnicode_DATA(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010539 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010540 if (kind2 > kind) {
10541 Py_DECREF(sub);
10542 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010543 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010544 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010010545 buf2 = _PyUnicode_AsKind(sub, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010546 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010547 if (!buf2) {
10548 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010549 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010550 return -1;
10551 }
10552 len1 = PyUnicode_GET_LENGTH(str);
10553 len2 = PyUnicode_GET_LENGTH(sub);
10554
Benjamin Petersonead6b532011-12-20 17:23:42 -060010555 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010556 case PyUnicode_1BYTE_KIND:
10557 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10558 break;
10559 case PyUnicode_2BYTE_KIND:
10560 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10561 break;
10562 case PyUnicode_4BYTE_KIND:
10563 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10564 break;
10565 default:
10566 result = -1;
10567 assert(0);
10568 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010569
10570 Py_DECREF(str);
10571 Py_DECREF(sub);
10572
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010573 if (kind2 != kind)
10574 PyMem_Free(buf2);
10575
Guido van Rossum403d68b2000-03-13 15:55:09 +000010576 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010577}
10578
Guido van Rossumd57fd912000-03-10 22:53:23 +000010579/* Concat to string or Unicode object giving a new Unicode object. */
10580
Alexander Belopolsky40018472011-02-26 01:02:56 +000010581PyObject *
10582PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010583{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010584 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010585 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010586 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010587
10588 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010589 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010590 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010591 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010592 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010593 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010594 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010595
10596 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010597 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010598 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010599 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010600 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010601 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010602 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010604 }
10605
Victor Stinner488fa492011-12-12 00:01:39 +010010606 u_len = PyUnicode_GET_LENGTH(u);
10607 v_len = PyUnicode_GET_LENGTH(v);
10608 if (u_len > PY_SSIZE_T_MAX - v_len) {
10609 PyErr_SetString(PyExc_OverflowError,
10610 "strings are too large to concat");
10611 goto onError;
10612 }
10613 new_len = u_len + v_len;
10614
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010615 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010616 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Victor Stinnere6abb482012-05-02 01:15:40 +020010617 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010618
Guido van Rossumd57fd912000-03-10 22:53:23 +000010619 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010620 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010621 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010622 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010623 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10624 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010625 Py_DECREF(u);
10626 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010627 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010628 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010629
Benjamin Peterson29060642009-01-31 22:14:21 +000010630 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010631 Py_XDECREF(u);
10632 Py_XDECREF(v);
10633 return NULL;
10634}
10635
Walter Dörwald1ab83302007-05-18 17:15:44 +000010636void
Victor Stinner23e56682011-10-03 03:54:37 +020010637PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010638{
Victor Stinner23e56682011-10-03 03:54:37 +020010639 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010640 Py_UCS4 maxchar, maxchar2;
10641 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010642
10643 if (p_left == NULL) {
10644 if (!PyErr_Occurred())
10645 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010646 return;
10647 }
Victor Stinner23e56682011-10-03 03:54:37 +020010648 left = *p_left;
10649 if (right == NULL || !PyUnicode_Check(left)) {
10650 if (!PyErr_Occurred())
10651 PyErr_BadInternalCall();
10652 goto error;
10653 }
10654
Benjamin Petersonbac79492012-01-14 13:34:47 -050010655 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010656 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010657 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010658 goto error;
10659
Victor Stinner488fa492011-12-12 00:01:39 +010010660 /* Shortcuts */
10661 if (left == unicode_empty) {
10662 Py_DECREF(left);
10663 Py_INCREF(right);
10664 *p_left = right;
10665 return;
10666 }
10667 if (right == unicode_empty)
10668 return;
10669
10670 left_len = PyUnicode_GET_LENGTH(left);
10671 right_len = PyUnicode_GET_LENGTH(right);
10672 if (left_len > PY_SSIZE_T_MAX - right_len) {
10673 PyErr_SetString(PyExc_OverflowError,
10674 "strings are too large to concat");
10675 goto error;
10676 }
10677 new_len = left_len + right_len;
10678
10679 if (unicode_modifiable(left)
10680 && PyUnicode_CheckExact(right)
10681 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010682 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10683 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010684 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010685 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010686 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10687 {
10688 /* append inplace */
10689 if (unicode_resize(p_left, new_len) != 0) {
10690 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10691 * deallocated so it cannot be put back into
10692 * 'variable'. The MemoryError is raised when there
10693 * is no value in 'variable', which might (very
10694 * remotely) be a cause of incompatibilities.
10695 */
10696 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010697 }
Victor Stinner488fa492011-12-12 00:01:39 +010010698 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerd3f08822012-05-29 12:57:52 +020010699 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010700 }
Victor Stinner488fa492011-12-12 00:01:39 +010010701 else {
10702 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10703 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Victor Stinnere6abb482012-05-02 01:15:40 +020010704 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010705
Victor Stinner488fa492011-12-12 00:01:39 +010010706 /* Concat the two Unicode strings */
10707 res = PyUnicode_New(new_len, maxchar);
10708 if (res == NULL)
10709 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010710 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10711 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010712 Py_DECREF(left);
10713 *p_left = res;
10714 }
10715 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010716 return;
10717
10718error:
Victor Stinner488fa492011-12-12 00:01:39 +010010719 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010720}
10721
10722void
10723PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10724{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010725 PyUnicode_Append(pleft, right);
10726 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010727}
10728
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010729PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010730 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010731\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010732Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010733string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010734interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010735
10736static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010737unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010738{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010739 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010740 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010741 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010742 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010743 int kind1, kind2, kind;
10744 void *buf1, *buf2;
10745 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010746
Jesus Ceaac451502011-04-20 17:09:23 +020010747 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10748 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010749 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010750
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010751 kind1 = PyUnicode_KIND(self);
10752 kind2 = PyUnicode_KIND(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010753 if (kind2 > kind1)
10754 return PyLong_FromLong(0);
10755 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010756 buf1 = PyUnicode_DATA(self);
10757 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010758 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010759 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010760 if (!buf2) {
10761 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010762 return NULL;
10763 }
10764 len1 = PyUnicode_GET_LENGTH(self);
10765 len2 = PyUnicode_GET_LENGTH(substring);
10766
10767 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010768 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010769 case PyUnicode_1BYTE_KIND:
10770 iresult = ucs1lib_count(
10771 ((Py_UCS1*)buf1) + start, end - start,
10772 buf2, len2, PY_SSIZE_T_MAX
10773 );
10774 break;
10775 case PyUnicode_2BYTE_KIND:
10776 iresult = ucs2lib_count(
10777 ((Py_UCS2*)buf1) + start, end - start,
10778 buf2, len2, PY_SSIZE_T_MAX
10779 );
10780 break;
10781 case PyUnicode_4BYTE_KIND:
10782 iresult = ucs4lib_count(
10783 ((Py_UCS4*)buf1) + start, end - start,
10784 buf2, len2, PY_SSIZE_T_MAX
10785 );
10786 break;
10787 default:
10788 assert(0); iresult = 0;
10789 }
10790
10791 result = PyLong_FromSsize_t(iresult);
10792
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010793 if (kind2 != kind)
10794 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010795
10796 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010797
Guido van Rossumd57fd912000-03-10 22:53:23 +000010798 return result;
10799}
10800
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010801PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010802 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010803\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010804Encode S using the codec registered for encoding. Default encoding\n\
10805is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010806handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010807a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10808'xmlcharrefreplace' as well as any other name registered with\n\
10809codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010810
10811static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010812unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010813{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010814 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010815 char *encoding = NULL;
10816 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010817
Benjamin Peterson308d6372009-09-18 21:42:35 +000010818 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10819 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010820 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010821 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010822}
10823
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010824PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010825 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010826\n\
10827Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010828If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010829
10830static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010831unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010832{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010833 Py_ssize_t i, j, line_pos, src_len, incr;
10834 Py_UCS4 ch;
10835 PyObject *u;
10836 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010837 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010838 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010839 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010840
10841 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010842 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010843
Antoine Pitrou22425222011-10-04 19:10:51 +020010844 if (PyUnicode_READY(self) == -1)
10845 return NULL;
10846
Thomas Wouters7e474022000-07-16 12:04:32 +000010847 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010848 src_len = PyUnicode_GET_LENGTH(self);
10849 i = j = line_pos = 0;
10850 kind = PyUnicode_KIND(self);
10851 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010852 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010853 for (; i < src_len; i++) {
10854 ch = PyUnicode_READ(kind, src_data, i);
10855 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010856 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010857 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010858 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010859 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010860 goto overflow;
10861 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010862 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010863 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010864 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010865 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010866 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010867 goto overflow;
10868 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010869 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010870 if (ch == '\n' || ch == '\r')
10871 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010872 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010873 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010010874 if (!found)
10875 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010876
Guido van Rossumd57fd912000-03-10 22:53:23 +000010877 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010878 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010879 if (!u)
10880 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010881 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010882
Antoine Pitroue71d5742011-10-04 15:55:09 +020010883 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010884
Antoine Pitroue71d5742011-10-04 15:55:09 +020010885 for (; i < src_len; i++) {
10886 ch = PyUnicode_READ(kind, src_data, i);
10887 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010888 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010889 incr = tabsize - (line_pos % tabsize);
10890 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010010891 FILL(kind, dest_data, ' ', j, incr);
10892 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010893 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010894 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010895 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010896 line_pos++;
10897 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010898 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010899 if (ch == '\n' || ch == '\r')
10900 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010901 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010902 }
10903 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010904 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010905
Antoine Pitroue71d5742011-10-04 15:55:09 +020010906 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010907 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10908 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010909}
10910
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010911PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010912 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010913\n\
10914Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010915such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010916arguments start and end are interpreted as in slice notation.\n\
10917\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010918Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010919
10920static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010921unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010922{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010923 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010924 Py_ssize_t start;
10925 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010926 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010927
Jesus Ceaac451502011-04-20 17:09:23 +020010928 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10929 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010930 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010931
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010932 if (PyUnicode_READY(self) == -1)
10933 return NULL;
10934 if (PyUnicode_READY(substring) == -1)
10935 return NULL;
10936
Victor Stinner7931d9a2011-11-04 00:22:48 +010010937 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010938
10939 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010940
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010941 if (result == -2)
10942 return NULL;
10943
Christian Heimes217cfd12007-12-02 14:31:20 +000010944 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010945}
10946
10947static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010948unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010949{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010950 void *data;
10951 enum PyUnicode_Kind kind;
10952 Py_UCS4 ch;
10953 PyObject *res;
10954
10955 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
10956 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010957 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010958 }
10959 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
10960 PyErr_SetString(PyExc_IndexError, "string index out of range");
10961 return NULL;
10962 }
10963 kind = PyUnicode_KIND(self);
10964 data = PyUnicode_DATA(self);
10965 ch = PyUnicode_READ(kind, data, index);
10966 if (ch < 256)
10967 return get_latin1_char(ch);
10968
10969 res = PyUnicode_New(1, ch);
10970 if (res == NULL)
10971 return NULL;
10972 kind = PyUnicode_KIND(res);
10973 data = PyUnicode_DATA(res);
10974 PyUnicode_WRITE(kind, data, 0, ch);
10975 assert(_PyUnicode_CheckConsistency(res, 1));
10976 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010977}
10978
Guido van Rossumc2504932007-09-18 19:42:40 +000010979/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010010980 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000010981static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010982unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010983{
Guido van Rossumc2504932007-09-18 19:42:40 +000010984 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010010985 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010986
Benjamin Petersonf6622c82012-04-09 14:53:07 -040010987#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050010988 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040010989#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010990 if (_PyUnicode_HASH(self) != -1)
10991 return _PyUnicode_HASH(self);
10992 if (PyUnicode_READY(self) == -1)
10993 return -1;
10994 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010010995 /*
10996 We make the hash of the empty string be 0, rather than using
10997 (prefix ^ suffix), since this slightly obfuscates the hash secret
10998 */
10999 if (len == 0) {
11000 _PyUnicode_HASH(self) = 0;
11001 return 0;
11002 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011003
11004 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011005#define HASH(P) \
11006 x ^= (Py_uhash_t) *P << 7; \
11007 while (--len >= 0) \
11008 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011009
Georg Brandl2fb477c2012-02-21 00:33:36 +010011010 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011011 switch (PyUnicode_KIND(self)) {
11012 case PyUnicode_1BYTE_KIND: {
11013 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11014 HASH(c);
11015 break;
11016 }
11017 case PyUnicode_2BYTE_KIND: {
11018 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11019 HASH(s);
11020 break;
11021 }
11022 default: {
11023 Py_UCS4 *l;
11024 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11025 "Impossible switch case in unicode_hash");
11026 l = PyUnicode_4BYTE_DATA(self);
11027 HASH(l);
11028 break;
11029 }
11030 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011031 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11032 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011033
Guido van Rossumc2504932007-09-18 19:42:40 +000011034 if (x == -1)
11035 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011036 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011037 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011038}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011039#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011040
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011041PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011042 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011043\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011044Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011045
11046static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011047unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011048{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011049 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011050 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011051 Py_ssize_t start;
11052 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011053
Jesus Ceaac451502011-04-20 17:09:23 +020011054 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11055 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011056 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011057
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011058 if (PyUnicode_READY(self) == -1)
11059 return NULL;
11060 if (PyUnicode_READY(substring) == -1)
11061 return NULL;
11062
Victor Stinner7931d9a2011-11-04 00:22:48 +010011063 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011064
11065 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011066
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011067 if (result == -2)
11068 return NULL;
11069
Guido van Rossumd57fd912000-03-10 22:53:23 +000011070 if (result < 0) {
11071 PyErr_SetString(PyExc_ValueError, "substring not found");
11072 return NULL;
11073 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011074
Christian Heimes217cfd12007-12-02 14:31:20 +000011075 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011076}
11077
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011078PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011079 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011080\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011081Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011082at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011083
11084static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011085unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011086{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011087 Py_ssize_t i, length;
11088 int kind;
11089 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011090 int cased;
11091
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011092 if (PyUnicode_READY(self) == -1)
11093 return NULL;
11094 length = PyUnicode_GET_LENGTH(self);
11095 kind = PyUnicode_KIND(self);
11096 data = PyUnicode_DATA(self);
11097
Guido van Rossumd57fd912000-03-10 22:53:23 +000011098 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011099 if (length == 1)
11100 return PyBool_FromLong(
11101 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011102
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011103 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011104 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011105 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011106
Guido van Rossumd57fd912000-03-10 22:53:23 +000011107 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011108 for (i = 0; i < length; i++) {
11109 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011110
Benjamin Peterson29060642009-01-31 22:14:21 +000011111 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11112 return PyBool_FromLong(0);
11113 else if (!cased && Py_UNICODE_ISLOWER(ch))
11114 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011115 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011116 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011117}
11118
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011119PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011120 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011121\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011122Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011123at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011124
11125static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011126unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011127{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011128 Py_ssize_t i, length;
11129 int kind;
11130 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011131 int cased;
11132
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011133 if (PyUnicode_READY(self) == -1)
11134 return NULL;
11135 length = PyUnicode_GET_LENGTH(self);
11136 kind = PyUnicode_KIND(self);
11137 data = PyUnicode_DATA(self);
11138
Guido van Rossumd57fd912000-03-10 22:53:23 +000011139 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011140 if (length == 1)
11141 return PyBool_FromLong(
11142 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011143
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011144 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011145 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011146 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011147
Guido van Rossumd57fd912000-03-10 22:53:23 +000011148 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011149 for (i = 0; i < length; i++) {
11150 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011151
Benjamin Peterson29060642009-01-31 22:14:21 +000011152 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11153 return PyBool_FromLong(0);
11154 else if (!cased && Py_UNICODE_ISUPPER(ch))
11155 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011156 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011157 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011158}
11159
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011160PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011161 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011162\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011163Return True if S is a titlecased string and there is at least one\n\
11164character in S, i.e. upper- and titlecase characters may only\n\
11165follow uncased characters and lowercase characters only cased ones.\n\
11166Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011167
11168static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011169unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011170{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011171 Py_ssize_t i, length;
11172 int kind;
11173 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174 int cased, previous_is_cased;
11175
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011176 if (PyUnicode_READY(self) == -1)
11177 return NULL;
11178 length = PyUnicode_GET_LENGTH(self);
11179 kind = PyUnicode_KIND(self);
11180 data = PyUnicode_DATA(self);
11181
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011183 if (length == 1) {
11184 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11185 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11186 (Py_UNICODE_ISUPPER(ch) != 0));
11187 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011188
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011189 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011190 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011191 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011192
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193 cased = 0;
11194 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011195 for (i = 0; i < length; i++) {
11196 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011197
Benjamin Peterson29060642009-01-31 22:14:21 +000011198 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11199 if (previous_is_cased)
11200 return PyBool_FromLong(0);
11201 previous_is_cased = 1;
11202 cased = 1;
11203 }
11204 else if (Py_UNICODE_ISLOWER(ch)) {
11205 if (!previous_is_cased)
11206 return PyBool_FromLong(0);
11207 previous_is_cased = 1;
11208 cased = 1;
11209 }
11210 else
11211 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011212 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011213 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011214}
11215
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011216PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011217 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011219Return True if all characters in S are whitespace\n\
11220and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221
11222static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011223unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011225 Py_ssize_t i, length;
11226 int kind;
11227 void *data;
11228
11229 if (PyUnicode_READY(self) == -1)
11230 return NULL;
11231 length = PyUnicode_GET_LENGTH(self);
11232 kind = PyUnicode_KIND(self);
11233 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011234
Guido van Rossumd57fd912000-03-10 22:53:23 +000011235 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011236 if (length == 1)
11237 return PyBool_FromLong(
11238 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011239
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011240 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011241 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011242 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011243
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011244 for (i = 0; i < length; i++) {
11245 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011246 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011247 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011248 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011249 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011250}
11251
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011252PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011253 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011254\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011255Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011256and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011257
11258static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011259unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011260{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011261 Py_ssize_t i, length;
11262 int kind;
11263 void *data;
11264
11265 if (PyUnicode_READY(self) == -1)
11266 return NULL;
11267 length = PyUnicode_GET_LENGTH(self);
11268 kind = PyUnicode_KIND(self);
11269 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011270
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011271 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011272 if (length == 1)
11273 return PyBool_FromLong(
11274 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011275
11276 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011277 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011278 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011279
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011280 for (i = 0; i < length; i++) {
11281 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011282 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011283 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011284 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011285}
11286
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011287PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011288 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011289\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011290Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011291and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011292
11293static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011294unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011295{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011296 int kind;
11297 void *data;
11298 Py_ssize_t len, i;
11299
11300 if (PyUnicode_READY(self) == -1)
11301 return NULL;
11302
11303 kind = PyUnicode_KIND(self);
11304 data = PyUnicode_DATA(self);
11305 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011306
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011307 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011308 if (len == 1) {
11309 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11310 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11311 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011312
11313 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011314 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011315 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011316
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011317 for (i = 0; i < len; i++) {
11318 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011319 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011320 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011321 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011322 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011323}
11324
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011325PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011326 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011327\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011328Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011329False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330
11331static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011332unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011333{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011334 Py_ssize_t i, length;
11335 int kind;
11336 void *data;
11337
11338 if (PyUnicode_READY(self) == -1)
11339 return NULL;
11340 length = PyUnicode_GET_LENGTH(self);
11341 kind = PyUnicode_KIND(self);
11342 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343
Guido van Rossumd57fd912000-03-10 22:53:23 +000011344 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011345 if (length == 1)
11346 return PyBool_FromLong(
11347 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011348
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011349 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011350 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011351 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011352
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011353 for (i = 0; i < length; i++) {
11354 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011355 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011356 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011357 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011358}
11359
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011360PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011361 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011362\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011363Return True if all characters in S are digits\n\
11364and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011365
11366static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011367unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011368{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011369 Py_ssize_t i, length;
11370 int kind;
11371 void *data;
11372
11373 if (PyUnicode_READY(self) == -1)
11374 return NULL;
11375 length = PyUnicode_GET_LENGTH(self);
11376 kind = PyUnicode_KIND(self);
11377 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011378
Guido van Rossumd57fd912000-03-10 22:53:23 +000011379 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011380 if (length == 1) {
11381 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11382 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11383 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011384
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011385 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011386 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011387 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011388
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011389 for (i = 0; i < length; i++) {
11390 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011391 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011392 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011393 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011394}
11395
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011396PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011397 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011399Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011400False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011401
11402static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011403unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011404{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011405 Py_ssize_t i, length;
11406 int kind;
11407 void *data;
11408
11409 if (PyUnicode_READY(self) == -1)
11410 return NULL;
11411 length = PyUnicode_GET_LENGTH(self);
11412 kind = PyUnicode_KIND(self);
11413 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414
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_ISNUMERIC(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
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011424 for (i = 0; i < length; i++) {
11425 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011426 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011427 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011428 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429}
11430
Martin v. Löwis47383402007-08-15 07:32:56 +000011431int
11432PyUnicode_IsIdentifier(PyObject *self)
11433{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011434 int kind;
11435 void *data;
11436 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011437 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011438
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011439 if (PyUnicode_READY(self) == -1) {
11440 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011441 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011442 }
11443
11444 /* Special case for empty strings */
11445 if (PyUnicode_GET_LENGTH(self) == 0)
11446 return 0;
11447 kind = PyUnicode_KIND(self);
11448 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011449
11450 /* PEP 3131 says that the first character must be in
11451 XID_Start and subsequent characters in XID_Continue,
11452 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011453 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011454 letters, digits, underscore). However, given the current
11455 definition of XID_Start and XID_Continue, it is sufficient
11456 to check just for these, except that _ must be allowed
11457 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011458 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011459 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011460 return 0;
11461
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011462 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011463 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011464 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011465 return 1;
11466}
11467
11468PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011469 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011470\n\
11471Return True if S is a valid identifier according\n\
11472to the language definition.");
11473
11474static PyObject*
11475unicode_isidentifier(PyObject *self)
11476{
11477 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11478}
11479
Georg Brandl559e5d72008-06-11 18:37:52 +000011480PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011481 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011482\n\
11483Return True if all characters in S are considered\n\
11484printable in repr() or S is empty, False otherwise.");
11485
11486static PyObject*
11487unicode_isprintable(PyObject *self)
11488{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011489 Py_ssize_t i, length;
11490 int kind;
11491 void *data;
11492
11493 if (PyUnicode_READY(self) == -1)
11494 return NULL;
11495 length = PyUnicode_GET_LENGTH(self);
11496 kind = PyUnicode_KIND(self);
11497 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011498
11499 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011500 if (length == 1)
11501 return PyBool_FromLong(
11502 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011503
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011504 for (i = 0; i < length; i++) {
11505 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011506 Py_RETURN_FALSE;
11507 }
11508 }
11509 Py_RETURN_TRUE;
11510}
11511
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011512PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011513 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011514\n\
11515Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011516iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517
11518static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011519unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011521 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011522}
11523
Martin v. Löwis18e16552006-02-15 17:27:45 +000011524static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011525unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011526{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011527 if (PyUnicode_READY(self) == -1)
11528 return -1;
11529 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011530}
11531
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011532PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011533 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011534\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011535Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011536done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011537
11538static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011539unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011541 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011542 Py_UCS4 fillchar = ' ';
11543
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011544 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011545 return NULL;
11546
Benjamin Petersonbac79492012-01-14 13:34:47 -050011547 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011548 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549
Victor Stinnerc4b49542011-12-11 22:44:26 +010011550 if (PyUnicode_GET_LENGTH(self) >= width)
11551 return unicode_result_unchanged(self);
11552
11553 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554}
11555
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011556PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011557 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011559Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560
11561static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011562unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011563{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011564 if (PyUnicode_READY(self) == -1)
11565 return NULL;
11566 if (PyUnicode_IS_ASCII(self))
11567 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011568 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569}
11570
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011571#define LEFTSTRIP 0
11572#define RIGHTSTRIP 1
11573#define BOTHSTRIP 2
11574
11575/* Arrays indexed by above */
11576static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11577
11578#define STRIPNAME(i) (stripformat[i]+3)
11579
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011580/* externally visible for str.strip(unicode) */
11581PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011582_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011583{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011584 void *data;
11585 int kind;
11586 Py_ssize_t i, j, len;
11587 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011588
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011589 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11590 return NULL;
11591
11592 kind = PyUnicode_KIND(self);
11593 data = PyUnicode_DATA(self);
11594 len = PyUnicode_GET_LENGTH(self);
11595 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11596 PyUnicode_DATA(sepobj),
11597 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011598
Benjamin Peterson14339b62009-01-31 16:36:08 +000011599 i = 0;
11600 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011601 while (i < len &&
11602 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011603 i++;
11604 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011605 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011606
Benjamin Peterson14339b62009-01-31 16:36:08 +000011607 j = len;
11608 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011609 do {
11610 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011611 } while (j >= i &&
11612 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011613 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011614 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011615
Victor Stinner7931d9a2011-11-04 00:22:48 +010011616 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011617}
11618
11619PyObject*
11620PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11621{
11622 unsigned char *data;
11623 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011624 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011625
Victor Stinnerde636f32011-10-01 03:55:54 +020011626 if (PyUnicode_READY(self) == -1)
11627 return NULL;
11628
Victor Stinner684d5fd2012-05-03 02:32:34 +020011629 length = PyUnicode_GET_LENGTH(self);
11630 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011631
Victor Stinner684d5fd2012-05-03 02:32:34 +020011632 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011633 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011634
Victor Stinnerde636f32011-10-01 03:55:54 +020011635 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011636 PyErr_SetString(PyExc_IndexError, "string index out of range");
11637 return NULL;
11638 }
Victor Stinner684d5fd2012-05-03 02:32:34 +020011639 if (start >= length || end < start) {
Victor Stinner3a7f7972012-05-03 03:36:40 +020011640 Py_INCREF(unicode_empty);
11641 return unicode_empty;
Victor Stinner684d5fd2012-05-03 02:32:34 +020011642 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020011643
Victor Stinner684d5fd2012-05-03 02:32:34 +020011644 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011645 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011646 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011647 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011648 }
11649 else {
11650 kind = PyUnicode_KIND(self);
11651 data = PyUnicode_1BYTE_DATA(self);
11652 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011653 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011654 length);
11655 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011656}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011657
11658static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011659do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011660{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011661 int kind;
11662 void *data;
11663 Py_ssize_t len, i, j;
11664
11665 if (PyUnicode_READY(self) == -1)
11666 return NULL;
11667
11668 kind = PyUnicode_KIND(self);
11669 data = PyUnicode_DATA(self);
11670 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011671
Benjamin Peterson14339b62009-01-31 16:36:08 +000011672 i = 0;
11673 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011674 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011675 i++;
11676 }
11677 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011678
Benjamin Peterson14339b62009-01-31 16:36:08 +000011679 j = len;
11680 if (striptype != LEFTSTRIP) {
11681 do {
11682 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011683 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011684 j++;
11685 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011686
Victor Stinner7931d9a2011-11-04 00:22:48 +010011687 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011688}
11689
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011690
11691static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011692do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011693{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011694 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011695
Benjamin Peterson14339b62009-01-31 16:36:08 +000011696 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11697 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011698
Benjamin Peterson14339b62009-01-31 16:36:08 +000011699 if (sep != NULL && sep != Py_None) {
11700 if (PyUnicode_Check(sep))
11701 return _PyUnicode_XStrip(self, striptype, sep);
11702 else {
11703 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011704 "%s arg must be None or str",
11705 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011706 return NULL;
11707 }
11708 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011709
Benjamin Peterson14339b62009-01-31 16:36:08 +000011710 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011711}
11712
11713
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011714PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011715 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011716\n\
11717Return a copy of the string S with leading and trailing\n\
11718whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011719If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011720
11721static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011722unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011723{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011724 if (PyTuple_GET_SIZE(args) == 0)
11725 return do_strip(self, BOTHSTRIP); /* Common case */
11726 else
11727 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011728}
11729
11730
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011731PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011732 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011733\n\
11734Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011735If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011736
11737static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011738unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011739{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011740 if (PyTuple_GET_SIZE(args) == 0)
11741 return do_strip(self, LEFTSTRIP); /* Common case */
11742 else
11743 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011744}
11745
11746
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011747PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011748 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011749\n\
11750Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011751If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011752
11753static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011754unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011755{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011756 if (PyTuple_GET_SIZE(args) == 0)
11757 return do_strip(self, RIGHTSTRIP); /* Common case */
11758 else
11759 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011760}
11761
11762
Guido van Rossumd57fd912000-03-10 22:53:23 +000011763static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011764unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011765{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011766 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011767 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011768
Georg Brandl222de0f2009-04-12 12:01:50 +000011769 if (len < 1) {
11770 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011771 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011772 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011773
Victor Stinnerc4b49542011-12-11 22:44:26 +010011774 /* no repeat, return original string */
11775 if (len == 1)
11776 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011777
Benjamin Petersonbac79492012-01-14 13:34:47 -050011778 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011779 return NULL;
11780
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011781 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011782 PyErr_SetString(PyExc_OverflowError,
11783 "repeated string is too long");
11784 return NULL;
11785 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011786 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011787
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011788 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011789 if (!u)
11790 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011791 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011792
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011793 if (PyUnicode_GET_LENGTH(str) == 1) {
11794 const int kind = PyUnicode_KIND(str);
11795 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011796 if (kind == PyUnicode_1BYTE_KIND) {
11797 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011798 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011799 }
11800 else if (kind == PyUnicode_2BYTE_KIND) {
11801 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011802 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011803 ucs2[n] = fill_char;
11804 } else {
11805 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11806 assert(kind == PyUnicode_4BYTE_KIND);
11807 for (n = 0; n < len; ++n)
11808 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011809 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011810 }
11811 else {
11812 /* number of characters copied this far */
11813 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011814 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011815 char *to = (char *) PyUnicode_DATA(u);
11816 Py_MEMCPY(to, PyUnicode_DATA(str),
11817 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011818 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011819 n = (done <= nchars-done) ? done : nchars-done;
11820 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011821 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011822 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011823 }
11824
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011825 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011826 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011827}
11828
Alexander Belopolsky40018472011-02-26 01:02:56 +000011829PyObject *
11830PyUnicode_Replace(PyObject *obj,
11831 PyObject *subobj,
11832 PyObject *replobj,
11833 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011834{
11835 PyObject *self;
11836 PyObject *str1;
11837 PyObject *str2;
11838 PyObject *result;
11839
11840 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011841 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011842 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011843 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011844 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011845 Py_DECREF(self);
11846 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011847 }
11848 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011849 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011850 Py_DECREF(self);
11851 Py_DECREF(str1);
11852 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011853 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011854 if (PyUnicode_READY(self) == -1 ||
11855 PyUnicode_READY(str1) == -1 ||
11856 PyUnicode_READY(str2) == -1)
11857 result = NULL;
11858 else
11859 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860 Py_DECREF(self);
11861 Py_DECREF(str1);
11862 Py_DECREF(str2);
11863 return result;
11864}
11865
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011866PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011867 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011868\n\
11869Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011870old replaced by new. If the optional argument count is\n\
11871given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011872
11873static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011874unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011875{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011876 PyObject *str1;
11877 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011878 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011879 PyObject *result;
11880
Martin v. Löwis18e16552006-02-15 17:27:45 +000011881 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011882 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060011883 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011884 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011885 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011886 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011887 return NULL;
11888 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011889 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011890 Py_DECREF(str1);
11891 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011892 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011893 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
11894 result = NULL;
11895 else
11896 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011897
11898 Py_DECREF(str1);
11899 Py_DECREF(str2);
11900 return result;
11901}
11902
Alexander Belopolsky40018472011-02-26 01:02:56 +000011903static PyObject *
11904unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011905{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011906 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907 Py_ssize_t isize;
11908 Py_ssize_t osize, squote, dquote, i, o;
11909 Py_UCS4 max, quote;
11910 int ikind, okind;
11911 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011912
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011913 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011914 return NULL;
11915
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011916 isize = PyUnicode_GET_LENGTH(unicode);
11917 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011918
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011919 /* Compute length of output, quote characters, and
11920 maximum character */
11921 osize = 2; /* quotes */
11922 max = 127;
11923 squote = dquote = 0;
11924 ikind = PyUnicode_KIND(unicode);
11925 for (i = 0; i < isize; i++) {
11926 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11927 switch (ch) {
11928 case '\'': squote++; osize++; break;
11929 case '"': dquote++; osize++; break;
11930 case '\\': case '\t': case '\r': case '\n':
11931 osize += 2; break;
11932 default:
11933 /* Fast-path ASCII */
11934 if (ch < ' ' || ch == 0x7f)
11935 osize += 4; /* \xHH */
11936 else if (ch < 0x7f)
11937 osize++;
11938 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11939 osize++;
11940 max = ch > max ? ch : max;
11941 }
11942 else if (ch < 0x100)
11943 osize += 4; /* \xHH */
11944 else if (ch < 0x10000)
11945 osize += 6; /* \uHHHH */
11946 else
11947 osize += 10; /* \uHHHHHHHH */
11948 }
11949 }
11950
11951 quote = '\'';
11952 if (squote) {
11953 if (dquote)
11954 /* Both squote and dquote present. Use squote,
11955 and escape them */
11956 osize += squote;
11957 else
11958 quote = '"';
11959 }
11960
11961 repr = PyUnicode_New(osize, max);
11962 if (repr == NULL)
11963 return NULL;
11964 okind = PyUnicode_KIND(repr);
11965 odata = PyUnicode_DATA(repr);
11966
11967 PyUnicode_WRITE(okind, odata, 0, quote);
11968 PyUnicode_WRITE(okind, odata, osize-1, quote);
11969
11970 for (i = 0, o = 1; i < isize; i++) {
11971 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011972
11973 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011974 if ((ch == quote) || (ch == '\\')) {
11975 PyUnicode_WRITE(okind, odata, o++, '\\');
11976 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011977 continue;
11978 }
11979
Benjamin Peterson29060642009-01-31 22:14:21 +000011980 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011981 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011982 PyUnicode_WRITE(okind, odata, o++, '\\');
11983 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011984 }
11985 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011986 PyUnicode_WRITE(okind, odata, o++, '\\');
11987 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011988 }
11989 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011990 PyUnicode_WRITE(okind, odata, o++, '\\');
11991 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011992 }
11993
11994 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011995 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011996 PyUnicode_WRITE(okind, odata, o++, '\\');
11997 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020011998 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
11999 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012000 }
12001
Georg Brandl559e5d72008-06-11 18:37:52 +000012002 /* Copy ASCII characters as-is */
12003 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012004 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012005 }
12006
Benjamin Peterson29060642009-01-31 22:14:21 +000012007 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012008 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012009 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012010 (categories Z* and C* except ASCII space)
12011 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012012 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012013 PyUnicode_WRITE(okind, odata, o++, '\\');
Georg Brandl559e5d72008-06-11 18:37:52 +000012014 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012015 if (ch <= 0xff) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012016 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012017 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12018 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012019 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012020 /* Map 16-bit characters to '\uxxxx' */
12021 else if (ch <= 0xffff) {
12022 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012023 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12024 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12025 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12026 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012027 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012028 /* Map 21-bit characters to '\U00xxxxxx' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012029 else {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012030 PyUnicode_WRITE(okind, odata, o++, 'U');
12031 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12032 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12033 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12034 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
Victor Stinnerf5cff562011-10-14 02:13:11 +020012035 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12036 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12037 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12038 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012039 }
12040 }
12041 /* Copy characters as-is */
12042 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012043 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012044 }
12045 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012046 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012047 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012048 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012049 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012050}
12051
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012052PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012053 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012054\n\
12055Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012056such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012057arguments start and end are interpreted as in slice notation.\n\
12058\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012059Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012060
12061static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012062unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012063{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012064 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012065 Py_ssize_t start;
12066 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012067 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012068
Jesus Ceaac451502011-04-20 17:09:23 +020012069 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12070 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012071 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012072
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012073 if (PyUnicode_READY(self) == -1)
12074 return NULL;
12075 if (PyUnicode_READY(substring) == -1)
12076 return NULL;
12077
Victor Stinner7931d9a2011-11-04 00:22:48 +010012078 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012079
12080 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012081
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012082 if (result == -2)
12083 return NULL;
12084
Christian Heimes217cfd12007-12-02 14:31:20 +000012085 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012086}
12087
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012088PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012089 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012090\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012091Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012092
12093static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012094unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012095{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012096 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012097 Py_ssize_t start;
12098 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012099 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012100
Jesus Ceaac451502011-04-20 17:09:23 +020012101 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12102 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012103 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012105 if (PyUnicode_READY(self) == -1)
12106 return NULL;
12107 if (PyUnicode_READY(substring) == -1)
12108 return NULL;
12109
Victor Stinner7931d9a2011-11-04 00:22:48 +010012110 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012111
12112 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012113
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012114 if (result == -2)
12115 return NULL;
12116
Guido van Rossumd57fd912000-03-10 22:53:23 +000012117 if (result < 0) {
12118 PyErr_SetString(PyExc_ValueError, "substring not found");
12119 return NULL;
12120 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012121
Christian Heimes217cfd12007-12-02 14:31:20 +000012122 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012123}
12124
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012125PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012126 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012127\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012128Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012129done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012130
12131static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012132unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012133{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012134 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012135 Py_UCS4 fillchar = ' ';
12136
Victor Stinnere9a29352011-10-01 02:14:59 +020012137 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012138 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012139
Benjamin Petersonbac79492012-01-14 13:34:47 -050012140 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012141 return NULL;
12142
Victor Stinnerc4b49542011-12-11 22:44:26 +010012143 if (PyUnicode_GET_LENGTH(self) >= width)
12144 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012145
Victor Stinnerc4b49542011-12-11 22:44:26 +010012146 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012147}
12148
Alexander Belopolsky40018472011-02-26 01:02:56 +000012149PyObject *
12150PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012151{
12152 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012153
Guido van Rossumd57fd912000-03-10 22:53:23 +000012154 s = PyUnicode_FromObject(s);
12155 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012156 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012157 if (sep != NULL) {
12158 sep = PyUnicode_FromObject(sep);
12159 if (sep == NULL) {
12160 Py_DECREF(s);
12161 return NULL;
12162 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012163 }
12164
Victor Stinner9310abb2011-10-05 00:59:23 +020012165 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012166
12167 Py_DECREF(s);
12168 Py_XDECREF(sep);
12169 return result;
12170}
12171
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012172PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012173 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012174\n\
12175Return a list of the words in S, using sep as the\n\
12176delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012177splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012178whitespace string is a separator and empty strings are\n\
12179removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012180
12181static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012182unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012183{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012184 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012185 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012186 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012187
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012188 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12189 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012190 return NULL;
12191
12192 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012193 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012194 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012195 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012196 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012197 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012198}
12199
Thomas Wouters477c8d52006-05-27 19:21:47 +000012200PyObject *
12201PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12202{
12203 PyObject* str_obj;
12204 PyObject* sep_obj;
12205 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012206 int kind1, kind2, kind;
12207 void *buf1 = NULL, *buf2 = NULL;
12208 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012209
12210 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012211 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012212 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012213 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012214 if (!sep_obj) {
12215 Py_DECREF(str_obj);
12216 return NULL;
12217 }
12218 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12219 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012220 Py_DECREF(str_obj);
12221 return NULL;
12222 }
12223
Victor Stinner14f8f022011-10-05 20:58:25 +020012224 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012225 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012226 kind = Py_MAX(kind1, kind2);
12227 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012228 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012229 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012230 if (!buf1)
12231 goto onError;
12232 buf2 = PyUnicode_DATA(sep_obj);
12233 if (kind2 != kind)
12234 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12235 if (!buf2)
12236 goto onError;
12237 len1 = PyUnicode_GET_LENGTH(str_obj);
12238 len2 = PyUnicode_GET_LENGTH(sep_obj);
12239
Benjamin Petersonead6b532011-12-20 17:23:42 -060012240 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012241 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012242 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12243 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12244 else
12245 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012246 break;
12247 case PyUnicode_2BYTE_KIND:
12248 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12249 break;
12250 case PyUnicode_4BYTE_KIND:
12251 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12252 break;
12253 default:
12254 assert(0);
12255 out = 0;
12256 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012257
12258 Py_DECREF(sep_obj);
12259 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012260 if (kind1 != kind)
12261 PyMem_Free(buf1);
12262 if (kind2 != kind)
12263 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012264
12265 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012266 onError:
12267 Py_DECREF(sep_obj);
12268 Py_DECREF(str_obj);
12269 if (kind1 != kind && buf1)
12270 PyMem_Free(buf1);
12271 if (kind2 != kind && buf2)
12272 PyMem_Free(buf2);
12273 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012274}
12275
12276
12277PyObject *
12278PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12279{
12280 PyObject* str_obj;
12281 PyObject* sep_obj;
12282 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012283 int kind1, kind2, kind;
12284 void *buf1 = NULL, *buf2 = NULL;
12285 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012286
12287 str_obj = PyUnicode_FromObject(str_in);
12288 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012289 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012290 sep_obj = PyUnicode_FromObject(sep_in);
12291 if (!sep_obj) {
12292 Py_DECREF(str_obj);
12293 return NULL;
12294 }
12295
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012296 kind1 = PyUnicode_KIND(str_in);
12297 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012298 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012299 buf1 = PyUnicode_DATA(str_in);
12300 if (kind1 != kind)
12301 buf1 = _PyUnicode_AsKind(str_in, kind);
12302 if (!buf1)
12303 goto onError;
12304 buf2 = PyUnicode_DATA(sep_obj);
12305 if (kind2 != kind)
12306 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12307 if (!buf2)
12308 goto onError;
12309 len1 = PyUnicode_GET_LENGTH(str_obj);
12310 len2 = PyUnicode_GET_LENGTH(sep_obj);
12311
Benjamin Petersonead6b532011-12-20 17:23:42 -060012312 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012313 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012314 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12315 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12316 else
12317 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012318 break;
12319 case PyUnicode_2BYTE_KIND:
12320 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12321 break;
12322 case PyUnicode_4BYTE_KIND:
12323 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12324 break;
12325 default:
12326 assert(0);
12327 out = 0;
12328 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012329
12330 Py_DECREF(sep_obj);
12331 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012332 if (kind1 != kind)
12333 PyMem_Free(buf1);
12334 if (kind2 != kind)
12335 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012336
12337 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012338 onError:
12339 Py_DECREF(sep_obj);
12340 Py_DECREF(str_obj);
12341 if (kind1 != kind && buf1)
12342 PyMem_Free(buf1);
12343 if (kind2 != kind && buf2)
12344 PyMem_Free(buf2);
12345 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012346}
12347
12348PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012349 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012350\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012351Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012352the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012353found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012354
12355static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012356unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012357{
Victor Stinner9310abb2011-10-05 00:59:23 +020012358 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012359}
12360
12361PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012362 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012363\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012364Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012365the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012366separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012367
12368static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012369unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012370{
Victor Stinner9310abb2011-10-05 00:59:23 +020012371 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012372}
12373
Alexander Belopolsky40018472011-02-26 01:02:56 +000012374PyObject *
12375PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012376{
12377 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012378
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012379 s = PyUnicode_FromObject(s);
12380 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012381 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012382 if (sep != NULL) {
12383 sep = PyUnicode_FromObject(sep);
12384 if (sep == NULL) {
12385 Py_DECREF(s);
12386 return NULL;
12387 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012388 }
12389
Victor Stinner9310abb2011-10-05 00:59:23 +020012390 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012391
12392 Py_DECREF(s);
12393 Py_XDECREF(sep);
12394 return result;
12395}
12396
12397PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012398 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012399\n\
12400Return a list of the words in S, using sep as the\n\
12401delimiter string, starting at the end of the string and\n\
12402working to the front. If maxsplit is given, at most maxsplit\n\
12403splits are done. If sep is not specified, any whitespace string\n\
12404is a separator.");
12405
12406static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012407unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012408{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012409 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012410 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012411 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012412
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012413 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12414 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012415 return NULL;
12416
12417 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012418 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012419 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012420 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012421 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012422 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012423}
12424
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012425PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012426 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012427\n\
12428Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012429Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012430is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012431
12432static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012433unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012434{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012435 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012436 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012437
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012438 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12439 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012440 return NULL;
12441
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012442 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012443}
12444
12445static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012446PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012447{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012448 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012449}
12450
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012451PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012452 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012453\n\
12454Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012455and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012456
12457static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012458unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012459{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012460 if (PyUnicode_READY(self) == -1)
12461 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012462 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012463}
12464
Georg Brandlceee0772007-11-27 23:48:05 +000012465PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012466 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012467\n\
12468Return a translation table usable for str.translate().\n\
12469If there is only one argument, it must be a dictionary mapping Unicode\n\
12470ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012471Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012472If there are two arguments, they must be strings of equal length, and\n\
12473in the resulting dictionary, each character in x will be mapped to the\n\
12474character at the same position in y. If there is a third argument, it\n\
12475must be a string, whose characters will be mapped to None in the result.");
12476
12477static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012478unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012479{
12480 PyObject *x, *y = NULL, *z = NULL;
12481 PyObject *new = NULL, *key, *value;
12482 Py_ssize_t i = 0;
12483 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012484
Georg Brandlceee0772007-11-27 23:48:05 +000012485 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12486 return NULL;
12487 new = PyDict_New();
12488 if (!new)
12489 return NULL;
12490 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012491 int x_kind, y_kind, z_kind;
12492 void *x_data, *y_data, *z_data;
12493
Georg Brandlceee0772007-11-27 23:48:05 +000012494 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012495 if (!PyUnicode_Check(x)) {
12496 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12497 "be a string if there is a second argument");
12498 goto err;
12499 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012500 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012501 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12502 "arguments must have equal length");
12503 goto err;
12504 }
12505 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012506 x_kind = PyUnicode_KIND(x);
12507 y_kind = PyUnicode_KIND(y);
12508 x_data = PyUnicode_DATA(x);
12509 y_data = PyUnicode_DATA(y);
12510 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12511 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012512 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012513 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012514 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012515 if (!value) {
12516 Py_DECREF(key);
12517 goto err;
12518 }
Georg Brandlceee0772007-11-27 23:48:05 +000012519 res = PyDict_SetItem(new, key, value);
12520 Py_DECREF(key);
12521 Py_DECREF(value);
12522 if (res < 0)
12523 goto err;
12524 }
12525 /* create entries for deleting chars in z */
12526 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012527 z_kind = PyUnicode_KIND(z);
12528 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012529 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012530 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012531 if (!key)
12532 goto err;
12533 res = PyDict_SetItem(new, key, Py_None);
12534 Py_DECREF(key);
12535 if (res < 0)
12536 goto err;
12537 }
12538 }
12539 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012540 int kind;
12541 void *data;
12542
Georg Brandlceee0772007-11-27 23:48:05 +000012543 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012544 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012545 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12546 "to maketrans it must be a dict");
12547 goto err;
12548 }
12549 /* copy entries into the new dict, converting string keys to int keys */
12550 while (PyDict_Next(x, &i, &key, &value)) {
12551 if (PyUnicode_Check(key)) {
12552 /* convert string keys to integer keys */
12553 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012554 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012555 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12556 "table must be of length 1");
12557 goto err;
12558 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012559 kind = PyUnicode_KIND(key);
12560 data = PyUnicode_DATA(key);
12561 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012562 if (!newkey)
12563 goto err;
12564 res = PyDict_SetItem(new, newkey, value);
12565 Py_DECREF(newkey);
12566 if (res < 0)
12567 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012568 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012569 /* just keep integer keys */
12570 if (PyDict_SetItem(new, key, value) < 0)
12571 goto err;
12572 } else {
12573 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12574 "be strings or integers");
12575 goto err;
12576 }
12577 }
12578 }
12579 return new;
12580 err:
12581 Py_DECREF(new);
12582 return NULL;
12583}
12584
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012585PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012586 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012587\n\
12588Return a copy of the string S, where all characters have been mapped\n\
12589through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012590Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012591Unmapped characters are left untouched. Characters mapped to None\n\
12592are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012593
12594static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012595unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012596{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012597 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012598}
12599
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012600PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012601 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012602\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012603Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012604
12605static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012606unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012607{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012608 if (PyUnicode_READY(self) == -1)
12609 return NULL;
12610 if (PyUnicode_IS_ASCII(self))
12611 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012612 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012613}
12614
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012615PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012616 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012617\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012618Pad a numeric string S with zeros on the left, to fill a field\n\
12619of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012620
12621static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012622unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012623{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012624 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012625 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012626 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012627 int kind;
12628 void *data;
12629 Py_UCS4 chr;
12630
Martin v. Löwis18e16552006-02-15 17:27:45 +000012631 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012632 return NULL;
12633
Benjamin Petersonbac79492012-01-14 13:34:47 -050012634 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012635 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012636
Victor Stinnerc4b49542011-12-11 22:44:26 +010012637 if (PyUnicode_GET_LENGTH(self) >= width)
12638 return unicode_result_unchanged(self);
12639
12640 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012641
12642 u = pad(self, fill, 0, '0');
12643
Walter Dörwald068325e2002-04-15 13:36:47 +000012644 if (u == NULL)
12645 return NULL;
12646
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012647 kind = PyUnicode_KIND(u);
12648 data = PyUnicode_DATA(u);
12649 chr = PyUnicode_READ(kind, data, fill);
12650
12651 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012652 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012653 PyUnicode_WRITE(kind, data, 0, chr);
12654 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012655 }
12656
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012657 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012658 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012659}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012660
12661#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012662static PyObject *
12663unicode__decimal2ascii(PyObject *self)
12664{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012665 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012666}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012667#endif
12668
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012669PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012670 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012671\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012672Return True if S starts with the specified prefix, False otherwise.\n\
12673With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012674With optional end, stop comparing S at that position.\n\
12675prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012676
12677static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012678unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012679 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012680{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012681 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012682 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012683 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012684 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012685 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012686
Jesus Ceaac451502011-04-20 17:09:23 +020012687 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012688 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012689 if (PyTuple_Check(subobj)) {
12690 Py_ssize_t i;
12691 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012692 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012693 if (substring == NULL)
12694 return NULL;
12695 result = tailmatch(self, substring, start, end, -1);
12696 Py_DECREF(substring);
12697 if (result) {
12698 Py_RETURN_TRUE;
12699 }
12700 }
12701 /* nothing matched */
12702 Py_RETURN_FALSE;
12703 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012704 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012705 if (substring == NULL) {
12706 if (PyErr_ExceptionMatches(PyExc_TypeError))
12707 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12708 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012709 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012710 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012711 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012712 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012713 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012714}
12715
12716
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012717PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012718 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012719\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012720Return True if S ends with the specified suffix, False otherwise.\n\
12721With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012722With optional end, stop comparing S at that position.\n\
12723suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012724
12725static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012726unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012727 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012728{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012729 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012730 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012731 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012732 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012733 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012734
Jesus Ceaac451502011-04-20 17:09:23 +020012735 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012736 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012737 if (PyTuple_Check(subobj)) {
12738 Py_ssize_t i;
12739 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012740 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012741 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012742 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012743 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012744 result = tailmatch(self, substring, start, end, +1);
12745 Py_DECREF(substring);
12746 if (result) {
12747 Py_RETURN_TRUE;
12748 }
12749 }
12750 Py_RETURN_FALSE;
12751 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012752 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012753 if (substring == NULL) {
12754 if (PyErr_ExceptionMatches(PyExc_TypeError))
12755 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12756 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012757 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012758 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012759 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012760 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012761 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012762}
12763
Victor Stinner202fdca2012-05-07 12:47:02 +020012764Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012765_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012766{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012767 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012768 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
12769 writer->data = PyUnicode_DATA(writer->buffer);
12770 writer->kind = PyUnicode_KIND(writer->buffer);
12771}
12772
Victor Stinnerd3f08822012-05-29 12:57:52 +020012773void
12774_PyUnicodeWriter_Init(_PyUnicodeWriter *writer, Py_ssize_t min_length)
Victor Stinner202fdca2012-05-07 12:47:02 +020012775{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012776 memset(writer, 0, sizeof(*writer));
12777#ifdef Py_DEBUG
12778 writer->kind = 5; /* invalid kind */
12779#endif
12780 writer->min_length = Py_MAX(min_length, 100);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012781 writer->overallocate = (min_length > 0);
Victor Stinner202fdca2012-05-07 12:47:02 +020012782}
12783
Victor Stinnerd3f08822012-05-29 12:57:52 +020012784int
12785_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
12786 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020012787{
12788 Py_ssize_t newlen;
12789 PyObject *newbuffer;
12790
Victor Stinnerd3f08822012-05-29 12:57:52 +020012791 assert(length > 0);
12792
Victor Stinner202fdca2012-05-07 12:47:02 +020012793 if (length > PY_SSIZE_T_MAX - writer->pos) {
12794 PyErr_NoMemory();
12795 return -1;
12796 }
12797 newlen = writer->pos + length;
12798
Victor Stinnerd3f08822012-05-29 12:57:52 +020012799 if (writer->buffer == NULL) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012800 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012801 /* overallocate 25% to limit the number of resize */
12802 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12803 newlen += newlen / 4;
12804 if (newlen < writer->min_length)
12805 newlen = writer->min_length;
12806 }
12807 writer->buffer = PyUnicode_New(newlen, maxchar);
12808 if (writer->buffer == NULL)
12809 return -1;
12810 _PyUnicodeWriter_Update(writer);
12811 return 0;
12812 }
Victor Stinner202fdca2012-05-07 12:47:02 +020012813
Victor Stinnerd3f08822012-05-29 12:57:52 +020012814 if (newlen > writer->size) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012815 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012816 /* overallocate 25% to limit the number of resize */
12817 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12818 newlen += newlen / 4;
12819 if (newlen < writer->min_length)
12820 newlen = writer->min_length;
12821 }
12822
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012823 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020012824 /* resize + widen */
12825 newbuffer = PyUnicode_New(newlen, maxchar);
12826 if (newbuffer == NULL)
12827 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012828 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12829 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020012830 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012831 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020012832 }
12833 else {
12834 newbuffer = resize_compact(writer->buffer, newlen);
12835 if (newbuffer == NULL)
12836 return -1;
12837 }
12838 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012839 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012840 }
12841 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012842 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012843 newbuffer = PyUnicode_New(writer->size, maxchar);
12844 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020012845 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012846 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12847 writer->buffer, 0, writer->pos);
12848 Py_DECREF(writer->buffer);
12849 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012850 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012851 }
12852 return 0;
12853}
12854
Victor Stinnerd3f08822012-05-29 12:57:52 +020012855int
12856_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
12857{
12858 Py_UCS4 maxchar;
12859 Py_ssize_t len;
12860
12861 if (PyUnicode_READY(str) == -1)
12862 return -1;
12863 len = PyUnicode_GET_LENGTH(str);
12864 if (len == 0)
12865 return 0;
12866 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
12867 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012868 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012869 Py_INCREF(str);
12870 writer->buffer = str;
12871 _PyUnicodeWriter_Update(writer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012872 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012873 writer->size = 0;
12874 writer->pos += len;
12875 return 0;
12876 }
12877 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
12878 return -1;
12879 }
12880 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
12881 str, 0, len);
12882 writer->pos += len;
12883 return 0;
12884}
12885
12886PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012887_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012888{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012889 if (writer->pos == 0) {
12890 Py_XDECREF(writer->buffer);
12891 Py_INCREF(unicode_empty);
12892 return unicode_empty;
12893 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012894 if (writer->readonly) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012895 assert(PyUnicode_GET_LENGTH(writer->buffer) == writer->pos);
12896 return writer->buffer;
12897 }
12898 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
12899 PyObject *newbuffer;
12900 newbuffer = resize_compact(writer->buffer, writer->pos);
12901 if (newbuffer == NULL) {
12902 Py_DECREF(writer->buffer);
12903 return NULL;
12904 }
12905 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020012906 }
Victor Stinnerf59c28c2012-05-09 03:24:14 +020012907 assert(_PyUnicode_CheckConsistency(writer->buffer, 1));
Victor Stinner202fdca2012-05-07 12:47:02 +020012908 return writer->buffer;
12909}
12910
Victor Stinnerd3f08822012-05-29 12:57:52 +020012911void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012912_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012913{
12914 Py_CLEAR(writer->buffer);
12915}
12916
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012917#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012918
12919PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012920 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012921\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012922Return a formatted version of S, using substitutions from args and kwargs.\n\
12923The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012924
Eric Smith27bbca62010-11-04 17:06:58 +000012925PyDoc_STRVAR(format_map__doc__,
12926 "S.format_map(mapping) -> str\n\
12927\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012928Return a formatted version of S, using substitutions from mapping.\n\
12929The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012930
Eric Smith4a7d76d2008-05-30 18:10:19 +000012931static PyObject *
12932unicode__format__(PyObject* self, PyObject* args)
12933{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012934 PyObject *format_spec;
12935 _PyUnicodeWriter writer;
12936 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012937
12938 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12939 return NULL;
12940
Victor Stinnerd3f08822012-05-29 12:57:52 +020012941 if (PyUnicode_READY(self) == -1)
12942 return NULL;
12943 _PyUnicodeWriter_Init(&writer, 0);
12944 ret = _PyUnicode_FormatAdvancedWriter(&writer,
12945 self, format_spec, 0,
12946 PyUnicode_GET_LENGTH(format_spec));
12947 if (ret == -1) {
12948 _PyUnicodeWriter_Dealloc(&writer);
12949 return NULL;
12950 }
12951 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000012952}
12953
Eric Smith8c663262007-08-25 02:26:07 +000012954PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012955 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012956\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012957Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012958
12959static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012960unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012961{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012962 Py_ssize_t size;
12963
12964 /* If it's a compact object, account for base structure +
12965 character data. */
12966 if (PyUnicode_IS_COMPACT_ASCII(v))
12967 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12968 else if (PyUnicode_IS_COMPACT(v))
12969 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012970 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012971 else {
12972 /* If it is a two-block object, account for base object, and
12973 for character block if present. */
12974 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012975 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012976 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012977 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012978 }
12979 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012980 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012981 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012982 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012983 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012984 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012985
12986 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012987}
12988
12989PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012990 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012991
12992static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012993unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012994{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010012995 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012996 if (!copy)
12997 return NULL;
12998 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012999}
13000
Guido van Rossumd57fd912000-03-10 22:53:23 +000013001static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013002 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013003 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013004 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13005 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013006 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13007 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013008 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013009 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13010 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13011 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13012 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13013 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013014 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013015 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13016 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13017 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013018 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013019 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13020 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13021 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013022 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013023 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013024 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013025 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013026 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13027 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13028 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13029 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13030 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13031 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13032 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13033 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13034 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13035 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13036 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13037 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13038 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13039 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013040 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013041 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013042 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013043 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013044 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013045 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013046 {"maketrans", (PyCFunction) unicode_maketrans,
13047 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013048 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013049#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013050 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013051 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013052#endif
13053
Benjamin Peterson14339b62009-01-31 16:36:08 +000013054 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013055 {NULL, NULL}
13056};
13057
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013058static PyObject *
13059unicode_mod(PyObject *v, PyObject *w)
13060{
Brian Curtindfc80e32011-08-10 20:28:54 -050013061 if (!PyUnicode_Check(v))
13062 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013063 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013064}
13065
13066static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013067 0, /*nb_add*/
13068 0, /*nb_subtract*/
13069 0, /*nb_multiply*/
13070 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013071};
13072
Guido van Rossumd57fd912000-03-10 22:53:23 +000013073static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013074 (lenfunc) unicode_length, /* sq_length */
13075 PyUnicode_Concat, /* sq_concat */
13076 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13077 (ssizeargfunc) unicode_getitem, /* sq_item */
13078 0, /* sq_slice */
13079 0, /* sq_ass_item */
13080 0, /* sq_ass_slice */
13081 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013082};
13083
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013084static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013085unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013086{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013087 if (PyUnicode_READY(self) == -1)
13088 return NULL;
13089
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013090 if (PyIndex_Check(item)) {
13091 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013092 if (i == -1 && PyErr_Occurred())
13093 return NULL;
13094 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013095 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013096 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013097 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013098 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013099 PyObject *result;
13100 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013101 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013102 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013104 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013105 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013106 return NULL;
13107 }
13108
13109 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013110 Py_INCREF(unicode_empty);
13111 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013112 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013113 slicelength == PyUnicode_GET_LENGTH(self)) {
13114 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013115 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013116 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013117 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013118 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013119 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013120 src_kind = PyUnicode_KIND(self);
13121 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013122 if (!PyUnicode_IS_ASCII(self)) {
13123 kind_limit = kind_maxchar_limit(src_kind);
13124 max_char = 0;
13125 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13126 ch = PyUnicode_READ(src_kind, src_data, cur);
13127 if (ch > max_char) {
13128 max_char = ch;
13129 if (max_char >= kind_limit)
13130 break;
13131 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013132 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013133 }
Victor Stinner55c99112011-10-13 01:17:06 +020013134 else
13135 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013136 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013137 if (result == NULL)
13138 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013139 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013140 dest_data = PyUnicode_DATA(result);
13141
13142 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013143 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13144 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013145 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013146 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013147 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013148 } else {
13149 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13150 return NULL;
13151 }
13152}
13153
13154static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013155 (lenfunc)unicode_length, /* mp_length */
13156 (binaryfunc)unicode_subscript, /* mp_subscript */
13157 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013158};
13159
Guido van Rossumd57fd912000-03-10 22:53:23 +000013160
Guido van Rossumd57fd912000-03-10 22:53:23 +000013161/* Helpers for PyUnicode_Format() */
13162
13163static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013164getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013165{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013166 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013167 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013168 (*p_argidx)++;
13169 if (arglen < 0)
13170 return args;
13171 else
13172 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013173 }
13174 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013175 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013176 return NULL;
13177}
13178
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013179/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013180
Victor Stinnerd3f08822012-05-29 12:57:52 +020013181static int
13182formatfloat(PyObject *v, int flags, int prec, int type,
13183 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013184{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013185 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013186 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013187 Py_ssize_t len;
Tim Petersced69f82003-09-16 20:30:58 +000013188
Guido van Rossumd57fd912000-03-10 22:53:23 +000013189 x = PyFloat_AsDouble(v);
13190 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013191 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013192
Guido van Rossumd57fd912000-03-10 22:53:23 +000013193 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013194 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013195
Eric Smith0923d1d2009-04-16 20:16:10 +000013196 p = PyOS_double_to_string(x, type, prec,
13197 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013198 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013199 return -1;
13200 len = strlen(p);
13201 if (writer) {
13202 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13203 return -1;
Victor Stinner3a7d0962012-05-29 18:53:56 +020013204 memcpy((char*)writer->data + writer->pos * writer->kind,
Victor Stinnerd3f08822012-05-29 12:57:52 +020013205 p,
13206 len);
13207 writer->pos += len;
13208 }
13209 else
13210 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013211 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013212 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013213}
13214
Victor Stinnerd0880d52012-04-27 23:40:13 +020013215/* formatlong() emulates the format codes d, u, o, x and X, and
13216 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13217 * Python's regular ints.
13218 * Return value: a new PyUnicodeObject*, or NULL if error.
13219 * The output string is of the form
13220 * "-"? ("0x" | "0X")? digit+
13221 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13222 * set in flags. The case of hex digits will be correct,
13223 * There will be at least prec digits, zero-filled on the left if
13224 * necessary to get that many.
13225 * val object to be converted
13226 * flags bitmask of format flags; only F_ALT is looked at
13227 * prec minimum number of digits; 0-fill on left if needed
13228 * type a character in [duoxX]; u acts the same as d
13229 *
13230 * CAUTION: o, x and X conversions on regular ints can never
13231 * produce a '-' sign, but can for Python's unbounded ints.
13232 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013233static PyObject*
13234formatlong(PyObject *val, int flags, int prec, int type)
13235{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013236 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013237 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013238 Py_ssize_t i;
13239 int sign; /* 1 if '-', else 0 */
13240 int len; /* number of characters */
13241 Py_ssize_t llen;
13242 int numdigits; /* len == numnondigits + numdigits */
13243 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013244
Victor Stinnerd0880d52012-04-27 23:40:13 +020013245 /* Avoid exceeding SSIZE_T_MAX */
13246 if (prec > INT_MAX-3) {
13247 PyErr_SetString(PyExc_OverflowError,
13248 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013249 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013250 }
13251
13252 assert(PyLong_Check(val));
13253
13254 switch (type) {
13255 case 'd':
13256 case 'u':
13257 /* Special-case boolean: we want 0/1 */
Victor Stinnerb11d91d2012-04-28 00:25:34 +020013258 if (PyBool_Check(val))
13259 result = PyNumber_ToBase(val, 10);
13260 else
13261 result = Py_TYPE(val)->tp_str(val);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013262 break;
13263 case 'o':
13264 numnondigits = 2;
13265 result = PyNumber_ToBase(val, 8);
13266 break;
13267 case 'x':
13268 case 'X':
13269 numnondigits = 2;
13270 result = PyNumber_ToBase(val, 16);
13271 break;
13272 default:
13273 assert(!"'type' not in [duoxX]");
13274 }
13275 if (!result)
13276 return NULL;
13277
13278 assert(unicode_modifiable(result));
13279 assert(PyUnicode_IS_READY(result));
13280 assert(PyUnicode_IS_ASCII(result));
13281
13282 /* To modify the string in-place, there can only be one reference. */
13283 if (Py_REFCNT(result) != 1) {
13284 PyErr_BadInternalCall();
13285 return NULL;
13286 }
13287 buf = PyUnicode_DATA(result);
13288 llen = PyUnicode_GET_LENGTH(result);
13289 if (llen > INT_MAX) {
13290 PyErr_SetString(PyExc_ValueError,
13291 "string too large in _PyBytes_FormatLong");
13292 return NULL;
13293 }
13294 len = (int)llen;
13295 sign = buf[0] == '-';
13296 numnondigits += sign;
13297 numdigits = len - numnondigits;
13298 assert(numdigits > 0);
13299
13300 /* Get rid of base marker unless F_ALT */
13301 if (((flags & F_ALT) == 0 &&
13302 (type == 'o' || type == 'x' || type == 'X'))) {
13303 assert(buf[sign] == '0');
13304 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13305 buf[sign+1] == 'o');
13306 numnondigits -= 2;
13307 buf += 2;
13308 len -= 2;
13309 if (sign)
13310 buf[0] = '-';
13311 assert(len == numnondigits + numdigits);
13312 assert(numdigits > 0);
13313 }
13314
13315 /* Fill with leading zeroes to meet minimum width. */
13316 if (prec > numdigits) {
13317 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13318 numnondigits + prec);
13319 char *b1;
13320 if (!r1) {
13321 Py_DECREF(result);
13322 return NULL;
13323 }
13324 b1 = PyBytes_AS_STRING(r1);
13325 for (i = 0; i < numnondigits; ++i)
13326 *b1++ = *buf++;
13327 for (i = 0; i < prec - numdigits; i++)
13328 *b1++ = '0';
13329 for (i = 0; i < numdigits; i++)
13330 *b1++ = *buf++;
13331 *b1 = '\0';
13332 Py_DECREF(result);
13333 result = r1;
13334 buf = PyBytes_AS_STRING(result);
13335 len = numnondigits + prec;
13336 }
13337
13338 /* Fix up case for hex conversions. */
13339 if (type == 'X') {
13340 /* Need to convert all lower case letters to upper case.
13341 and need to convert 0x to 0X (and -0x to -0X). */
13342 for (i = 0; i < len; i++)
13343 if (buf[i] >= 'a' && buf[i] <= 'x')
13344 buf[i] -= 'a'-'A';
13345 }
13346 if (!PyUnicode_Check(result) || len != PyUnicode_GET_LENGTH(result)) {
13347 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013348 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013349 Py_DECREF(result);
13350 result = unicode;
13351 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013352 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013353}
13354
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013355static Py_UCS4
13356formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013357{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013358 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013359 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013360 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013361 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013362 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013363 goto onError;
13364 }
13365 else {
13366 /* Integer input truncated to a character */
13367 long x;
13368 x = PyLong_AsLong(v);
13369 if (x == -1 && PyErr_Occurred())
13370 goto onError;
13371
Victor Stinner8faf8212011-12-08 22:14:11 +010013372 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013373 PyErr_SetString(PyExc_OverflowError,
13374 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013375 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013376 }
13377
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013378 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013379 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013380
Benjamin Peterson29060642009-01-31 22:14:21 +000013381 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013382 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013383 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013384 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013385}
13386
Alexander Belopolsky40018472011-02-26 01:02:56 +000013387PyObject *
13388PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013389{
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013390 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013391 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013392 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013393 PyObject *temp = NULL;
13394 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013395 PyObject *uformat;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013396 void *fmt;
13397 enum PyUnicode_Kind kind, fmtkind;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013398 _PyUnicodeWriter writer;
Victor Stinneree4544c2012-05-09 22:24:08 +020013399 Py_ssize_t sublen;
13400 Py_UCS4 maxchar;
Tim Petersced69f82003-09-16 20:30:58 +000013401
Guido van Rossumd57fd912000-03-10 22:53:23 +000013402 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013403 PyErr_BadInternalCall();
13404 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013405 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013406 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013407 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013408 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013409 if (PyUnicode_READY(uformat) == -1)
13410 Py_DECREF(uformat);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013411
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013412 fmt = PyUnicode_DATA(uformat);
13413 fmtkind = PyUnicode_KIND(uformat);
13414 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13415 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013416
Victor Stinnerd3f08822012-05-29 12:57:52 +020013417 _PyUnicodeWriter_Init(&writer, fmtcnt + 100);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013418
Guido van Rossumd57fd912000-03-10 22:53:23 +000013419 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013420 arglen = PyTuple_Size(args);
13421 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013422 }
13423 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013424 arglen = -1;
13425 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013426 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013427 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013428 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013429 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013430
13431 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013432 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013433 Py_ssize_t nonfmtpos;
13434 nonfmtpos = fmtpos++;
13435 while (fmtcnt >= 0 &&
13436 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13437 fmtpos++;
13438 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013439 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013440 if (fmtcnt < 0)
13441 fmtpos--;
Victor Stinneree4544c2012-05-09 22:24:08 +020013442 sublen = fmtpos - nonfmtpos;
13443 maxchar = _PyUnicode_FindMaxChar(uformat,
13444 nonfmtpos, nonfmtpos + sublen);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013445 if (_PyUnicodeWriter_Prepare(&writer, sublen, maxchar) == -1)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013446 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013447
Victor Stinnerd3f08822012-05-29 12:57:52 +020013448 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13449 uformat, nonfmtpos, sublen);
Victor Stinneree4544c2012-05-09 22:24:08 +020013450 writer.pos += sublen;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013451 }
13452 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013453 /* Got a format specifier */
13454 int flags = 0;
13455 Py_ssize_t width = -1;
13456 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013457 Py_UCS4 c = '\0';
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013458 Py_UCS4 fill;
13459 int sign;
13460 Py_UCS4 signchar;
Benjamin Peterson29060642009-01-31 22:14:21 +000013461 int isnumok;
13462 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013463 void *pbuf = NULL;
13464 Py_ssize_t pindex, len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013465 Py_UCS4 bufmaxchar;
13466 Py_ssize_t buflen;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013467
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013468 fmtpos++;
Victor Stinner438106b2012-05-02 00:41:57 +020013469 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13470 if (c == '(') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013471 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013472 Py_ssize_t keylen;
13473 PyObject *key;
13474 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013475
Benjamin Peterson29060642009-01-31 22:14:21 +000013476 if (dict == NULL) {
13477 PyErr_SetString(PyExc_TypeError,
13478 "format requires a mapping");
13479 goto onError;
13480 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013481 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013482 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013483 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013484 /* Skip over balanced parentheses */
13485 while (pcount > 0 && --fmtcnt >= 0) {
Victor Stinnerbff7c962012-05-03 01:44:59 +020013486 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13487 if (c == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013488 --pcount;
Victor Stinnerbff7c962012-05-03 01:44:59 +020013489 else if (c == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013490 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013491 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013492 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013493 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013494 if (fmtcnt < 0 || pcount > 0) {
13495 PyErr_SetString(PyExc_ValueError,
13496 "incomplete format key");
13497 goto onError;
13498 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013499 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013500 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013501 if (key == NULL)
13502 goto onError;
13503 if (args_owned) {
13504 Py_DECREF(args);
13505 args_owned = 0;
13506 }
13507 args = PyObject_GetItem(dict, key);
13508 Py_DECREF(key);
13509 if (args == NULL) {
13510 goto onError;
13511 }
13512 args_owned = 1;
13513 arglen = -1;
13514 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013515 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013516 while (--fmtcnt >= 0) {
Victor Stinner438106b2012-05-02 00:41:57 +020013517 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
13518 switch (c) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013519 case '-': flags |= F_LJUST; continue;
13520 case '+': flags |= F_SIGN; continue;
13521 case ' ': flags |= F_BLANK; continue;
13522 case '#': flags |= F_ALT; continue;
13523 case '0': flags |= F_ZERO; continue;
13524 }
13525 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013526 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013527 if (c == '*') {
13528 v = getnextarg(args, arglen, &argidx);
13529 if (v == NULL)
13530 goto onError;
13531 if (!PyLong_Check(v)) {
13532 PyErr_SetString(PyExc_TypeError,
13533 "* wants int");
13534 goto onError;
13535 }
13536 width = PyLong_AsLong(v);
13537 if (width == -1 && PyErr_Occurred())
13538 goto onError;
13539 if (width < 0) {
13540 flags |= F_LJUST;
13541 width = -width;
13542 }
13543 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013544 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013545 }
13546 else if (c >= '0' && c <= '9') {
13547 width = c - '0';
13548 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013549 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013550 if (c < '0' || c > '9')
13551 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013552 /* Since c is unsigned, the RHS would end up as unsigned,
13553 mixing signed and unsigned comparison. Since c is between
13554 '0' and '9', casting to int is safe. */
13555 if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013556 PyErr_SetString(PyExc_ValueError,
13557 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013558 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013559 }
13560 width = width*10 + (c - '0');
13561 }
13562 }
13563 if (c == '.') {
13564 prec = 0;
13565 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013566 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013567 if (c == '*') {
13568 v = getnextarg(args, arglen, &argidx);
13569 if (v == NULL)
13570 goto onError;
13571 if (!PyLong_Check(v)) {
13572 PyErr_SetString(PyExc_TypeError,
13573 "* wants int");
13574 goto onError;
13575 }
13576 prec = PyLong_AsLong(v);
13577 if (prec == -1 && PyErr_Occurred())
13578 goto onError;
13579 if (prec < 0)
13580 prec = 0;
13581 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013582 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013583 }
13584 else if (c >= '0' && c <= '9') {
13585 prec = c - '0';
13586 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013587 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013588 if (c < '0' || c > '9')
13589 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013590 if (prec > (INT_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013591 PyErr_SetString(PyExc_ValueError,
13592 "prec too big");
13593 goto onError;
13594 }
13595 prec = prec*10 + (c - '0');
13596 }
13597 }
13598 } /* prec */
13599 if (fmtcnt >= 0) {
13600 if (c == 'h' || c == 'l' || c == 'L') {
13601 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013602 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013603 }
13604 }
13605 if (fmtcnt < 0) {
13606 PyErr_SetString(PyExc_ValueError,
13607 "incomplete format");
13608 goto onError;
13609 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013610 if (fmtcnt == 0)
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013611 writer.overallocate = 0;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013612
13613 if (c == '%') {
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013614 if (_PyUnicodeWriter_Prepare(&writer, 1, '%') == -1)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013615 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013616 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '%');
13617 writer.pos += 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013618 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013619 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013620
Victor Stinneraff3cc62012-04-30 05:19:21 +020013621 v = getnextarg(args, arglen, &argidx);
13622 if (v == NULL)
13623 goto onError;
13624
Benjamin Peterson29060642009-01-31 22:14:21 +000013625 sign = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013626 signchar = '\0';
Benjamin Peterson29060642009-01-31 22:14:21 +000013627 fill = ' ';
13628 switch (c) {
13629
Benjamin Peterson29060642009-01-31 22:14:21 +000013630 case 's':
13631 case 'r':
13632 case 'a':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013633 if (PyLong_CheckExact(v) && width == -1 && prec == -1) {
13634 /* Fast path */
13635 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13636 goto onError;
13637 goto nextarg;
13638 }
13639
Victor Stinner808fc0a2010-03-22 12:50:40 +000013640 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013641 temp = v;
13642 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013643 }
13644 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013645 if (c == 's')
13646 temp = PyObject_Str(v);
13647 else if (c == 'r')
13648 temp = PyObject_Repr(v);
13649 else
13650 temp = PyObject_ASCII(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013651 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013652 break;
13653
13654 case 'i':
13655 case 'd':
13656 case 'u':
13657 case 'o':
13658 case 'x':
13659 case 'X':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013660 if (PyLong_CheckExact(v)
13661 && width == -1 && prec == -1
13662 && !(flags & (F_SIGN | F_BLANK)))
13663 {
13664 /* Fast path */
13665 switch(c)
13666 {
13667 case 'd':
13668 case 'i':
13669 case 'u':
13670 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13671 goto onError;
13672 goto nextarg;
13673 case 'x':
13674 if (_PyLong_FormatWriter(&writer, v, 16, flags & F_ALT) == -1)
13675 goto onError;
13676 goto nextarg;
13677 case 'o':
13678 if (_PyLong_FormatWriter(&writer, v, 8, flags & F_ALT) == -1)
13679 goto onError;
13680 goto nextarg;
13681 default:
13682 break;
13683 }
13684 }
13685
Benjamin Peterson29060642009-01-31 22:14:21 +000013686 isnumok = 0;
13687 if (PyNumber_Check(v)) {
13688 PyObject *iobj=NULL;
13689
13690 if (PyLong_Check(v)) {
13691 iobj = v;
13692 Py_INCREF(iobj);
13693 }
13694 else {
13695 iobj = PyNumber_Long(v);
13696 }
13697 if (iobj!=NULL) {
13698 if (PyLong_Check(iobj)) {
13699 isnumok = 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013700 sign = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013701 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013702 Py_DECREF(iobj);
Benjamin Peterson29060642009-01-31 22:14:21 +000013703 }
13704 else {
13705 Py_DECREF(iobj);
13706 }
13707 }
13708 }
13709 if (!isnumok) {
13710 PyErr_Format(PyExc_TypeError,
13711 "%%%c format: a number is required, "
13712 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13713 goto onError;
13714 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013715 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013716 fill = '0';
13717 break;
13718
13719 case 'e':
13720 case 'E':
13721 case 'f':
13722 case 'F':
13723 case 'g':
13724 case 'G':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013725 if (width == -1 && prec == -1
13726 && !(flags & (F_SIGN | F_BLANK)))
13727 {
13728 /* Fast path */
13729 if (formatfloat(v, flags, prec, c, NULL, &writer) == -1)
13730 goto onError;
13731 goto nextarg;
13732 }
13733
Benjamin Peterson29060642009-01-31 22:14:21 +000013734 sign = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013735 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013736 fill = '0';
Victor Stinnerd3f08822012-05-29 12:57:52 +020013737 if (formatfloat(v, flags, prec, c, &temp, NULL) == -1)
13738 temp = NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000013739 break;
13740
13741 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013742 {
13743 Py_UCS4 ch = formatchar(v);
13744 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013745 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013746 if (width == -1 && prec == -1) {
13747 /* Fast path */
13748 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1)
13749 goto onError;
13750 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch);
13751 writer.pos += 1;
13752 goto nextarg;
13753 }
Victor Stinnerb5c3ea32012-05-02 00:29:36 +020013754 temp = PyUnicode_FromOrdinal(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +000013755 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013756 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013757
13758 default:
13759 PyErr_Format(PyExc_ValueError,
13760 "unsupported format character '%c' (0x%x) "
13761 "at index %zd",
13762 (31<=c && c<=126) ? (char)c : '?',
13763 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013764 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013765 goto onError;
13766 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013767 if (temp == NULL)
13768 goto onError;
13769 assert (PyUnicode_Check(temp));
Victor Stinnerd3f08822012-05-29 12:57:52 +020013770
13771 if (width == -1 && prec == -1
13772 && !(flags & (F_SIGN | F_BLANK)))
13773 {
13774 /* Fast path */
13775 if (_PyUnicodeWriter_WriteStr(&writer, temp) == -1)
13776 goto onError;
13777 goto nextarg;
13778 }
13779
Victor Stinneraff3cc62012-04-30 05:19:21 +020013780 if (PyUnicode_READY(temp) == -1) {
13781 Py_CLEAR(temp);
13782 goto onError;
13783 }
13784 kind = PyUnicode_KIND(temp);
13785 pbuf = PyUnicode_DATA(temp);
13786 len = PyUnicode_GET_LENGTH(temp);
13787
13788 if (c == 's' || c == 'r' || c == 'a') {
13789 if (prec >= 0 && len > prec)
13790 len = prec;
13791 }
13792
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013793 /* pbuf is initialized here. */
13794 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013795 if (sign) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013796 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
13797 if (ch == '-' || ch == '+') {
13798 signchar = ch;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013799 len--;
13800 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013801 }
13802 else if (flags & F_SIGN)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013803 signchar = '+';
Benjamin Peterson29060642009-01-31 22:14:21 +000013804 else if (flags & F_BLANK)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013805 signchar = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +000013806 else
13807 sign = 0;
13808 }
13809 if (width < len)
13810 width = len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013811
13812 /* Compute the length and maximum character of the
13813 written characters */
13814 bufmaxchar = 127;
13815 if (!(flags & F_LJUST)) {
13816 if (sign) {
13817 if ((width-1) > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013818 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013819 }
13820 else {
13821 if (width > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013822 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013823 }
13824 }
13825 maxchar = _PyUnicode_FindMaxChar(temp, 0, pindex+len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013826 bufmaxchar = MAX_MAXCHAR(bufmaxchar, maxchar);
Victor Stinneree4544c2012-05-09 22:24:08 +020013827
13828 buflen = width;
13829 if (sign && len == width)
13830 buflen++;
13831
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013832 if (_PyUnicodeWriter_Prepare(&writer, buflen, bufmaxchar) == -1)
Victor Stinneree4544c2012-05-09 22:24:08 +020013833 goto onError;
13834
13835 /* Write characters */
Benjamin Peterson29060642009-01-31 22:14:21 +000013836 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013837 if (fill != ' ') {
Victor Stinneree4544c2012-05-09 22:24:08 +020013838 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13839 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013840 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013841 if (width > len)
13842 width--;
13843 }
13844 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013845 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013846 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013847 if (fill != ' ') {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013848 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13849 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13850 writer.pos += 2;
13851 pindex += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +000013852 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013853 width -= 2;
13854 if (width < 0)
13855 width = 0;
13856 len -= 2;
13857 }
13858 if (width > len && !(flags & F_LJUST)) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013859 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013860 FILL(writer.kind, writer.data, fill, writer.pos, sublen);
13861 writer.pos += sublen;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013862 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013863 }
13864 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013865 if (sign) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013866 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13867 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013868 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013869 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013870 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13871 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013872 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13873 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13874 writer.pos += 2;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013875 pindex += 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013876 }
13877 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013878
Victor Stinnerd3f08822012-05-29 12:57:52 +020013879 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13880 temp, pindex, len);
Victor Stinneree4544c2012-05-09 22:24:08 +020013881 writer.pos += len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013882 if (width > len) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013883 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013884 FILL(writer.kind, writer.data, ' ', writer.pos, sublen);
13885 writer.pos += sublen;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013886 }
Victor Stinneree4544c2012-05-09 22:24:08 +020013887
Victor Stinnerd3f08822012-05-29 12:57:52 +020013888nextarg:
Benjamin Peterson29060642009-01-31 22:14:21 +000013889 if (dict && (argidx < arglen) && c != '%') {
13890 PyErr_SetString(PyExc_TypeError,
13891 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013892 goto onError;
13893 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013894 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013895 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013896 } /* until end */
13897 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013898 PyErr_SetString(PyExc_TypeError,
13899 "not all arguments converted during string formatting");
13900 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013901 }
13902
13903 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013904 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013905 }
13906 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013907 Py_XDECREF(temp);
13908 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013909 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013910
Benjamin Peterson29060642009-01-31 22:14:21 +000013911 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013912 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013913 Py_XDECREF(temp);
13914 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013915 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013916 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013917 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013918 }
13919 return NULL;
13920}
13921
Jeremy Hylton938ace62002-07-17 16:30:39 +000013922static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013923unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13924
Tim Peters6d6c1a32001-08-02 04:15:00 +000013925static PyObject *
13926unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13927{
Benjamin Peterson29060642009-01-31 22:14:21 +000013928 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013929 static char *kwlist[] = {"object", "encoding", "errors", 0};
13930 char *encoding = NULL;
13931 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013932
Benjamin Peterson14339b62009-01-31 16:36:08 +000013933 if (type != &PyUnicode_Type)
13934 return unicode_subtype_new(type, args, kwds);
13935 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013936 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013937 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013938 if (x == NULL) {
13939 Py_INCREF(unicode_empty);
13940 return unicode_empty;
13941 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013942 if (encoding == NULL && errors == NULL)
13943 return PyObject_Str(x);
13944 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013945 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013946}
13947
Guido van Rossume023fe02001-08-30 03:12:59 +000013948static PyObject *
13949unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13950{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013951 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013952 Py_ssize_t length, char_size;
13953 int share_wstr, share_utf8;
13954 unsigned int kind;
13955 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013956
Benjamin Peterson14339b62009-01-31 16:36:08 +000013957 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013958
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013959 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013960 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013961 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013962 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050013963 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013964 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013965 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013966 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013967
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013968 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013969 if (self == NULL) {
13970 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013971 return NULL;
13972 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013973 kind = PyUnicode_KIND(unicode);
13974 length = PyUnicode_GET_LENGTH(unicode);
13975
13976 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013977#ifdef Py_DEBUG
13978 _PyUnicode_HASH(self) = -1;
13979#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013980 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013981#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013982 _PyUnicode_STATE(self).interned = 0;
13983 _PyUnicode_STATE(self).kind = kind;
13984 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013985 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013986 _PyUnicode_STATE(self).ready = 1;
13987 _PyUnicode_WSTR(self) = NULL;
13988 _PyUnicode_UTF8_LENGTH(self) = 0;
13989 _PyUnicode_UTF8(self) = NULL;
13990 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013991 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013992
13993 share_utf8 = 0;
13994 share_wstr = 0;
13995 if (kind == PyUnicode_1BYTE_KIND) {
13996 char_size = 1;
13997 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13998 share_utf8 = 1;
13999 }
14000 else if (kind == PyUnicode_2BYTE_KIND) {
14001 char_size = 2;
14002 if (sizeof(wchar_t) == 2)
14003 share_wstr = 1;
14004 }
14005 else {
14006 assert(kind == PyUnicode_4BYTE_KIND);
14007 char_size = 4;
14008 if (sizeof(wchar_t) == 4)
14009 share_wstr = 1;
14010 }
14011
14012 /* Ensure we won't overflow the length. */
14013 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14014 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014015 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014016 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014017 data = PyObject_MALLOC((length + 1) * char_size);
14018 if (data == NULL) {
14019 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014020 goto onError;
14021 }
14022
Victor Stinnerc3c74152011-10-02 20:39:55 +020014023 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014024 if (share_utf8) {
14025 _PyUnicode_UTF8_LENGTH(self) = length;
14026 _PyUnicode_UTF8(self) = data;
14027 }
14028 if (share_wstr) {
14029 _PyUnicode_WSTR_LENGTH(self) = length;
14030 _PyUnicode_WSTR(self) = (wchar_t *)data;
14031 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014032
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014033 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014034 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014035 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014036#ifdef Py_DEBUG
14037 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14038#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014039 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014040 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014041
14042onError:
14043 Py_DECREF(unicode);
14044 Py_DECREF(self);
14045 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014046}
14047
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014048PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000014049 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014050\n\
Collin Winterd474ce82007-08-07 19:42:11 +000014051Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000014052encoding defaults to the current default string encoding.\n\
14053errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014054
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014055static PyObject *unicode_iter(PyObject *seq);
14056
Guido van Rossumd57fd912000-03-10 22:53:23 +000014057PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014058 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014059 "str", /* tp_name */
14060 sizeof(PyUnicodeObject), /* tp_size */
14061 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014062 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014063 (destructor)unicode_dealloc, /* tp_dealloc */
14064 0, /* tp_print */
14065 0, /* tp_getattr */
14066 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014067 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014068 unicode_repr, /* tp_repr */
14069 &unicode_as_number, /* tp_as_number */
14070 &unicode_as_sequence, /* tp_as_sequence */
14071 &unicode_as_mapping, /* tp_as_mapping */
14072 (hashfunc) unicode_hash, /* tp_hash*/
14073 0, /* tp_call*/
14074 (reprfunc) unicode_str, /* tp_str */
14075 PyObject_GenericGetAttr, /* tp_getattro */
14076 0, /* tp_setattro */
14077 0, /* tp_as_buffer */
14078 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014079 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014080 unicode_doc, /* tp_doc */
14081 0, /* tp_traverse */
14082 0, /* tp_clear */
14083 PyUnicode_RichCompare, /* tp_richcompare */
14084 0, /* tp_weaklistoffset */
14085 unicode_iter, /* tp_iter */
14086 0, /* tp_iternext */
14087 unicode_methods, /* tp_methods */
14088 0, /* tp_members */
14089 0, /* tp_getset */
14090 &PyBaseObject_Type, /* tp_base */
14091 0, /* tp_dict */
14092 0, /* tp_descr_get */
14093 0, /* tp_descr_set */
14094 0, /* tp_dictoffset */
14095 0, /* tp_init */
14096 0, /* tp_alloc */
14097 unicode_new, /* tp_new */
14098 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014099};
14100
14101/* Initialize the Unicode implementation */
14102
Victor Stinner3a50e702011-10-18 21:21:00 +020014103int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014104{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014105 int i;
14106
Thomas Wouters477c8d52006-05-27 19:21:47 +000014107 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014108 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014109 0x000A, /* LINE FEED */
14110 0x000D, /* CARRIAGE RETURN */
14111 0x001C, /* FILE SEPARATOR */
14112 0x001D, /* GROUP SEPARATOR */
14113 0x001E, /* RECORD SEPARATOR */
14114 0x0085, /* NEXT LINE */
14115 0x2028, /* LINE SEPARATOR */
14116 0x2029, /* PARAGRAPH SEPARATOR */
14117 };
14118
Fred Drakee4315f52000-05-09 19:53:39 +000014119 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014120 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014121 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014122 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014123 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014124
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014125 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014126 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014127 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014128 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014129
14130 /* initialize the linebreak bloom filter */
14131 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014132 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014133 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014134
14135 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014136
14137#ifdef HAVE_MBCS
14138 winver.dwOSVersionInfoSize = sizeof(winver);
14139 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14140 PyErr_SetFromWindowsErr(0);
14141 return -1;
14142 }
14143#endif
14144 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014145}
14146
14147/* Finalize the Unicode implementation */
14148
Christian Heimesa156e092008-02-16 07:38:31 +000014149int
14150PyUnicode_ClearFreeList(void)
14151{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014152 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014153}
14154
Guido van Rossumd57fd912000-03-10 22:53:23 +000014155void
Thomas Wouters78890102000-07-22 19:25:51 +000014156_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014157{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014158 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014159
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014160 Py_XDECREF(unicode_empty);
14161 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014162
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014163 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014164 if (unicode_latin1[i]) {
14165 Py_DECREF(unicode_latin1[i]);
14166 unicode_latin1[i] = NULL;
14167 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014168 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014169 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014170 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014171}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014172
Walter Dörwald16807132007-05-25 13:52:07 +000014173void
14174PyUnicode_InternInPlace(PyObject **p)
14175{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014176 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014177 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014178#ifdef Py_DEBUG
14179 assert(s != NULL);
14180 assert(_PyUnicode_CHECK(s));
14181#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014182 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014183 return;
14184#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014185 /* If it's a subclass, we don't really know what putting
14186 it in the interned dict might do. */
14187 if (!PyUnicode_CheckExact(s))
14188 return;
14189 if (PyUnicode_CHECK_INTERNED(s))
14190 return;
14191 if (interned == NULL) {
14192 interned = PyDict_New();
14193 if (interned == NULL) {
14194 PyErr_Clear(); /* Don't leave an exception */
14195 return;
14196 }
14197 }
14198 /* It might be that the GetItem call fails even
14199 though the key is present in the dictionary,
14200 namely when this happens during a stack overflow. */
14201 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014202 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014203 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014204
Benjamin Peterson29060642009-01-31 22:14:21 +000014205 if (t) {
14206 Py_INCREF(t);
14207 Py_DECREF(*p);
14208 *p = t;
14209 return;
14210 }
Walter Dörwald16807132007-05-25 13:52:07 +000014211
Benjamin Peterson14339b62009-01-31 16:36:08 +000014212 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014213 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014214 PyErr_Clear();
14215 PyThreadState_GET()->recursion_critical = 0;
14216 return;
14217 }
14218 PyThreadState_GET()->recursion_critical = 0;
14219 /* The two references in interned are not counted by refcnt.
14220 The deallocator will take care of this */
14221 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014222 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014223}
14224
14225void
14226PyUnicode_InternImmortal(PyObject **p)
14227{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014228 PyUnicode_InternInPlace(p);
14229 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014230 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014231 Py_INCREF(*p);
14232 }
Walter Dörwald16807132007-05-25 13:52:07 +000014233}
14234
14235PyObject *
14236PyUnicode_InternFromString(const char *cp)
14237{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014238 PyObject *s = PyUnicode_FromString(cp);
14239 if (s == NULL)
14240 return NULL;
14241 PyUnicode_InternInPlace(&s);
14242 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014243}
14244
Alexander Belopolsky40018472011-02-26 01:02:56 +000014245void
14246_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014247{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014248 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014249 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014250 Py_ssize_t i, n;
14251 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014252
Benjamin Peterson14339b62009-01-31 16:36:08 +000014253 if (interned == NULL || !PyDict_Check(interned))
14254 return;
14255 keys = PyDict_Keys(interned);
14256 if (keys == NULL || !PyList_Check(keys)) {
14257 PyErr_Clear();
14258 return;
14259 }
Walter Dörwald16807132007-05-25 13:52:07 +000014260
Benjamin Peterson14339b62009-01-31 16:36:08 +000014261 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14262 detector, interned unicode strings are not forcibly deallocated;
14263 rather, we give them their stolen references back, and then clear
14264 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014265
Benjamin Peterson14339b62009-01-31 16:36:08 +000014266 n = PyList_GET_SIZE(keys);
14267 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014268 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014269 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014270 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014271 if (PyUnicode_READY(s) == -1) {
14272 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014273 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014274 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014275 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014276 case SSTATE_NOT_INTERNED:
14277 /* XXX Shouldn't happen */
14278 break;
14279 case SSTATE_INTERNED_IMMORTAL:
14280 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014281 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014282 break;
14283 case SSTATE_INTERNED_MORTAL:
14284 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014285 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014286 break;
14287 default:
14288 Py_FatalError("Inconsistent interned string state.");
14289 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014290 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014291 }
14292 fprintf(stderr, "total size of all interned strings: "
14293 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14294 "mortal/immortal\n", mortal_size, immortal_size);
14295 Py_DECREF(keys);
14296 PyDict_Clear(interned);
14297 Py_DECREF(interned);
14298 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014299}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014300
14301
14302/********************* Unicode Iterator **************************/
14303
14304typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014305 PyObject_HEAD
14306 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014307 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014308} unicodeiterobject;
14309
14310static void
14311unicodeiter_dealloc(unicodeiterobject *it)
14312{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014313 _PyObject_GC_UNTRACK(it);
14314 Py_XDECREF(it->it_seq);
14315 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014316}
14317
14318static int
14319unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14320{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014321 Py_VISIT(it->it_seq);
14322 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014323}
14324
14325static PyObject *
14326unicodeiter_next(unicodeiterobject *it)
14327{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014328 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014329
Benjamin Peterson14339b62009-01-31 16:36:08 +000014330 assert(it != NULL);
14331 seq = it->it_seq;
14332 if (seq == NULL)
14333 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014334 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014335
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014336 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14337 int kind = PyUnicode_KIND(seq);
14338 void *data = PyUnicode_DATA(seq);
14339 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14340 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014341 if (item != NULL)
14342 ++it->it_index;
14343 return item;
14344 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014345
Benjamin Peterson14339b62009-01-31 16:36:08 +000014346 Py_DECREF(seq);
14347 it->it_seq = NULL;
14348 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014349}
14350
14351static PyObject *
14352unicodeiter_len(unicodeiterobject *it)
14353{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014354 Py_ssize_t len = 0;
14355 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014356 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014357 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014358}
14359
14360PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14361
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014362static PyObject *
14363unicodeiter_reduce(unicodeiterobject *it)
14364{
14365 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014366 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014367 it->it_seq, it->it_index);
14368 } else {
14369 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14370 if (u == NULL)
14371 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014372 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014373 }
14374}
14375
14376PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14377
14378static PyObject *
14379unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14380{
14381 Py_ssize_t index = PyLong_AsSsize_t(state);
14382 if (index == -1 && PyErr_Occurred())
14383 return NULL;
14384 if (index < 0)
14385 index = 0;
14386 it->it_index = index;
14387 Py_RETURN_NONE;
14388}
14389
14390PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14391
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014392static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014393 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014394 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014395 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14396 reduce_doc},
14397 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14398 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014399 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014400};
14401
14402PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014403 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14404 "str_iterator", /* tp_name */
14405 sizeof(unicodeiterobject), /* tp_basicsize */
14406 0, /* tp_itemsize */
14407 /* methods */
14408 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14409 0, /* tp_print */
14410 0, /* tp_getattr */
14411 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014412 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014413 0, /* tp_repr */
14414 0, /* tp_as_number */
14415 0, /* tp_as_sequence */
14416 0, /* tp_as_mapping */
14417 0, /* tp_hash */
14418 0, /* tp_call */
14419 0, /* tp_str */
14420 PyObject_GenericGetAttr, /* tp_getattro */
14421 0, /* tp_setattro */
14422 0, /* tp_as_buffer */
14423 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14424 0, /* tp_doc */
14425 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14426 0, /* tp_clear */
14427 0, /* tp_richcompare */
14428 0, /* tp_weaklistoffset */
14429 PyObject_SelfIter, /* tp_iter */
14430 (iternextfunc)unicodeiter_next, /* tp_iternext */
14431 unicodeiter_methods, /* tp_methods */
14432 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014433};
14434
14435static PyObject *
14436unicode_iter(PyObject *seq)
14437{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014438 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014439
Benjamin Peterson14339b62009-01-31 16:36:08 +000014440 if (!PyUnicode_Check(seq)) {
14441 PyErr_BadInternalCall();
14442 return NULL;
14443 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014444 if (PyUnicode_READY(seq) == -1)
14445 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014446 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14447 if (it == NULL)
14448 return NULL;
14449 it->it_index = 0;
14450 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014451 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014452 _PyObject_GC_TRACK(it);
14453 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014454}
14455
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014456
14457size_t
14458Py_UNICODE_strlen(const Py_UNICODE *u)
14459{
14460 int res = 0;
14461 while(*u++)
14462 res++;
14463 return res;
14464}
14465
14466Py_UNICODE*
14467Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14468{
14469 Py_UNICODE *u = s1;
14470 while ((*u++ = *s2++));
14471 return s1;
14472}
14473
14474Py_UNICODE*
14475Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14476{
14477 Py_UNICODE *u = s1;
14478 while ((*u++ = *s2++))
14479 if (n-- == 0)
14480 break;
14481 return s1;
14482}
14483
14484Py_UNICODE*
14485Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14486{
14487 Py_UNICODE *u1 = s1;
14488 u1 += Py_UNICODE_strlen(u1);
14489 Py_UNICODE_strcpy(u1, s2);
14490 return s1;
14491}
14492
14493int
14494Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14495{
14496 while (*s1 && *s2 && *s1 == *s2)
14497 s1++, s2++;
14498 if (*s1 && *s2)
14499 return (*s1 < *s2) ? -1 : +1;
14500 if (*s1)
14501 return 1;
14502 if (*s2)
14503 return -1;
14504 return 0;
14505}
14506
14507int
14508Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14509{
14510 register Py_UNICODE u1, u2;
14511 for (; n != 0; n--) {
14512 u1 = *s1;
14513 u2 = *s2;
14514 if (u1 != u2)
14515 return (u1 < u2) ? -1 : +1;
14516 if (u1 == '\0')
14517 return 0;
14518 s1++;
14519 s2++;
14520 }
14521 return 0;
14522}
14523
14524Py_UNICODE*
14525Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14526{
14527 const Py_UNICODE *p;
14528 for (p = s; *p; p++)
14529 if (*p == c)
14530 return (Py_UNICODE*)p;
14531 return NULL;
14532}
14533
14534Py_UNICODE*
14535Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14536{
14537 const Py_UNICODE *p;
14538 p = s + Py_UNICODE_strlen(s);
14539 while (p != s) {
14540 p--;
14541 if (*p == c)
14542 return (Py_UNICODE*)p;
14543 }
14544 return NULL;
14545}
Victor Stinner331ea922010-08-10 16:37:20 +000014546
Victor Stinner71133ff2010-09-01 23:43:53 +000014547Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014548PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014549{
Victor Stinner577db2c2011-10-11 22:12:48 +020014550 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014551 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014552
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014553 if (!PyUnicode_Check(unicode)) {
14554 PyErr_BadArgument();
14555 return NULL;
14556 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014557 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014558 if (u == NULL)
14559 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014560 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014561 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014562 PyErr_NoMemory();
14563 return NULL;
14564 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014565 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014566 size *= sizeof(Py_UNICODE);
14567 copy = PyMem_Malloc(size);
14568 if (copy == NULL) {
14569 PyErr_NoMemory();
14570 return NULL;
14571 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014572 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014573 return copy;
14574}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014575
Georg Brandl66c221e2010-10-14 07:04:07 +000014576/* A _string module, to export formatter_parser and formatter_field_name_split
14577 to the string.Formatter class implemented in Python. */
14578
14579static PyMethodDef _string_methods[] = {
14580 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14581 METH_O, PyDoc_STR("split the argument as a field name")},
14582 {"formatter_parser", (PyCFunction) formatter_parser,
14583 METH_O, PyDoc_STR("parse the argument as a format string")},
14584 {NULL, NULL}
14585};
14586
14587static struct PyModuleDef _string_module = {
14588 PyModuleDef_HEAD_INIT,
14589 "_string",
14590 PyDoc_STR("string helper module"),
14591 0,
14592 _string_methods,
14593 NULL,
14594 NULL,
14595 NULL,
14596 NULL
14597};
14598
14599PyMODINIT_FUNC
14600PyInit__string(void)
14601{
14602 return PyModule_Create(&_string_module);
14603}
14604
14605
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014606#ifdef __cplusplus
14607}
14608#endif