blob: 267dae1bc7a2d13612883e13543cca726c3f6a62 [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;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001131
Victor Stinneree4544c2012-05-09 22:24:08 +02001132 assert(0 <= how_many);
1133 assert(0 <= from_start);
1134 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001135 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001136 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001137 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001138
Victor Stinnerd3f08822012-05-29 12:57:52 +02001139 assert(PyUnicode_Check(to));
1140 assert(PyUnicode_IS_READY(to));
1141 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1142
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001143 if (how_many == 0)
1144 return 0;
1145
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001147 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001148 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001149 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001150
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001151 if (from_kind == to_kind) {
1152 if (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)) {
1153 /* Writing Latin-1 characters into an ASCII string requires to
1154 check that all written characters are pure ASCII */
1155#ifndef Py_DEBUG
1156 if (check_maxchar) {
1157 Py_UCS4 max_char;
1158 max_char = ucs1lib_find_max_char(from_data,
Victor Stinner8a8b3ea2012-06-16 04:53:25 +02001159 (Py_UCS1*)from_data + how_many);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001160 if (max_char >= 128)
1161 return -1;
1162 }
1163#else
1164 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1165 Py_UCS4 ch;
1166 Py_ssize_t i;
1167 for (i=0; i < how_many; i++) {
1168 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1169 assert(ch <= to_maxchar);
1170 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001171#endif
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001172 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001173 Py_MEMCPY((char*)to_data + to_kind * to_start,
1174 (char*)from_data + from_kind * from_start,
1175 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001176 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001177 else if (from_kind == PyUnicode_1BYTE_KIND
1178 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001179 {
1180 _PyUnicode_CONVERT_BYTES(
1181 Py_UCS1, Py_UCS2,
1182 PyUnicode_1BYTE_DATA(from) + from_start,
1183 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1184 PyUnicode_2BYTE_DATA(to) + to_start
1185 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001186 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001187 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001188 && to_kind == PyUnicode_4BYTE_KIND)
1189 {
1190 _PyUnicode_CONVERT_BYTES(
1191 Py_UCS1, Py_UCS4,
1192 PyUnicode_1BYTE_DATA(from) + from_start,
1193 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1194 PyUnicode_4BYTE_DATA(to) + to_start
1195 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001196 }
1197 else if (from_kind == PyUnicode_2BYTE_KIND
1198 && to_kind == PyUnicode_4BYTE_KIND)
1199 {
1200 _PyUnicode_CONVERT_BYTES(
1201 Py_UCS2, Py_UCS4,
1202 PyUnicode_2BYTE_DATA(from) + from_start,
1203 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1204 PyUnicode_4BYTE_DATA(to) + to_start
1205 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001206 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001207 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001208 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1209
1210#ifndef Py_DEBUG
1211 if (!check_maxchar) {
1212 if (from_kind == PyUnicode_2BYTE_KIND
1213 && to_kind == PyUnicode_1BYTE_KIND)
1214 {
1215 _PyUnicode_CONVERT_BYTES(
1216 Py_UCS2, Py_UCS1,
1217 PyUnicode_2BYTE_DATA(from) + from_start,
1218 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1219 PyUnicode_1BYTE_DATA(to) + to_start
1220 );
1221 }
1222 else if (from_kind == PyUnicode_4BYTE_KIND
1223 && to_kind == PyUnicode_1BYTE_KIND)
1224 {
1225 _PyUnicode_CONVERT_BYTES(
1226 Py_UCS4, Py_UCS1,
1227 PyUnicode_4BYTE_DATA(from) + from_start,
1228 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1229 PyUnicode_1BYTE_DATA(to) + to_start
1230 );
1231 }
1232 else if (from_kind == PyUnicode_4BYTE_KIND
1233 && to_kind == PyUnicode_2BYTE_KIND)
1234 {
1235 _PyUnicode_CONVERT_BYTES(
1236 Py_UCS4, Py_UCS2,
1237 PyUnicode_4BYTE_DATA(from) + from_start,
1238 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1239 PyUnicode_2BYTE_DATA(to) + to_start
1240 );
1241 }
1242 else {
1243 assert(0);
1244 return -1;
1245 }
1246 }
1247 else
1248#endif
Victor Stinnerf42dc442011-10-02 23:33:16 +02001249 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001250 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001251 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001252 Py_ssize_t i;
1253
Victor Stinnera0702ab2011-09-29 14:14:38 +02001254 for (i=0; i < how_many; i++) {
1255 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001256#ifndef Py_DEBUG
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001257 if (ch > to_maxchar)
1258 return -1;
Victor Stinner24e403b2012-06-16 04:53:00 +02001259#else
1260 assert(ch <= to_maxchar);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001261#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001262 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1263 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001264 }
1265 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001266 return 0;
1267}
1268
Victor Stinnerd3f08822012-05-29 12:57:52 +02001269void
1270_PyUnicode_FastCopyCharacters(
1271 PyObject *to, Py_ssize_t to_start,
1272 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001273{
1274 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1275}
1276
1277Py_ssize_t
1278PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1279 PyObject *from, Py_ssize_t from_start,
1280 Py_ssize_t how_many)
1281{
1282 int err;
1283
1284 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1285 PyErr_BadInternalCall();
1286 return -1;
1287 }
1288
Benjamin Petersonbac79492012-01-14 13:34:47 -05001289 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001290 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001291 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001292 return -1;
1293
Victor Stinnerd3f08822012-05-29 12:57:52 +02001294 if (from_start < 0) {
1295 PyErr_SetString(PyExc_IndexError, "string index out of range");
1296 return -1;
1297 }
1298 if (to_start < 0) {
1299 PyErr_SetString(PyExc_IndexError, "string index out of range");
1300 return -1;
1301 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001302 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1303 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1304 PyErr_Format(PyExc_SystemError,
1305 "Cannot write %zi characters at %zi "
1306 "in a string of %zi characters",
1307 how_many, to_start, PyUnicode_GET_LENGTH(to));
1308 return -1;
1309 }
1310
1311 if (how_many == 0)
1312 return 0;
1313
Victor Stinner488fa492011-12-12 00:01:39 +01001314 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001315 return -1;
1316
1317 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1318 if (err) {
1319 PyErr_Format(PyExc_SystemError,
1320 "Cannot copy %s characters "
1321 "into a string of %s characters",
1322 unicode_kind_name(from),
1323 unicode_kind_name(to));
1324 return -1;
1325 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001326 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001327}
1328
Victor Stinner17222162011-09-28 22:15:37 +02001329/* Find the maximum code point and count the number of surrogate pairs so a
1330 correct string length can be computed before converting a string to UCS4.
1331 This function counts single surrogates as a character and not as a pair.
1332
1333 Return 0 on success, or -1 on error. */
1334static int
1335find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1336 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001337{
1338 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001339 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001340
Victor Stinnerc53be962011-10-02 21:33:54 +02001341 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001342 *num_surrogates = 0;
1343 *maxchar = 0;
1344
1345 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001346#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001347 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1348 && (iter+1) < end
1349 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001351 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001352 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001353 iter += 2;
1354 }
1355 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001356#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001357 {
1358 ch = *iter;
1359 iter++;
1360 }
1361 if (ch > *maxchar) {
1362 *maxchar = ch;
1363 if (*maxchar > MAX_UNICODE) {
1364 PyErr_Format(PyExc_ValueError,
1365 "character U+%x is not in range [U+0000; U+10ffff]",
1366 ch);
1367 return -1;
1368 }
1369 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001370 }
1371 return 0;
1372}
1373
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001374int
1375_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001376{
1377 wchar_t *end;
1378 Py_UCS4 maxchar = 0;
1379 Py_ssize_t num_surrogates;
1380#if SIZEOF_WCHAR_T == 2
1381 Py_ssize_t length_wo_surrogates;
1382#endif
1383
Georg Brandl7597add2011-10-05 16:36:47 +02001384 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001385 strings were created using _PyObject_New() and where no canonical
1386 representation (the str field) has been set yet aka strings
1387 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001388 assert(_PyUnicode_CHECK(unicode));
1389 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001390 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001391 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001392 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001393 /* Actually, it should neither be interned nor be anything else: */
1394 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001395
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001396 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001397 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001398 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001399 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001400
1401 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001402 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1403 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001404 PyErr_NoMemory();
1405 return -1;
1406 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001407 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001408 _PyUnicode_WSTR(unicode), end,
1409 PyUnicode_1BYTE_DATA(unicode));
1410 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1411 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1412 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1413 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001414 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001415 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001416 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001417 }
1418 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001419 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001420 _PyUnicode_UTF8(unicode) = NULL;
1421 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001422 }
1423 PyObject_FREE(_PyUnicode_WSTR(unicode));
1424 _PyUnicode_WSTR(unicode) = NULL;
1425 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1426 }
1427 /* In this case we might have to convert down from 4-byte native
1428 wchar_t to 2-byte unicode. */
1429 else if (maxchar < 65536) {
1430 assert(num_surrogates == 0 &&
1431 "FindMaxCharAndNumSurrogatePairs() messed up");
1432
Victor Stinner506f5922011-09-28 22:34:18 +02001433#if SIZEOF_WCHAR_T == 2
1434 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001435 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001436 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1437 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1438 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001439 _PyUnicode_UTF8(unicode) = NULL;
1440 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001441#else
1442 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001443 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001444 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001445 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001446 PyErr_NoMemory();
1447 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001448 }
Victor Stinner506f5922011-09-28 22:34:18 +02001449 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1450 _PyUnicode_WSTR(unicode), end,
1451 PyUnicode_2BYTE_DATA(unicode));
1452 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1453 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1454 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001455 _PyUnicode_UTF8(unicode) = NULL;
1456 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001457 PyObject_FREE(_PyUnicode_WSTR(unicode));
1458 _PyUnicode_WSTR(unicode) = NULL;
1459 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1460#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001461 }
1462 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1463 else {
1464#if SIZEOF_WCHAR_T == 2
1465 /* in case the native representation is 2-bytes, we need to allocate a
1466 new normalized 4-byte version. */
1467 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001468 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1469 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001470 PyErr_NoMemory();
1471 return -1;
1472 }
1473 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1474 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001475 _PyUnicode_UTF8(unicode) = NULL;
1476 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001477 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1478 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001479 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001480 PyObject_FREE(_PyUnicode_WSTR(unicode));
1481 _PyUnicode_WSTR(unicode) = NULL;
1482 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1483#else
1484 assert(num_surrogates == 0);
1485
Victor Stinnerc3c74152011-10-02 20:39:55 +02001486 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001487 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001488 _PyUnicode_UTF8(unicode) = NULL;
1489 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001490 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1491#endif
1492 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1493 }
1494 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001495 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001496 return 0;
1497}
1498
Alexander Belopolsky40018472011-02-26 01:02:56 +00001499static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001500unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001501{
Walter Dörwald16807132007-05-25 13:52:07 +00001502 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001503 case SSTATE_NOT_INTERNED:
1504 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001505
Benjamin Peterson29060642009-01-31 22:14:21 +00001506 case SSTATE_INTERNED_MORTAL:
1507 /* revive dead object temporarily for DelItem */
1508 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001509 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001510 Py_FatalError(
1511 "deletion of interned string failed");
1512 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001513
Benjamin Peterson29060642009-01-31 22:14:21 +00001514 case SSTATE_INTERNED_IMMORTAL:
1515 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001516
Benjamin Peterson29060642009-01-31 22:14:21 +00001517 default:
1518 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001519 }
1520
Victor Stinner03490912011-10-03 23:45:12 +02001521 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001522 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001523 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001524 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001525 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1526 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001527
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001528 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001529}
1530
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001531#ifdef Py_DEBUG
1532static int
1533unicode_is_singleton(PyObject *unicode)
1534{
1535 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1536 if (unicode == unicode_empty)
1537 return 1;
1538 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1539 {
1540 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1541 if (ch < 256 && unicode_latin1[ch] == unicode)
1542 return 1;
1543 }
1544 return 0;
1545}
1546#endif
1547
Alexander Belopolsky40018472011-02-26 01:02:56 +00001548static int
Victor Stinner488fa492011-12-12 00:01:39 +01001549unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001550{
Victor Stinner488fa492011-12-12 00:01:39 +01001551 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001552 if (Py_REFCNT(unicode) != 1)
1553 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001554 if (_PyUnicode_HASH(unicode) != -1)
1555 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001556 if (PyUnicode_CHECK_INTERNED(unicode))
1557 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001558 if (!PyUnicode_CheckExact(unicode))
1559 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001560#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001561 /* singleton refcount is greater than 1 */
1562 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001563#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001564 return 1;
1565}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001566
Victor Stinnerfe226c02011-10-03 03:52:20 +02001567static int
1568unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1569{
1570 PyObject *unicode;
1571 Py_ssize_t old_length;
1572
1573 assert(p_unicode != NULL);
1574 unicode = *p_unicode;
1575
1576 assert(unicode != NULL);
1577 assert(PyUnicode_Check(unicode));
1578 assert(0 <= length);
1579
Victor Stinner910337b2011-10-03 03:20:16 +02001580 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001581 old_length = PyUnicode_WSTR_LENGTH(unicode);
1582 else
1583 old_length = PyUnicode_GET_LENGTH(unicode);
1584 if (old_length == length)
1585 return 0;
1586
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001587 if (length == 0) {
1588 Py_DECREF(*p_unicode);
1589 *p_unicode = unicode_empty;
1590 Py_INCREF(*p_unicode);
1591 return 0;
1592 }
1593
Victor Stinner488fa492011-12-12 00:01:39 +01001594 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001595 PyObject *copy = resize_copy(unicode, length);
1596 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001597 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001598 Py_DECREF(*p_unicode);
1599 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001600 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001601 }
1602
Victor Stinnerfe226c02011-10-03 03:52:20 +02001603 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001604 PyObject *new_unicode = resize_compact(unicode, length);
1605 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001606 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001607 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001608 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001609 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001610 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001611}
1612
Alexander Belopolsky40018472011-02-26 01:02:56 +00001613int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001614PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001615{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001616 PyObject *unicode;
1617 if (p_unicode == NULL) {
1618 PyErr_BadInternalCall();
1619 return -1;
1620 }
1621 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001622 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001623 {
1624 PyErr_BadInternalCall();
1625 return -1;
1626 }
1627 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001628}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001629
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001630static int
Victor Stinner1b487b42012-05-03 12:29:04 +02001631unicode_widen(PyObject **p_unicode, Py_ssize_t length,
1632 unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001633{
1634 PyObject *result;
1635 assert(PyUnicode_IS_READY(*p_unicode));
Victor Stinner1b487b42012-05-03 12:29:04 +02001636 assert(length <= PyUnicode_GET_LENGTH(*p_unicode));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001637 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1638 return 0;
1639 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1640 maxchar);
1641 if (result == NULL)
1642 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001643 _PyUnicode_FastCopyCharacters(result, 0, *p_unicode, 0, length);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001644 Py_DECREF(*p_unicode);
1645 *p_unicode = result;
1646 return 0;
1647}
1648
1649static int
1650unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1651 Py_UCS4 ch)
1652{
Victor Stinner15e9ed22012-02-22 13:36:20 +01001653 assert(ch <= MAX_UNICODE);
Victor Stinner1b487b42012-05-03 12:29:04 +02001654 if (unicode_widen(p_unicode, *pos, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001655 return -1;
1656 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1657 PyUnicode_DATA(*p_unicode),
1658 (*pos)++, ch);
1659 return 0;
1660}
1661
Victor Stinnerc5166102012-02-22 13:55:02 +01001662/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001663
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001664 WARNING: The function doesn't copy the terminating null character and
1665 doesn't check the maximum character (may write a latin1 character in an
1666 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001667static void
1668unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1669 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001670{
1671 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1672 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001673 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001674
1675 switch (kind) {
1676 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001677 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001678 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001679 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001680 }
1681 case PyUnicode_2BYTE_KIND: {
1682 Py_UCS2 *start = (Py_UCS2 *)data + index;
1683 Py_UCS2 *ucs2 = start;
1684 assert(index <= PyUnicode_GET_LENGTH(unicode));
1685
Victor Stinner184252a2012-06-16 02:57:41 +02001686 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001687 *ucs2 = (Py_UCS2)*str;
1688
1689 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001690 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001691 }
1692 default: {
1693 Py_UCS4 *start = (Py_UCS4 *)data + index;
1694 Py_UCS4 *ucs4 = start;
1695 assert(kind == PyUnicode_4BYTE_KIND);
1696 assert(index <= PyUnicode_GET_LENGTH(unicode));
1697
Victor Stinner184252a2012-06-16 02:57:41 +02001698 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001699 *ucs4 = (Py_UCS4)*str;
1700
1701 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001702 }
1703 }
1704}
1705
1706
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001707static PyObject*
1708get_latin1_char(unsigned char ch)
1709{
Victor Stinnera464fc12011-10-02 20:39:30 +02001710 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001711 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001712 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001713 if (!unicode)
1714 return NULL;
1715 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001716 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001717 unicode_latin1[ch] = unicode;
1718 }
1719 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001720 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001721}
1722
Alexander Belopolsky40018472011-02-26 01:02:56 +00001723PyObject *
1724PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001725{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001726 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001727 Py_UCS4 maxchar = 0;
1728 Py_ssize_t num_surrogates;
1729
1730 if (u == NULL)
1731 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001732
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001733 /* If the Unicode data is known at construction time, we can apply
1734 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001735
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001736 /* Optimization for empty strings */
1737 if (size == 0 && unicode_empty != NULL) {
1738 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001739 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001740 }
Tim Petersced69f82003-09-16 20:30:58 +00001741
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001742 /* Single character Unicode objects in the Latin-1 range are
1743 shared when using this constructor */
1744 if (size == 1 && *u < 256)
1745 return get_latin1_char((unsigned char)*u);
1746
1747 /* If not empty and not single character, copy the Unicode data
1748 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001749 if (find_maxchar_surrogates(u, u + size,
1750 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001751 return NULL;
1752
Victor Stinner8faf8212011-12-08 22:14:11 +01001753 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001754 if (!unicode)
1755 return NULL;
1756
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001757 switch (PyUnicode_KIND(unicode)) {
1758 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001759 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001760 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1761 break;
1762 case PyUnicode_2BYTE_KIND:
1763#if Py_UNICODE_SIZE == 2
1764 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1765#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001766 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1768#endif
1769 break;
1770 case PyUnicode_4BYTE_KIND:
1771#if SIZEOF_WCHAR_T == 2
1772 /* This is the only case which has to process surrogates, thus
1773 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001774 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001775#else
1776 assert(num_surrogates == 0);
1777 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1778#endif
1779 break;
1780 default:
1781 assert(0 && "Impossible state");
1782 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001783
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001784 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001785}
1786
Alexander Belopolsky40018472011-02-26 01:02:56 +00001787PyObject *
1788PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001789{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001790 if (size < 0) {
1791 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001792 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001793 return NULL;
1794 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001795 if (u != NULL)
1796 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1797 else
1798 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001799}
1800
Alexander Belopolsky40018472011-02-26 01:02:56 +00001801PyObject *
1802PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001803{
1804 size_t size = strlen(u);
1805 if (size > PY_SSIZE_T_MAX) {
1806 PyErr_SetString(PyExc_OverflowError, "input too long");
1807 return NULL;
1808 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001809 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001810}
1811
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001812PyObject *
1813_PyUnicode_FromId(_Py_Identifier *id)
1814{
1815 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001816 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1817 strlen(id->string),
1818 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001819 if (!id->object)
1820 return NULL;
1821 PyUnicode_InternInPlace(&id->object);
1822 assert(!id->next);
1823 id->next = static_strings;
1824 static_strings = id;
1825 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001826 return id->object;
1827}
1828
1829void
1830_PyUnicode_ClearStaticStrings()
1831{
1832 _Py_Identifier *i;
1833 for (i = static_strings; i; i = i->next) {
1834 Py_DECREF(i->object);
1835 i->object = NULL;
1836 i->next = NULL;
1837 }
1838}
1839
Benjamin Peterson0df54292012-03-26 14:50:32 -04001840/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001841
Victor Stinnerd3f08822012-05-29 12:57:52 +02001842PyObject*
1843_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001844{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001845 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001846 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001847 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001848#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001849 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001850#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001851 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001852 }
Victor Stinner785938e2011-12-11 20:09:03 +01001853 unicode = PyUnicode_New(size, 127);
1854 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001855 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001856 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1857 assert(_PyUnicode_CheckConsistency(unicode, 1));
1858 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001859}
1860
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001861static Py_UCS4
1862kind_maxchar_limit(unsigned int kind)
1863{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001864 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001865 case PyUnicode_1BYTE_KIND:
1866 return 0x80;
1867 case PyUnicode_2BYTE_KIND:
1868 return 0x100;
1869 case PyUnicode_4BYTE_KIND:
1870 return 0x10000;
1871 default:
1872 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001873 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001874 }
1875}
1876
Victor Stinnere6abb482012-05-02 01:15:40 +02001877Py_LOCAL_INLINE(Py_UCS4)
1878align_maxchar(Py_UCS4 maxchar)
1879{
1880 if (maxchar <= 127)
1881 return 127;
1882 else if (maxchar <= 255)
1883 return 255;
1884 else if (maxchar <= 65535)
1885 return 65535;
1886 else
1887 return MAX_UNICODE;
1888}
1889
Victor Stinner702c7342011-10-05 13:50:52 +02001890static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001891_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001892{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001893 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001894 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001895
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001896 if (size == 0) {
1897 Py_INCREF(unicode_empty);
1898 return unicode_empty;
1899 }
1900 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001901 if (size == 1)
1902 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001903
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001904 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001905 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001906 if (!res)
1907 return NULL;
1908 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001909 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001910 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001911}
1912
Victor Stinnere57b1c02011-09-28 22:20:48 +02001913static PyObject*
1914_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001915{
1916 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001917 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001918
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001919 if (size == 0) {
1920 Py_INCREF(unicode_empty);
1921 return unicode_empty;
1922 }
1923 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001924 if (size == 1) {
1925 Py_UCS4 ch = u[0];
1926 if (ch < 256)
1927 return get_latin1_char((unsigned char)ch);
1928
1929 res = PyUnicode_New(1, ch);
1930 if (res == NULL)
1931 return NULL;
1932 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1933 assert(_PyUnicode_CheckConsistency(res, 1));
1934 return res;
1935 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001936
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001937 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001938 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001939 if (!res)
1940 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001941 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001942 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001943 else {
1944 _PyUnicode_CONVERT_BYTES(
1945 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1946 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001947 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001948 return res;
1949}
1950
Victor Stinnere57b1c02011-09-28 22:20:48 +02001951static PyObject*
1952_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001953{
1954 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001955 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001956
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001957 if (size == 0) {
1958 Py_INCREF(unicode_empty);
1959 return unicode_empty;
1960 }
1961 assert(size > 0);
Victor Stinnerb6cd0142012-05-03 02:17:04 +02001962 if (size == 1) {
1963 Py_UCS4 ch = u[0];
1964 if (ch < 256)
1965 return get_latin1_char((unsigned char)ch);
1966
1967 res = PyUnicode_New(1, ch);
1968 if (res == NULL)
1969 return NULL;
1970 PyUnicode_WRITE(PyUnicode_KIND(res), PyUnicode_DATA(res), 0, ch);
1971 assert(_PyUnicode_CheckConsistency(res, 1));
1972 return res;
1973 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001974
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001975 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001976 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001977 if (!res)
1978 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001979 if (max_char < 256)
1980 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1981 PyUnicode_1BYTE_DATA(res));
1982 else if (max_char < 0x10000)
1983 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1984 PyUnicode_2BYTE_DATA(res));
1985 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001986 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001987 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001988 return res;
1989}
1990
1991PyObject*
1992PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1993{
Victor Stinnercfed46e2011-11-22 01:29:14 +01001994 if (size < 0) {
1995 PyErr_SetString(PyExc_ValueError, "size must be positive");
1996 return NULL;
1997 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06001998 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001999 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002000 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002001 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002002 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002003 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002004 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002005 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002006 PyErr_SetString(PyExc_SystemError, "invalid kind");
2007 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002008 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002009}
2010
Victor Stinnerece58de2012-04-23 23:36:38 +02002011Py_UCS4
2012_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2013{
2014 enum PyUnicode_Kind kind;
2015 void *startptr, *endptr;
2016
2017 assert(PyUnicode_IS_READY(unicode));
2018 assert(0 <= start);
2019 assert(end <= PyUnicode_GET_LENGTH(unicode));
2020 assert(start <= end);
2021
2022 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2023 return PyUnicode_MAX_CHAR_VALUE(unicode);
2024
2025 if (start == end)
2026 return 127;
2027
Victor Stinner94d558b2012-04-27 22:26:58 +02002028 if (PyUnicode_IS_ASCII(unicode))
2029 return 127;
2030
Victor Stinnerece58de2012-04-23 23:36:38 +02002031 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002032 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002033 endptr = (char *)startptr + end * kind;
2034 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002035 switch(kind) {
2036 case PyUnicode_1BYTE_KIND:
2037 return ucs1lib_find_max_char(startptr, endptr);
2038 case PyUnicode_2BYTE_KIND:
2039 return ucs2lib_find_max_char(startptr, endptr);
2040 case PyUnicode_4BYTE_KIND:
2041 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002042 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002043 assert(0);
2044 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002045 }
2046}
2047
Victor Stinner25a4b292011-10-06 12:31:55 +02002048/* Ensure that a string uses the most efficient storage, if it is not the
2049 case: create a new string with of the right kind. Write NULL into *p_unicode
2050 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002051static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002052unicode_adjust_maxchar(PyObject **p_unicode)
2053{
2054 PyObject *unicode, *copy;
2055 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002056 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002057 unsigned int kind;
2058
2059 assert(p_unicode != NULL);
2060 unicode = *p_unicode;
2061 assert(PyUnicode_IS_READY(unicode));
2062 if (PyUnicode_IS_ASCII(unicode))
2063 return;
2064
2065 len = PyUnicode_GET_LENGTH(unicode);
2066 kind = PyUnicode_KIND(unicode);
2067 if (kind == PyUnicode_1BYTE_KIND) {
2068 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002069 max_char = ucs1lib_find_max_char(u, u + len);
2070 if (max_char >= 128)
2071 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002072 }
2073 else if (kind == PyUnicode_2BYTE_KIND) {
2074 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002075 max_char = ucs2lib_find_max_char(u, u + len);
2076 if (max_char >= 256)
2077 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002078 }
2079 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002080 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002081 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002082 max_char = ucs4lib_find_max_char(u, u + len);
2083 if (max_char >= 0x10000)
2084 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002085 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002086 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002087 if (copy != NULL)
2088 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002089 Py_DECREF(unicode);
2090 *p_unicode = copy;
2091}
2092
Victor Stinner034f6cf2011-09-30 02:26:44 +02002093PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002094_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002095{
Victor Stinner87af4f22011-11-21 23:03:47 +01002096 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002097 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002098
Victor Stinner034f6cf2011-09-30 02:26:44 +02002099 if (!PyUnicode_Check(unicode)) {
2100 PyErr_BadInternalCall();
2101 return NULL;
2102 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002103 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002104 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002105
Victor Stinner87af4f22011-11-21 23:03:47 +01002106 length = PyUnicode_GET_LENGTH(unicode);
2107 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002108 if (!copy)
2109 return NULL;
2110 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2111
Victor Stinner87af4f22011-11-21 23:03:47 +01002112 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2113 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002114 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002115 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002116}
2117
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002118
Victor Stinnerbc603d12011-10-02 01:00:40 +02002119/* Widen Unicode objects to larger buffers. Don't write terminating null
2120 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002121
2122void*
2123_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2124{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002125 Py_ssize_t len;
2126 void *result;
2127 unsigned int skind;
2128
Benjamin Petersonbac79492012-01-14 13:34:47 -05002129 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002130 return NULL;
2131
2132 len = PyUnicode_GET_LENGTH(s);
2133 skind = PyUnicode_KIND(s);
2134 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002135 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002136 return NULL;
2137 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002138 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002139 case PyUnicode_2BYTE_KIND:
2140 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2141 if (!result)
2142 return PyErr_NoMemory();
2143 assert(skind == PyUnicode_1BYTE_KIND);
2144 _PyUnicode_CONVERT_BYTES(
2145 Py_UCS1, Py_UCS2,
2146 PyUnicode_1BYTE_DATA(s),
2147 PyUnicode_1BYTE_DATA(s) + len,
2148 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002149 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002150 case PyUnicode_4BYTE_KIND:
2151 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2152 if (!result)
2153 return PyErr_NoMemory();
2154 if (skind == PyUnicode_2BYTE_KIND) {
2155 _PyUnicode_CONVERT_BYTES(
2156 Py_UCS2, Py_UCS4,
2157 PyUnicode_2BYTE_DATA(s),
2158 PyUnicode_2BYTE_DATA(s) + len,
2159 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002160 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002161 else {
2162 assert(skind == PyUnicode_1BYTE_KIND);
2163 _PyUnicode_CONVERT_BYTES(
2164 Py_UCS1, Py_UCS4,
2165 PyUnicode_1BYTE_DATA(s),
2166 PyUnicode_1BYTE_DATA(s) + len,
2167 result);
2168 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002169 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002170 default:
2171 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002172 }
Victor Stinner01698042011-10-04 00:04:26 +02002173 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002174 return NULL;
2175}
2176
2177static Py_UCS4*
2178as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2179 int copy_null)
2180{
2181 int kind;
2182 void *data;
2183 Py_ssize_t len, targetlen;
2184 if (PyUnicode_READY(string) == -1)
2185 return NULL;
2186 kind = PyUnicode_KIND(string);
2187 data = PyUnicode_DATA(string);
2188 len = PyUnicode_GET_LENGTH(string);
2189 targetlen = len;
2190 if (copy_null)
2191 targetlen++;
2192 if (!target) {
2193 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2194 PyErr_NoMemory();
2195 return NULL;
2196 }
2197 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2198 if (!target) {
2199 PyErr_NoMemory();
2200 return NULL;
2201 }
2202 }
2203 else {
2204 if (targetsize < targetlen) {
2205 PyErr_Format(PyExc_SystemError,
2206 "string is longer than the buffer");
2207 if (copy_null && 0 < targetsize)
2208 target[0] = 0;
2209 return NULL;
2210 }
2211 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002212 if (kind == PyUnicode_1BYTE_KIND) {
2213 Py_UCS1 *start = (Py_UCS1 *) data;
2214 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002215 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002216 else if (kind == PyUnicode_2BYTE_KIND) {
2217 Py_UCS2 *start = (Py_UCS2 *) data;
2218 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2219 }
2220 else {
2221 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002222 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002223 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002224 if (copy_null)
2225 target[len] = 0;
2226 return target;
2227}
2228
2229Py_UCS4*
2230PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2231 int copy_null)
2232{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002233 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002234 PyErr_BadInternalCall();
2235 return NULL;
2236 }
2237 return as_ucs4(string, target, targetsize, copy_null);
2238}
2239
2240Py_UCS4*
2241PyUnicode_AsUCS4Copy(PyObject *string)
2242{
2243 return as_ucs4(string, NULL, 0, 1);
2244}
2245
2246#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002247
Alexander Belopolsky40018472011-02-26 01:02:56 +00002248PyObject *
2249PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002250{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002251 if (w == NULL) {
Victor Stinner382955f2011-12-11 21:44:00 +01002252 if (size == 0) {
2253 Py_INCREF(unicode_empty);
2254 return unicode_empty;
2255 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002256 PyErr_BadInternalCall();
2257 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002258 }
2259
Martin v. Löwis790465f2008-04-05 20:41:37 +00002260 if (size == -1) {
2261 size = wcslen(w);
2262 }
2263
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002264 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002265}
2266
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002267#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002268
Walter Dörwald346737f2007-05-31 10:44:43 +00002269static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002270makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2271 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002272{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002273 *fmt++ = '%';
2274 if (width) {
2275 if (zeropad)
2276 *fmt++ = '0';
2277 fmt += sprintf(fmt, "%d", width);
2278 }
2279 if (precision)
2280 fmt += sprintf(fmt, ".%d", precision);
2281 if (longflag)
2282 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002283 else if (longlongflag) {
2284 /* longlongflag should only ever be nonzero on machines with
2285 HAVE_LONG_LONG defined */
2286#ifdef HAVE_LONG_LONG
2287 char *f = PY_FORMAT_LONG_LONG;
2288 while (*f)
2289 *fmt++ = *f++;
2290#else
2291 /* we shouldn't ever get here */
2292 assert(0);
2293 *fmt++ = 'l';
2294#endif
2295 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002296 else if (size_tflag) {
2297 char *f = PY_FORMAT_SIZE_T;
2298 while (*f)
2299 *fmt++ = *f++;
2300 }
2301 *fmt++ = c;
2302 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002303}
2304
Victor Stinner96865452011-03-01 23:44:09 +00002305/* helper for PyUnicode_FromFormatV() */
2306
2307static const char*
2308parse_format_flags(const char *f,
2309 int *p_width, int *p_precision,
2310 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2311{
2312 int width, precision, longflag, longlongflag, size_tflag;
2313
2314 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2315 f++;
2316 width = 0;
2317 while (Py_ISDIGIT((unsigned)*f))
2318 width = (width*10) + *f++ - '0';
2319 precision = 0;
2320 if (*f == '.') {
2321 f++;
2322 while (Py_ISDIGIT((unsigned)*f))
2323 precision = (precision*10) + *f++ - '0';
2324 if (*f == '%') {
2325 /* "%.3%s" => f points to "3" */
2326 f--;
2327 }
2328 }
2329 if (*f == '\0') {
2330 /* bogus format "%.1" => go backward, f points to "1" */
2331 f--;
2332 }
2333 if (p_width != NULL)
2334 *p_width = width;
2335 if (p_precision != NULL)
2336 *p_precision = precision;
2337
2338 /* Handle %ld, %lu, %lld and %llu. */
2339 longflag = 0;
2340 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002341 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002342
2343 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002344 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002345 longflag = 1;
2346 ++f;
2347 }
2348#ifdef HAVE_LONG_LONG
2349 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002350 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002351 longlongflag = 1;
2352 f += 2;
2353 }
2354#endif
2355 }
2356 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002357 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002358 size_tflag = 1;
2359 ++f;
2360 }
2361 if (p_longflag != NULL)
2362 *p_longflag = longflag;
2363 if (p_longlongflag != NULL)
2364 *p_longlongflag = longlongflag;
2365 if (p_size_tflag != NULL)
2366 *p_size_tflag = size_tflag;
2367 return f;
2368}
2369
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002370/* maximum number of characters required for output of %ld. 21 characters
2371 allows for 64-bit integers (in decimal) and an optional sign. */
2372#define MAX_LONG_CHARS 21
2373/* maximum number of characters required for output of %lld.
2374 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2375 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2376#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2377
Walter Dörwaldd2034312007-05-18 16:29:38 +00002378PyObject *
2379PyUnicode_FromFormatV(const char *format, va_list vargs)
2380{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002381 va_list count;
2382 Py_ssize_t callcount = 0;
2383 PyObject **callresults = NULL;
2384 PyObject **callresult = NULL;
2385 Py_ssize_t n = 0;
2386 int width = 0;
2387 int precision = 0;
2388 int zeropad;
2389 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002390 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002391 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002392 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002393 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2394 Py_UCS4 argmaxchar;
2395 Py_ssize_t numbersize = 0;
2396 char *numberresults = NULL;
2397 char *numberresult = NULL;
2398 Py_ssize_t i;
2399 int kind;
2400 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002401
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002402 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002403 /* step 1: count the number of %S/%R/%A/%s format specifications
2404 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2405 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002406 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002407 * also estimate a upper bound for all the number formats in the string,
2408 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002409 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002410 for (f = format; *f; f++) {
2411 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002412 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002413 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2414 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2415 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2416 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002417
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002418 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002419#ifdef HAVE_LONG_LONG
2420 if (longlongflag) {
2421 if (width < MAX_LONG_LONG_CHARS)
2422 width = MAX_LONG_LONG_CHARS;
2423 }
2424 else
2425#endif
2426 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2427 including sign. Decimal takes the most space. This
2428 isn't enough for octal. If a width is specified we
2429 need more (which we allocate later). */
2430 if (width < MAX_LONG_CHARS)
2431 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002432
2433 /* account for the size + '\0' to separate numbers
2434 inside of the numberresults buffer */
2435 numbersize += (width + 1);
2436 }
2437 }
2438 else if ((unsigned char)*f > 127) {
2439 PyErr_Format(PyExc_ValueError,
2440 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2441 "string, got a non-ASCII byte: 0x%02x",
2442 (unsigned char)*f);
2443 return NULL;
2444 }
2445 }
2446 /* step 2: allocate memory for the results of
2447 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2448 if (callcount) {
2449 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2450 if (!callresults) {
2451 PyErr_NoMemory();
2452 return NULL;
2453 }
2454 callresult = callresults;
2455 }
2456 /* step 2.5: allocate memory for the results of formating numbers */
2457 if (numbersize) {
2458 numberresults = PyObject_Malloc(numbersize);
2459 if (!numberresults) {
2460 PyErr_NoMemory();
2461 goto fail;
2462 }
2463 numberresult = numberresults;
2464 }
2465
2466 /* step 3: format numbers and figure out how large a buffer we need */
2467 for (f = format; *f; f++) {
2468 if (*f == '%') {
2469 const char* p;
2470 int longflag;
2471 int longlongflag;
2472 int size_tflag;
2473 int numprinted;
2474
2475 p = f;
2476 zeropad = (f[1] == '0');
2477 f = parse_format_flags(f, &width, &precision,
2478 &longflag, &longlongflag, &size_tflag);
2479 switch (*f) {
2480 case 'c':
2481 {
2482 Py_UCS4 ordinal = va_arg(count, int);
Victor Stinnere6abb482012-05-02 01:15:40 +02002483 maxchar = MAX_MAXCHAR(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002484 n++;
2485 break;
2486 }
2487 case '%':
2488 n++;
2489 break;
2490 case 'i':
2491 case 'd':
2492 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2493 width, precision, *f);
2494 if (longflag)
2495 numprinted = sprintf(numberresult, fmt,
2496 va_arg(count, long));
2497#ifdef HAVE_LONG_LONG
2498 else if (longlongflag)
2499 numprinted = sprintf(numberresult, fmt,
2500 va_arg(count, PY_LONG_LONG));
2501#endif
2502 else if (size_tflag)
2503 numprinted = sprintf(numberresult, fmt,
2504 va_arg(count, Py_ssize_t));
2505 else
2506 numprinted = sprintf(numberresult, fmt,
2507 va_arg(count, int));
2508 n += numprinted;
2509 /* advance by +1 to skip over the '\0' */
2510 numberresult += (numprinted + 1);
2511 assert(*(numberresult - 1) == '\0');
2512 assert(*(numberresult - 2) != '\0');
2513 assert(numprinted >= 0);
2514 assert(numberresult <= numberresults + numbersize);
2515 break;
2516 case 'u':
2517 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2518 width, precision, 'u');
2519 if (longflag)
2520 numprinted = sprintf(numberresult, fmt,
2521 va_arg(count, unsigned long));
2522#ifdef HAVE_LONG_LONG
2523 else if (longlongflag)
2524 numprinted = sprintf(numberresult, fmt,
2525 va_arg(count, unsigned PY_LONG_LONG));
2526#endif
2527 else if (size_tflag)
2528 numprinted = sprintf(numberresult, fmt,
2529 va_arg(count, size_t));
2530 else
2531 numprinted = sprintf(numberresult, fmt,
2532 va_arg(count, unsigned 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 'x':
2541 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2542 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2543 n += numprinted;
2544 numberresult += (numprinted + 1);
2545 assert(*(numberresult - 1) == '\0');
2546 assert(*(numberresult - 2) != '\0');
2547 assert(numprinted >= 0);
2548 assert(numberresult <= numberresults + numbersize);
2549 break;
2550 case 'p':
2551 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2552 /* %p is ill-defined: ensure leading 0x. */
2553 if (numberresult[1] == 'X')
2554 numberresult[1] = 'x';
2555 else if (numberresult[1] != 'x') {
2556 memmove(numberresult + 2, numberresult,
2557 strlen(numberresult) + 1);
2558 numberresult[0] = '0';
2559 numberresult[1] = 'x';
2560 numprinted += 2;
2561 }
2562 n += numprinted;
2563 numberresult += (numprinted + 1);
2564 assert(*(numberresult - 1) == '\0');
2565 assert(*(numberresult - 2) != '\0');
2566 assert(numprinted >= 0);
2567 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002568 break;
2569 case 's':
2570 {
2571 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002572 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002573 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002574 if (!str)
2575 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002576 /* since PyUnicode_DecodeUTF8 returns already flexible
2577 unicode objects, there is no need to call ready on them */
2578 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Victor Stinnere6abb482012-05-02 01:15:40 +02002579 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002580 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002581 /* Remember the str and switch to the next slot */
2582 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002583 break;
2584 }
2585 case 'U':
2586 {
2587 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002588 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002589 if (PyUnicode_READY(obj) == -1)
2590 goto fail;
2591 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002592 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002593 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002594 break;
2595 }
2596 case 'V':
2597 {
2598 PyObject *obj = va_arg(count, PyObject *);
2599 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002600 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002601 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002602 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002603 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002604 if (PyUnicode_READY(obj) == -1)
2605 goto fail;
2606 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002607 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002608 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002609 *callresult++ = NULL;
2610 }
2611 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002612 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002613 if (!str_obj)
2614 goto fail;
Benjamin Petersonbac79492012-01-14 13:34:47 -05002615 if (PyUnicode_READY(str_obj) == -1) {
Victor Stinnere1335c72011-10-04 20:53:03 +02002616 Py_DECREF(str_obj);
2617 goto fail;
2618 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002619 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Victor Stinnere6abb482012-05-02 01:15:40 +02002620 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002621 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002622 *callresult++ = str_obj;
2623 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002624 break;
2625 }
2626 case 'S':
2627 {
2628 PyObject *obj = va_arg(count, PyObject *);
2629 PyObject *str;
2630 assert(obj);
2631 str = PyObject_Str(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002632 if (!str)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002633 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002634 if (PyUnicode_READY(str) == -1) {
2635 Py_DECREF(str);
2636 goto fail;
2637 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002638 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Victor Stinnere6abb482012-05-02 01:15:40 +02002639 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002640 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002641 /* Remember the str and switch to the next slot */
2642 *callresult++ = str;
2643 break;
2644 }
2645 case 'R':
2646 {
2647 PyObject *obj = va_arg(count, PyObject *);
2648 PyObject *repr;
2649 assert(obj);
2650 repr = PyObject_Repr(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002651 if (!repr)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002652 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002653 if (PyUnicode_READY(repr) == -1) {
2654 Py_DECREF(repr);
2655 goto fail;
2656 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002657 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Victor Stinnere6abb482012-05-02 01:15:40 +02002658 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002659 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002660 /* Remember the repr and switch to the next slot */
2661 *callresult++ = repr;
2662 break;
2663 }
2664 case 'A':
2665 {
2666 PyObject *obj = va_arg(count, PyObject *);
2667 PyObject *ascii;
2668 assert(obj);
2669 ascii = PyObject_ASCII(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002670 if (!ascii)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002671 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002672 if (PyUnicode_READY(ascii) == -1) {
2673 Py_DECREF(ascii);
2674 goto fail;
2675 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002676 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Victor Stinnere6abb482012-05-02 01:15:40 +02002677 maxchar = MAX_MAXCHAR(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002678 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002679 /* Remember the repr and switch to the next slot */
2680 *callresult++ = ascii;
2681 break;
2682 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002683 default:
2684 /* if we stumble upon an unknown
2685 formatting code, copy the rest of
2686 the format string to the output
2687 string. (we cannot just skip the
2688 code, since there's no way to know
2689 what's in the argument list) */
2690 n += strlen(p);
2691 goto expand;
2692 }
2693 } else
2694 n++;
2695 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002696 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002697 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002698 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002699 we don't have to resize the string.
2700 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002701 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002702 if (!string)
2703 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002704 kind = PyUnicode_KIND(string);
2705 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002706 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002707 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002708
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002709 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002710 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002711 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002712
2713 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002714 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2715 /* checking for == because the last argument could be a empty
2716 string, which causes i to point to end, the assert at the end of
2717 the loop */
2718 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002719
Benjamin Peterson14339b62009-01-31 16:36:08 +00002720 switch (*f) {
2721 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002722 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002723 const int ordinal = va_arg(vargs, int);
2724 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002725 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002726 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002727 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002728 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002729 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002730 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002731 case 'p':
Victor Stinnerc5166102012-02-22 13:55:02 +01002732 {
Victor Stinner184252a2012-06-16 02:57:41 +02002733 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002734 /* unused, since we already have the result */
2735 if (*f == 'p')
2736 (void) va_arg(vargs, void *);
2737 else
2738 (void) va_arg(vargs, int);
2739 /* extract the result from numberresults and append. */
Victor Stinner184252a2012-06-16 02:57:41 +02002740 len = strlen(numberresult);
2741 unicode_write_cstr(string, i, numberresult, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002742 /* skip over the separating '\0' */
Victor Stinner184252a2012-06-16 02:57:41 +02002743 i += len;
2744 numberresult += len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002745 assert(*numberresult == '\0');
2746 numberresult++;
2747 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002748 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002749 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002750 case 's':
2751 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002752 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002753 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002754 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002755 size = PyUnicode_GET_LENGTH(*callresult);
2756 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002757 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002758 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002759 /* We're done with the unicode()/repr() => forget it */
2760 Py_DECREF(*callresult);
2761 /* switch to next unicode()/repr() result */
2762 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002763 break;
2764 }
2765 case 'U':
2766 {
2767 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002768 Py_ssize_t size;
2769 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2770 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerd3f08822012-05-29 12:57:52 +02002771 _PyUnicode_FastCopyCharacters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002772 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002773 break;
2774 }
2775 case 'V':
2776 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002777 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002778 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002779 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002780 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002781 size = PyUnicode_GET_LENGTH(obj);
2782 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002783 _PyUnicode_FastCopyCharacters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002784 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002785 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002786 size = PyUnicode_GET_LENGTH(*callresult);
2787 assert(PyUnicode_KIND(*callresult) <=
2788 PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002789 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002790 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002791 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002792 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002793 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002794 break;
2795 }
2796 case 'S':
2797 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002798 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002799 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002800 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002801 /* unused, since we already have the result */
2802 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002803 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerd3f08822012-05-29 12:57:52 +02002804 _PyUnicode_FastCopyCharacters(string, i, *callresult, 0, size);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002805 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002806 /* We're done with the unicode()/repr() => forget it */
2807 Py_DECREF(*callresult);
2808 /* switch to next unicode()/repr() result */
2809 ++callresult;
2810 break;
2811 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002812 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002813 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002814 break;
2815 default:
Victor Stinner184252a2012-06-16 02:57:41 +02002816 {
2817 Py_ssize_t len = strlen(p);
2818 unicode_write_cstr(string, i, p, len);
2819 i += len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002820 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002821 goto end;
2822 }
Victor Stinner184252a2012-06-16 02:57:41 +02002823 }
Victor Stinner1205f272010-09-11 00:54:47 +00002824 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002825 else {
2826 assert(i < PyUnicode_GET_LENGTH(string));
2827 PyUnicode_WRITE(kind, data, i++, *f);
2828 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002829 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002830 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002831
Benjamin Peterson29060642009-01-31 22:14:21 +00002832 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002833 if (callresults)
2834 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002835 if (numberresults)
2836 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002837 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002838 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002839 if (callresults) {
2840 PyObject **callresult2 = callresults;
2841 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002842 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002843 ++callresult2;
2844 }
2845 PyObject_Free(callresults);
2846 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002847 if (numberresults)
2848 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002849 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002850}
2851
Walter Dörwaldd2034312007-05-18 16:29:38 +00002852PyObject *
2853PyUnicode_FromFormat(const char *format, ...)
2854{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002855 PyObject* ret;
2856 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002857
2858#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002859 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002860#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002861 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002862#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002863 ret = PyUnicode_FromFormatV(format, vargs);
2864 va_end(vargs);
2865 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002866}
2867
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002868#ifdef HAVE_WCHAR_H
2869
Victor Stinner5593d8a2010-10-02 11:11:27 +00002870/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2871 convert a Unicode object to a wide character string.
2872
Victor Stinnerd88d9832011-09-06 02:00:05 +02002873 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002874 character) required to convert the unicode object. Ignore size argument.
2875
Victor Stinnerd88d9832011-09-06 02:00:05 +02002876 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002877 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002878 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002879static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002880unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002881 wchar_t *w,
2882 Py_ssize_t size)
2883{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002884 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002885 const wchar_t *wstr;
2886
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002887 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002888 if (wstr == NULL)
2889 return -1;
2890
Victor Stinner5593d8a2010-10-02 11:11:27 +00002891 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002892 if (size > res)
2893 size = res + 1;
2894 else
2895 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002896 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002897 return res;
2898 }
2899 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002900 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002901}
2902
2903Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002904PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002905 wchar_t *w,
2906 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002907{
2908 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002909 PyErr_BadInternalCall();
2910 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002911 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002912 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002913}
2914
Victor Stinner137c34c2010-09-29 10:25:54 +00002915wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002916PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002917 Py_ssize_t *size)
2918{
2919 wchar_t* buffer;
2920 Py_ssize_t buflen;
2921
2922 if (unicode == NULL) {
2923 PyErr_BadInternalCall();
2924 return NULL;
2925 }
2926
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002927 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002928 if (buflen == -1)
2929 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002930 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002931 PyErr_NoMemory();
2932 return NULL;
2933 }
2934
Victor Stinner137c34c2010-09-29 10:25:54 +00002935 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2936 if (buffer == NULL) {
2937 PyErr_NoMemory();
2938 return NULL;
2939 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002940 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002941 if (buflen == -1)
2942 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002943 if (size != NULL)
2944 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002945 return buffer;
2946}
2947
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002948#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002949
Alexander Belopolsky40018472011-02-26 01:02:56 +00002950PyObject *
2951PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002952{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002953 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002954 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002955 PyErr_SetString(PyExc_ValueError,
2956 "chr() arg not in range(0x110000)");
2957 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002958 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002959
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002960 if (ordinal < 256)
2961 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002962
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002963 v = PyUnicode_New(1, ordinal);
2964 if (v == NULL)
2965 return NULL;
2966 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002967 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002968 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002969}
2970
Alexander Belopolsky40018472011-02-26 01:02:56 +00002971PyObject *
2972PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002973{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002974 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002975 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002976 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002977 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002978 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002979 Py_INCREF(obj);
2980 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002981 }
2982 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002983 /* For a Unicode subtype that's not a Unicode object,
2984 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002985 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002986 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002987 PyErr_Format(PyExc_TypeError,
2988 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002989 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002990 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002991}
2992
Alexander Belopolsky40018472011-02-26 01:02:56 +00002993PyObject *
2994PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002995 const char *encoding,
2996 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002997{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002998 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002999 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003000
Guido van Rossumd57fd912000-03-10 22:53:23 +00003001 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003002 PyErr_BadInternalCall();
3003 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003004 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003005
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003006 /* Decoding bytes objects is the most common case and should be fast */
3007 if (PyBytes_Check(obj)) {
3008 if (PyBytes_GET_SIZE(obj) == 0) {
3009 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02003010 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003011 }
3012 else {
3013 v = PyUnicode_Decode(
3014 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3015 encoding, errors);
3016 }
3017 return v;
3018 }
3019
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003020 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003021 PyErr_SetString(PyExc_TypeError,
3022 "decoding str is not supported");
3023 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003024 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003025
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003026 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3027 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3028 PyErr_Format(PyExc_TypeError,
3029 "coercing to str: need bytes, bytearray "
3030 "or buffer-like object, %.80s found",
3031 Py_TYPE(obj)->tp_name);
3032 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003033 }
Tim Petersced69f82003-09-16 20:30:58 +00003034
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003035 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003036 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02003037 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003038 }
Tim Petersced69f82003-09-16 20:30:58 +00003039 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003040 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003041
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003042 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003043 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003044}
3045
Victor Stinner600d3be2010-06-10 12:00:55 +00003046/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00003047 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
3048 1 on success. */
3049static int
3050normalize_encoding(const char *encoding,
3051 char *lower,
3052 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003053{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003054 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003055 char *l;
3056 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003057
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04003058 if (encoding == NULL) {
3059 strcpy(lower, "utf-8");
3060 return 1;
3061 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003062 e = encoding;
3063 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003064 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00003065 while (*e) {
3066 if (l == l_end)
3067 return 0;
David Malcolm96960882010-11-05 17:23:41 +00003068 if (Py_ISUPPER(*e)) {
3069 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003070 }
3071 else if (*e == '_') {
3072 *l++ = '-';
3073 e++;
3074 }
3075 else {
3076 *l++ = *e++;
3077 }
3078 }
3079 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003080 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003081}
3082
Alexander Belopolsky40018472011-02-26 01:02:56 +00003083PyObject *
3084PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003085 Py_ssize_t size,
3086 const char *encoding,
3087 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003088{
3089 PyObject *buffer = NULL, *unicode;
3090 Py_buffer info;
3091 char lower[11]; /* Enough for any encoding shortcut */
3092
Fred Drakee4315f52000-05-09 19:53:39 +00003093 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003094 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003095 if ((strcmp(lower, "utf-8") == 0) ||
3096 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003097 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003098 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003099 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003100 (strcmp(lower, "iso-8859-1") == 0))
3101 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003102#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003103 else if (strcmp(lower, "mbcs") == 0)
3104 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003105#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003106 else if (strcmp(lower, "ascii") == 0)
3107 return PyUnicode_DecodeASCII(s, size, errors);
3108 else if (strcmp(lower, "utf-16") == 0)
3109 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3110 else if (strcmp(lower, "utf-32") == 0)
3111 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3112 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003113
3114 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003115 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003116 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003117 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003118 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003119 if (buffer == NULL)
3120 goto onError;
3121 unicode = PyCodec_Decode(buffer, encoding, errors);
3122 if (unicode == NULL)
3123 goto onError;
3124 if (!PyUnicode_Check(unicode)) {
3125 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003126 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003127 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003128 Py_DECREF(unicode);
3129 goto onError;
3130 }
3131 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003132 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003133
Benjamin Peterson29060642009-01-31 22:14:21 +00003134 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003135 Py_XDECREF(buffer);
3136 return NULL;
3137}
3138
Alexander Belopolsky40018472011-02-26 01:02:56 +00003139PyObject *
3140PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003141 const char *encoding,
3142 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003143{
3144 PyObject *v;
3145
3146 if (!PyUnicode_Check(unicode)) {
3147 PyErr_BadArgument();
3148 goto onError;
3149 }
3150
3151 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003152 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003153
3154 /* Decode via the codec registry */
3155 v = PyCodec_Decode(unicode, encoding, errors);
3156 if (v == NULL)
3157 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003158 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003159
Benjamin Peterson29060642009-01-31 22:14:21 +00003160 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003161 return NULL;
3162}
3163
Alexander Belopolsky40018472011-02-26 01:02:56 +00003164PyObject *
3165PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003166 const char *encoding,
3167 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003168{
3169 PyObject *v;
3170
3171 if (!PyUnicode_Check(unicode)) {
3172 PyErr_BadArgument();
3173 goto onError;
3174 }
3175
3176 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003177 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003178
3179 /* Decode via the codec registry */
3180 v = PyCodec_Decode(unicode, encoding, errors);
3181 if (v == NULL)
3182 goto onError;
3183 if (!PyUnicode_Check(v)) {
3184 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003185 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003186 Py_TYPE(v)->tp_name);
3187 Py_DECREF(v);
3188 goto onError;
3189 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003190 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003191
Benjamin Peterson29060642009-01-31 22:14:21 +00003192 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003193 return NULL;
3194}
3195
Alexander Belopolsky40018472011-02-26 01:02:56 +00003196PyObject *
3197PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003198 Py_ssize_t size,
3199 const char *encoding,
3200 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003201{
3202 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003203
Guido van Rossumd57fd912000-03-10 22:53:23 +00003204 unicode = PyUnicode_FromUnicode(s, size);
3205 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003206 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003207 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3208 Py_DECREF(unicode);
3209 return v;
3210}
3211
Alexander Belopolsky40018472011-02-26 01:02:56 +00003212PyObject *
3213PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003214 const char *encoding,
3215 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003216{
3217 PyObject *v;
3218
3219 if (!PyUnicode_Check(unicode)) {
3220 PyErr_BadArgument();
3221 goto onError;
3222 }
3223
3224 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003225 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003226
3227 /* Encode via the codec registry */
3228 v = PyCodec_Encode(unicode, encoding, errors);
3229 if (v == NULL)
3230 goto onError;
3231 return v;
3232
Benjamin Peterson29060642009-01-31 22:14:21 +00003233 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003234 return NULL;
3235}
3236
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003237static size_t
3238wcstombs_errorpos(const wchar_t *wstr)
3239{
3240 size_t len;
3241#if SIZEOF_WCHAR_T == 2
3242 wchar_t buf[3];
3243#else
3244 wchar_t buf[2];
3245#endif
3246 char outbuf[MB_LEN_MAX];
3247 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003248
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003249#if SIZEOF_WCHAR_T == 2
3250 buf[2] = 0;
3251#else
3252 buf[1] = 0;
3253#endif
3254 start = wstr;
3255 while (*wstr != L'\0')
3256 {
3257 previous = wstr;
3258#if SIZEOF_WCHAR_T == 2
3259 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3260 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3261 {
3262 buf[0] = wstr[0];
3263 buf[1] = wstr[1];
3264 wstr += 2;
3265 }
3266 else {
3267 buf[0] = *wstr;
3268 buf[1] = 0;
3269 wstr++;
3270 }
3271#else
3272 buf[0] = *wstr;
3273 wstr++;
3274#endif
3275 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003276 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003277 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003278 }
3279
3280 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003281 return 0;
3282}
3283
Victor Stinner1b579672011-12-17 05:47:23 +01003284static int
3285locale_error_handler(const char *errors, int *surrogateescape)
3286{
3287 if (errors == NULL) {
3288 *surrogateescape = 0;
3289 return 0;
3290 }
3291
3292 if (strcmp(errors, "strict") == 0) {
3293 *surrogateescape = 0;
3294 return 0;
3295 }
3296 if (strcmp(errors, "surrogateescape") == 0) {
3297 *surrogateescape = 1;
3298 return 0;
3299 }
3300 PyErr_Format(PyExc_ValueError,
3301 "only 'strict' and 'surrogateescape' error handlers "
3302 "are supported, not '%s'",
3303 errors);
3304 return -1;
3305}
3306
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003307PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003308PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003309{
3310 Py_ssize_t wlen, wlen2;
3311 wchar_t *wstr;
3312 PyObject *bytes = NULL;
3313 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003314 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003315 PyObject *exc;
3316 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003317 int surrogateescape;
3318
3319 if (locale_error_handler(errors, &surrogateescape) < 0)
3320 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003321
3322 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3323 if (wstr == NULL)
3324 return NULL;
3325
3326 wlen2 = wcslen(wstr);
3327 if (wlen2 != wlen) {
3328 PyMem_Free(wstr);
3329 PyErr_SetString(PyExc_TypeError, "embedded null character");
3330 return NULL;
3331 }
3332
3333 if (surrogateescape) {
3334 /* locale encoding with surrogateescape */
3335 char *str;
3336
3337 str = _Py_wchar2char(wstr, &error_pos);
3338 if (str == NULL) {
3339 if (error_pos == (size_t)-1) {
3340 PyErr_NoMemory();
3341 PyMem_Free(wstr);
3342 return NULL;
3343 }
3344 else {
3345 goto encode_error;
3346 }
3347 }
3348 PyMem_Free(wstr);
3349
3350 bytes = PyBytes_FromString(str);
3351 PyMem_Free(str);
3352 }
3353 else {
3354 size_t len, len2;
3355
3356 len = wcstombs(NULL, wstr, 0);
3357 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003358 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003359 goto encode_error;
3360 }
3361
3362 bytes = PyBytes_FromStringAndSize(NULL, len);
3363 if (bytes == NULL) {
3364 PyMem_Free(wstr);
3365 return NULL;
3366 }
3367
3368 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3369 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003370 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003371 goto encode_error;
3372 }
3373 PyMem_Free(wstr);
3374 }
3375 return bytes;
3376
3377encode_error:
3378 errmsg = strerror(errno);
3379 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003380
3381 if (error_pos == (size_t)-1)
3382 error_pos = wcstombs_errorpos(wstr);
3383
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003384 PyMem_Free(wstr);
3385 Py_XDECREF(bytes);
3386
Victor Stinner2f197072011-12-17 07:08:30 +01003387 if (errmsg != NULL) {
3388 size_t errlen;
3389 wstr = _Py_char2wchar(errmsg, &errlen);
3390 if (wstr != NULL) {
3391 reason = PyUnicode_FromWideChar(wstr, errlen);
3392 PyMem_Free(wstr);
3393 } else
3394 errmsg = NULL;
3395 }
3396 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003397 reason = PyUnicode_FromString(
3398 "wcstombs() encountered an unencodable "
3399 "wide character");
3400 if (reason == NULL)
3401 return NULL;
3402
3403 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3404 "locale", unicode,
3405 (Py_ssize_t)error_pos,
3406 (Py_ssize_t)(error_pos+1),
3407 reason);
3408 Py_DECREF(reason);
3409 if (exc != NULL) {
3410 PyCodec_StrictErrors(exc);
3411 Py_XDECREF(exc);
3412 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003413 return NULL;
3414}
3415
Victor Stinnerad158722010-10-27 00:25:46 +00003416PyObject *
3417PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003418{
Victor Stinner99b95382011-07-04 14:23:54 +02003419#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003420 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003421#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003422 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003423#else
Victor Stinner793b5312011-04-27 00:24:21 +02003424 PyInterpreterState *interp = PyThreadState_GET()->interp;
3425 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3426 cannot use it to encode and decode filenames before it is loaded. Load
3427 the Python codec requires to encode at least its own filename. Use the C
3428 version of the locale codec until the codec registry is initialized and
3429 the Python codec is loaded.
3430
3431 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3432 cannot only rely on it: check also interp->fscodec_initialized for
3433 subinterpreters. */
3434 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003435 return PyUnicode_AsEncodedString(unicode,
3436 Py_FileSystemDefaultEncoding,
3437 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003438 }
3439 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003440 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003441 }
Victor Stinnerad158722010-10-27 00:25:46 +00003442#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003443}
3444
Alexander Belopolsky40018472011-02-26 01:02:56 +00003445PyObject *
3446PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003447 const char *encoding,
3448 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003449{
3450 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003451 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003452
Guido van Rossumd57fd912000-03-10 22:53:23 +00003453 if (!PyUnicode_Check(unicode)) {
3454 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003455 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003456 }
Fred Drakee4315f52000-05-09 19:53:39 +00003457
Fred Drakee4315f52000-05-09 19:53:39 +00003458 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003459 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003460 if ((strcmp(lower, "utf-8") == 0) ||
3461 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003462 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003463 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003464 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003465 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003466 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003467 }
Victor Stinner37296e82010-06-10 13:36:23 +00003468 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003469 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003470 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003471 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003472#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003473 else if (strcmp(lower, "mbcs") == 0)
3474 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003475#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003476 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003477 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003478 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003479
3480 /* Encode via the codec registry */
3481 v = PyCodec_Encode(unicode, encoding, errors);
3482 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003483 return NULL;
3484
3485 /* The normal path */
3486 if (PyBytes_Check(v))
3487 return v;
3488
3489 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003490 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003491 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003492 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003493
3494 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3495 "encoder %s returned bytearray instead of bytes",
3496 encoding);
3497 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003498 Py_DECREF(v);
3499 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003500 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003501
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003502 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3503 Py_DECREF(v);
3504 return b;
3505 }
3506
3507 PyErr_Format(PyExc_TypeError,
3508 "encoder did not return a bytes object (type=%.400s)",
3509 Py_TYPE(v)->tp_name);
3510 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003511 return NULL;
3512}
3513
Alexander Belopolsky40018472011-02-26 01:02:56 +00003514PyObject *
3515PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003516 const char *encoding,
3517 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003518{
3519 PyObject *v;
3520
3521 if (!PyUnicode_Check(unicode)) {
3522 PyErr_BadArgument();
3523 goto onError;
3524 }
3525
3526 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003527 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003528
3529 /* Encode via the codec registry */
3530 v = PyCodec_Encode(unicode, encoding, errors);
3531 if (v == NULL)
3532 goto onError;
3533 if (!PyUnicode_Check(v)) {
3534 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003535 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003536 Py_TYPE(v)->tp_name);
3537 Py_DECREF(v);
3538 goto onError;
3539 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003540 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003541
Benjamin Peterson29060642009-01-31 22:14:21 +00003542 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003543 return NULL;
3544}
3545
Victor Stinner2f197072011-12-17 07:08:30 +01003546static size_t
3547mbstowcs_errorpos(const char *str, size_t len)
3548{
3549#ifdef HAVE_MBRTOWC
3550 const char *start = str;
3551 mbstate_t mbs;
3552 size_t converted;
3553 wchar_t ch;
3554
3555 memset(&mbs, 0, sizeof mbs);
3556 while (len)
3557 {
3558 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3559 if (converted == 0)
3560 /* Reached end of string */
3561 break;
3562 if (converted == (size_t)-1 || converted == (size_t)-2) {
3563 /* Conversion error or incomplete character */
3564 return str - start;
3565 }
3566 else {
3567 str += converted;
3568 len -= converted;
3569 }
3570 }
3571 /* failed to find the undecodable byte sequence */
3572 return 0;
3573#endif
3574 return 0;
3575}
3576
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003577PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003578PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003579 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003580{
3581 wchar_t smallbuf[256];
3582 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3583 wchar_t *wstr;
3584 size_t wlen, wlen2;
3585 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003586 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003587 size_t error_pos;
3588 char *errmsg;
3589 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003590
3591 if (locale_error_handler(errors, &surrogateescape) < 0)
3592 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003593
3594 if (str[len] != '\0' || len != strlen(str)) {
3595 PyErr_SetString(PyExc_TypeError, "embedded null character");
3596 return NULL;
3597 }
3598
3599 if (surrogateescape)
3600 {
3601 wstr = _Py_char2wchar(str, &wlen);
3602 if (wstr == NULL) {
3603 if (wlen == (size_t)-1)
3604 PyErr_NoMemory();
3605 else
3606 PyErr_SetFromErrno(PyExc_OSError);
3607 return NULL;
3608 }
3609
3610 unicode = PyUnicode_FromWideChar(wstr, wlen);
3611 PyMem_Free(wstr);
3612 }
3613 else {
3614#ifndef HAVE_BROKEN_MBSTOWCS
3615 wlen = mbstowcs(NULL, str, 0);
3616#else
3617 wlen = len;
3618#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003619 if (wlen == (size_t)-1)
3620 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003621 if (wlen+1 <= smallbuf_len) {
3622 wstr = smallbuf;
3623 }
3624 else {
3625 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3626 return PyErr_NoMemory();
3627
3628 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3629 if (!wstr)
3630 return PyErr_NoMemory();
3631 }
3632
3633 /* This shouldn't fail now */
3634 wlen2 = mbstowcs(wstr, str, wlen+1);
3635 if (wlen2 == (size_t)-1) {
3636 if (wstr != smallbuf)
3637 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003638 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003639 }
3640#ifdef HAVE_BROKEN_MBSTOWCS
3641 assert(wlen2 == wlen);
3642#endif
3643 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3644 if (wstr != smallbuf)
3645 PyMem_Free(wstr);
3646 }
3647 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003648
3649decode_error:
3650 errmsg = strerror(errno);
3651 assert(errmsg != NULL);
3652
3653 error_pos = mbstowcs_errorpos(str, len);
3654 if (errmsg != NULL) {
3655 size_t errlen;
3656 wstr = _Py_char2wchar(errmsg, &errlen);
3657 if (wstr != NULL) {
3658 reason = PyUnicode_FromWideChar(wstr, errlen);
3659 PyMem_Free(wstr);
3660 } else
3661 errmsg = NULL;
3662 }
3663 if (errmsg == NULL)
3664 reason = PyUnicode_FromString(
3665 "mbstowcs() encountered an invalid multibyte sequence");
3666 if (reason == NULL)
3667 return NULL;
3668
3669 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3670 "locale", str, len,
3671 (Py_ssize_t)error_pos,
3672 (Py_ssize_t)(error_pos+1),
3673 reason);
3674 Py_DECREF(reason);
3675 if (exc != NULL) {
3676 PyCodec_StrictErrors(exc);
3677 Py_XDECREF(exc);
3678 }
3679 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003680}
3681
3682PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003683PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003684{
3685 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003686 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003687}
3688
3689
3690PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003691PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003692 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003693 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3694}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003695
Christian Heimes5894ba72007-11-04 11:43:14 +00003696PyObject*
3697PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3698{
Victor Stinner99b95382011-07-04 14:23:54 +02003699#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003700 return PyUnicode_DecodeMBCS(s, size, NULL);
3701#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003702 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003703#else
Victor Stinner793b5312011-04-27 00:24:21 +02003704 PyInterpreterState *interp = PyThreadState_GET()->interp;
3705 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3706 cannot use it to encode and decode filenames before it is loaded. Load
3707 the Python codec requires to encode at least its own filename. Use the C
3708 version of the locale codec until the codec registry is initialized and
3709 the Python codec is loaded.
3710
3711 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3712 cannot only rely on it: check also interp->fscodec_initialized for
3713 subinterpreters. */
3714 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003715 return PyUnicode_Decode(s, size,
3716 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003717 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003718 }
3719 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003720 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003721 }
Victor Stinnerad158722010-10-27 00:25:46 +00003722#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003723}
3724
Martin v. Löwis011e8422009-05-05 04:43:17 +00003725
3726int
Antoine Pitrou13348842012-01-29 18:36:34 +01003727_PyUnicode_HasNULChars(PyObject* s)
3728{
3729 static PyObject *nul = NULL;
3730
3731 if (nul == NULL)
3732 nul = PyUnicode_FromStringAndSize("\0", 1);
3733 if (nul == NULL)
3734 return -1;
3735 return PyUnicode_Contains(s, nul);
3736}
3737
3738
3739int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003740PyUnicode_FSConverter(PyObject* arg, void* addr)
3741{
3742 PyObject *output = NULL;
3743 Py_ssize_t size;
3744 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003745 if (arg == NULL) {
3746 Py_DECREF(*(PyObject**)addr);
3747 return 1;
3748 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003749 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003750 output = arg;
3751 Py_INCREF(output);
3752 }
3753 else {
3754 arg = PyUnicode_FromObject(arg);
3755 if (!arg)
3756 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003757 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003758 Py_DECREF(arg);
3759 if (!output)
3760 return 0;
3761 if (!PyBytes_Check(output)) {
3762 Py_DECREF(output);
3763 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3764 return 0;
3765 }
3766 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003767 size = PyBytes_GET_SIZE(output);
3768 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003769 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003770 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003771 Py_DECREF(output);
3772 return 0;
3773 }
3774 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003775 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003776}
3777
3778
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003779int
3780PyUnicode_FSDecoder(PyObject* arg, void* addr)
3781{
3782 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003783 if (arg == NULL) {
3784 Py_DECREF(*(PyObject**)addr);
3785 return 1;
3786 }
3787 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003788 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003789 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003790 output = arg;
3791 Py_INCREF(output);
3792 }
3793 else {
3794 arg = PyBytes_FromObject(arg);
3795 if (!arg)
3796 return 0;
3797 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3798 PyBytes_GET_SIZE(arg));
3799 Py_DECREF(arg);
3800 if (!output)
3801 return 0;
3802 if (!PyUnicode_Check(output)) {
3803 Py_DECREF(output);
3804 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3805 return 0;
3806 }
3807 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003808 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003809 Py_DECREF(output);
3810 return 0;
3811 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003812 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003813 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003814 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3815 Py_DECREF(output);
3816 return 0;
3817 }
3818 *(PyObject**)addr = output;
3819 return Py_CLEANUP_SUPPORTED;
3820}
3821
3822
Martin v. Löwis5b222132007-06-10 09:51:05 +00003823char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003824PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003825{
Christian Heimesf3863112007-11-22 07:46:41 +00003826 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003827
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003828 if (!PyUnicode_Check(unicode)) {
3829 PyErr_BadArgument();
3830 return NULL;
3831 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003832 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003833 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003834
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003835 if (PyUnicode_UTF8(unicode) == NULL) {
3836 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003837 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3838 if (bytes == NULL)
3839 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003840 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3841 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003842 Py_DECREF(bytes);
3843 return NULL;
3844 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003845 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3846 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3847 PyBytes_AS_STRING(bytes),
3848 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003849 Py_DECREF(bytes);
3850 }
3851
3852 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003853 *psize = PyUnicode_UTF8_LENGTH(unicode);
3854 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003855}
3856
3857char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003858PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003859{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003860 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3861}
3862
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003863Py_UNICODE *
3864PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3865{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003866 const unsigned char *one_byte;
3867#if SIZEOF_WCHAR_T == 4
3868 const Py_UCS2 *two_bytes;
3869#else
3870 const Py_UCS4 *four_bytes;
3871 const Py_UCS4 *ucs4_end;
3872 Py_ssize_t num_surrogates;
3873#endif
3874 wchar_t *w;
3875 wchar_t *wchar_end;
3876
3877 if (!PyUnicode_Check(unicode)) {
3878 PyErr_BadArgument();
3879 return NULL;
3880 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003881 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003882 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003883 assert(_PyUnicode_KIND(unicode) != 0);
3884 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003885
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003886 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003887#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003888 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3889 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003890 num_surrogates = 0;
3891
3892 for (; four_bytes < ucs4_end; ++four_bytes) {
3893 if (*four_bytes > 0xFFFF)
3894 ++num_surrogates;
3895 }
3896
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003897 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3898 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3899 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003900 PyErr_NoMemory();
3901 return NULL;
3902 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003903 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003904
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003905 w = _PyUnicode_WSTR(unicode);
3906 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3907 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003908 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3909 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003910 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003911 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003912 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3913 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003914 }
3915 else
3916 *w = *four_bytes;
3917
3918 if (w > wchar_end) {
3919 assert(0 && "Miscalculated string end");
3920 }
3921 }
3922 *w = 0;
3923#else
3924 /* sizeof(wchar_t) == 4 */
3925 Py_FatalError("Impossible unicode object state, wstr and str "
3926 "should share memory already.");
3927 return NULL;
3928#endif
3929 }
3930 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003931 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3932 (_PyUnicode_LENGTH(unicode) + 1));
3933 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003934 PyErr_NoMemory();
3935 return NULL;
3936 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003937 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3938 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3939 w = _PyUnicode_WSTR(unicode);
3940 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003941
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003942 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3943 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003944 for (; w < wchar_end; ++one_byte, ++w)
3945 *w = *one_byte;
3946 /* null-terminate the wstr */
3947 *w = 0;
3948 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003949 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003950#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003951 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003952 for (; w < wchar_end; ++two_bytes, ++w)
3953 *w = *two_bytes;
3954 /* null-terminate the wstr */
3955 *w = 0;
3956#else
3957 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003958 PyObject_FREE(_PyUnicode_WSTR(unicode));
3959 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003960 Py_FatalError("Impossible unicode object state, wstr "
3961 "and str should share memory already.");
3962 return NULL;
3963#endif
3964 }
3965 else {
3966 assert(0 && "This should never happen.");
3967 }
3968 }
3969 }
3970 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003971 *size = PyUnicode_WSTR_LENGTH(unicode);
3972 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003973}
3974
Alexander Belopolsky40018472011-02-26 01:02:56 +00003975Py_UNICODE *
3976PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003977{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003978 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003979}
3980
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003981
Alexander Belopolsky40018472011-02-26 01:02:56 +00003982Py_ssize_t
3983PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003984{
3985 if (!PyUnicode_Check(unicode)) {
3986 PyErr_BadArgument();
3987 goto onError;
3988 }
3989 return PyUnicode_GET_SIZE(unicode);
3990
Benjamin Peterson29060642009-01-31 22:14:21 +00003991 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003992 return -1;
3993}
3994
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003995Py_ssize_t
3996PyUnicode_GetLength(PyObject *unicode)
3997{
Victor Stinner07621332012-06-16 04:53:46 +02003998 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003999 PyErr_BadArgument();
4000 return -1;
4001 }
Victor Stinner07621332012-06-16 04:53:46 +02004002 if (PyUnicode_READY(unicode) == -1)
4003 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004004 return PyUnicode_GET_LENGTH(unicode);
4005}
4006
4007Py_UCS4
4008PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4009{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004010 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4011 PyErr_BadArgument();
4012 return (Py_UCS4)-1;
4013 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004014 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004015 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004016 return (Py_UCS4)-1;
4017 }
4018 return PyUnicode_READ_CHAR(unicode, index);
4019}
4020
4021int
4022PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4023{
4024 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004025 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004026 return -1;
4027 }
Victor Stinner488fa492011-12-12 00:01:39 +01004028 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004029 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004030 PyErr_SetString(PyExc_IndexError, "string index out of range");
4031 return -1;
4032 }
Victor Stinner488fa492011-12-12 00:01:39 +01004033 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004034 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004035 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4036 PyErr_SetString(PyExc_ValueError, "character out of range");
4037 return -1;
4038 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004039 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4040 index, ch);
4041 return 0;
4042}
4043
Alexander Belopolsky40018472011-02-26 01:02:56 +00004044const char *
4045PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004046{
Victor Stinner42cb4622010-09-01 19:39:01 +00004047 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004048}
4049
Victor Stinner554f3f02010-06-16 23:33:54 +00004050/* create or adjust a UnicodeDecodeError */
4051static void
4052make_decode_exception(PyObject **exceptionObject,
4053 const char *encoding,
4054 const char *input, Py_ssize_t length,
4055 Py_ssize_t startpos, Py_ssize_t endpos,
4056 const char *reason)
4057{
4058 if (*exceptionObject == NULL) {
4059 *exceptionObject = PyUnicodeDecodeError_Create(
4060 encoding, input, length, startpos, endpos, reason);
4061 }
4062 else {
4063 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4064 goto onError;
4065 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4066 goto onError;
4067 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4068 goto onError;
4069 }
4070 return;
4071
4072onError:
4073 Py_DECREF(*exceptionObject);
4074 *exceptionObject = NULL;
4075}
4076
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004077/* error handling callback helper:
4078 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004079 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004080 and adjust various state variables.
4081 return 0 on success, -1 on error
4082*/
4083
Alexander Belopolsky40018472011-02-26 01:02:56 +00004084static int
4085unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004086 const char *encoding, const char *reason,
4087 const char **input, const char **inend, Py_ssize_t *startinpos,
4088 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004089 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004090{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004091 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004092
4093 PyObject *restuple = NULL;
4094 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004095 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004096 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004097 Py_ssize_t requiredsize;
4098 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004099 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004100 int res = -1;
4101
Victor Stinner596a6c42011-11-09 00:02:18 +01004102 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4103 outsize = PyUnicode_GET_LENGTH(*output);
4104 else
4105 outsize = _PyUnicode_WSTR_LENGTH(*output);
4106
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004107 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004108 *errorHandler = PyCodec_LookupError(errors);
4109 if (*errorHandler == NULL)
4110 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004111 }
4112
Victor Stinner554f3f02010-06-16 23:33:54 +00004113 make_decode_exception(exceptionObject,
4114 encoding,
4115 *input, *inend - *input,
4116 *startinpos, *endinpos,
4117 reason);
4118 if (*exceptionObject == NULL)
4119 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004120
4121 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4122 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004123 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004124 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004125 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004126 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004127 }
4128 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004129 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004130 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004131 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004132
4133 /* Copy back the bytes variables, which might have been modified by the
4134 callback */
4135 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4136 if (!inputobj)
4137 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004138 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004139 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004140 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004141 *input = PyBytes_AS_STRING(inputobj);
4142 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004143 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004144 /* we can DECREF safely, as the exception has another reference,
4145 so the object won't go away. */
4146 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004147
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004148 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004149 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004150 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004151 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4152 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004153 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004154
Victor Stinner596a6c42011-11-09 00:02:18 +01004155 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4156 /* need more space? (at least enough for what we
4157 have+the replacement+the rest of the string (starting
4158 at the new input position), so we won't have to check space
4159 when there are no errors in the rest of the string) */
4160 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4161 requiredsize = *outpos + replen + insize-newpos;
4162 if (requiredsize > outsize) {
4163 if (requiredsize<2*outsize)
4164 requiredsize = 2*outsize;
4165 if (unicode_resize(output, requiredsize) < 0)
4166 goto onError;
4167 }
Victor Stinner1b487b42012-05-03 12:29:04 +02004168 if (unicode_widen(output, *outpos,
4169 PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004170 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004171 _PyUnicode_FastCopyCharacters(*output, *outpos, repunicode, 0, replen);
Victor Stinner596a6c42011-11-09 00:02:18 +01004172 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004173 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004174 else {
4175 wchar_t *repwstr;
4176 Py_ssize_t repwlen;
4177 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4178 if (repwstr == NULL)
4179 goto onError;
4180 /* need more space? (at least enough for what we
4181 have+the replacement+the rest of the string (starting
4182 at the new input position), so we won't have to check space
4183 when there are no errors in the rest of the string) */
4184 requiredsize = *outpos + repwlen + insize-newpos;
4185 if (requiredsize > outsize) {
4186 if (requiredsize < 2*outsize)
4187 requiredsize = 2*outsize;
4188 if (unicode_resize(output, requiredsize) < 0)
4189 goto onError;
4190 }
4191 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4192 *outpos += repwlen;
4193 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004194 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004195 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004196
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004197 /* we made it! */
4198 res = 0;
4199
Benjamin Peterson29060642009-01-31 22:14:21 +00004200 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004201 Py_XDECREF(restuple);
4202 return res;
4203}
4204
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004205/* --- UTF-7 Codec -------------------------------------------------------- */
4206
Antoine Pitrou244651a2009-05-04 18:56:13 +00004207/* See RFC2152 for details. We encode conservatively and decode liberally. */
4208
4209/* Three simple macros defining base-64. */
4210
4211/* Is c a base-64 character? */
4212
4213#define IS_BASE64(c) \
4214 (((c) >= 'A' && (c) <= 'Z') || \
4215 ((c) >= 'a' && (c) <= 'z') || \
4216 ((c) >= '0' && (c) <= '9') || \
4217 (c) == '+' || (c) == '/')
4218
4219/* given that c is a base-64 character, what is its base-64 value? */
4220
4221#define FROM_BASE64(c) \
4222 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4223 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4224 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4225 (c) == '+' ? 62 : 63)
4226
4227/* What is the base-64 character of the bottom 6 bits of n? */
4228
4229#define TO_BASE64(n) \
4230 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4231
4232/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4233 * decoded as itself. We are permissive on decoding; the only ASCII
4234 * byte not decoding to itself is the + which begins a base64
4235 * string. */
4236
4237#define DECODE_DIRECT(c) \
4238 ((c) <= 127 && (c) != '+')
4239
4240/* The UTF-7 encoder treats ASCII characters differently according to
4241 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4242 * the above). See RFC2152. This array identifies these different
4243 * sets:
4244 * 0 : "Set D"
4245 * alphanumeric and '(),-./:?
4246 * 1 : "Set O"
4247 * !"#$%&*;<=>@[]^_`{|}
4248 * 2 : "whitespace"
4249 * ht nl cr sp
4250 * 3 : special (must be base64 encoded)
4251 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4252 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004253
Tim Petersced69f82003-09-16 20:30:58 +00004254static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004255char utf7_category[128] = {
4256/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4257 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4258/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4259 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4260/* sp ! " # $ % & ' ( ) * + , - . / */
4261 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4262/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4263 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4264/* @ A B C D E F G H I J K L M N O */
4265 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4266/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4267 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4268/* ` a b c d e f g h i j k l m n o */
4269 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4270/* p q r s t u v w x y z { | } ~ del */
4271 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004272};
4273
Antoine Pitrou244651a2009-05-04 18:56:13 +00004274/* ENCODE_DIRECT: this character should be encoded as itself. The
4275 * answer depends on whether we are encoding set O as itself, and also
4276 * on whether we are encoding whitespace as itself. RFC2152 makes it
4277 * clear that the answers to these questions vary between
4278 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004279
Antoine Pitrou244651a2009-05-04 18:56:13 +00004280#define ENCODE_DIRECT(c, directO, directWS) \
4281 ((c) < 128 && (c) > 0 && \
4282 ((utf7_category[(c)] == 0) || \
4283 (directWS && (utf7_category[(c)] == 2)) || \
4284 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004285
Alexander Belopolsky40018472011-02-26 01:02:56 +00004286PyObject *
4287PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004288 Py_ssize_t size,
4289 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004290{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004291 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4292}
4293
Antoine Pitrou244651a2009-05-04 18:56:13 +00004294/* The decoder. The only state we preserve is our read position,
4295 * i.e. how many characters we have consumed. So if we end in the
4296 * middle of a shift sequence we have to back off the read position
4297 * and the output to the beginning of the sequence, otherwise we lose
4298 * all the shift state (seen bits, number of bits seen, high
4299 * surrogate). */
4300
Alexander Belopolsky40018472011-02-26 01:02:56 +00004301PyObject *
4302PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004303 Py_ssize_t size,
4304 const char *errors,
4305 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004306{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004307 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004308 Py_ssize_t startinpos;
4309 Py_ssize_t endinpos;
4310 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004311 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004312 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004313 const char *errmsg = "";
4314 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004315 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004316 unsigned int base64bits = 0;
4317 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004318 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004319 PyObject *errorHandler = NULL;
4320 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004321
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004322 /* Start off assuming it's all ASCII. Widen later as necessary. */
4323 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004324 if (!unicode)
4325 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004326 if (size == 0) {
4327 if (consumed)
4328 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004329 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004330 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004331
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004332 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004333 e = s + size;
4334
4335 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004336 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004337 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004338 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004339
Antoine Pitrou244651a2009-05-04 18:56:13 +00004340 if (inShift) { /* in a base-64 section */
4341 if (IS_BASE64(ch)) { /* consume a base-64 character */
4342 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4343 base64bits += 6;
4344 s++;
4345 if (base64bits >= 16) {
4346 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004347 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004348 base64bits -= 16;
4349 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4350 if (surrogate) {
4351 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004352 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4353 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004354 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4355 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004356 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004357 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004358 }
4359 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004360 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4361 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004362 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004363 }
4364 }
Victor Stinner551ac952011-11-29 22:58:13 +01004365 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004366 /* first surrogate */
4367 surrogate = outCh;
4368 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004369 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004370 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4371 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004372 }
4373 }
4374 }
4375 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004376 inShift = 0;
4377 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004378 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004379 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4380 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004381 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004382 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004383 if (base64bits > 0) { /* left-over bits */
4384 if (base64bits >= 6) {
4385 /* We've seen at least one base-64 character */
4386 errmsg = "partial character in shift sequence";
4387 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004388 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004389 else {
4390 /* Some bits remain; they should be zero */
4391 if (base64buffer != 0) {
4392 errmsg = "non-zero padding bits in shift sequence";
4393 goto utf7Error;
4394 }
4395 }
4396 }
4397 if (ch != '-') {
4398 /* '-' is absorbed; other terminating
4399 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004400 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4401 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004402 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004403 }
4404 }
4405 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004406 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004407 s++; /* consume '+' */
4408 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004409 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004410 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4411 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004412 }
4413 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004414 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004415 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004416 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004417 }
4418 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004419 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004420 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4421 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004422 s++;
4423 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004424 else {
4425 startinpos = s-starts;
4426 s++;
4427 errmsg = "unexpected special character";
4428 goto utf7Error;
4429 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004430 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004431utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004432 endinpos = s-starts;
4433 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004434 errors, &errorHandler,
4435 "utf7", errmsg,
4436 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004437 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004438 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004439 }
4440
Antoine Pitrou244651a2009-05-04 18:56:13 +00004441 /* end of string */
4442
4443 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4444 /* if we're in an inconsistent state, that's an error */
4445 if (surrogate ||
4446 (base64bits >= 6) ||
4447 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004448 endinpos = size;
4449 if (unicode_decode_call_errorhandler(
4450 errors, &errorHandler,
4451 "utf7", "unterminated shift sequence",
4452 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004453 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004454 goto onError;
4455 if (s < e)
4456 goto restart;
4457 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004458 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004459
4460 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004461 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004462 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004463 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004464 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004465 }
4466 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004467 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004468 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004469 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004470
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004471 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004472 goto onError;
4473
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004474 Py_XDECREF(errorHandler);
4475 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004476 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004477
Benjamin Peterson29060642009-01-31 22:14:21 +00004478 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004479 Py_XDECREF(errorHandler);
4480 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004481 Py_DECREF(unicode);
4482 return NULL;
4483}
4484
4485
Alexander Belopolsky40018472011-02-26 01:02:56 +00004486PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004487_PyUnicode_EncodeUTF7(PyObject *str,
4488 int base64SetO,
4489 int base64WhiteSpace,
4490 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004491{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004492 int kind;
4493 void *data;
4494 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004495 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004496 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004497 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004498 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004499 unsigned int base64bits = 0;
4500 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004501 char * out;
4502 char * start;
4503
Benjamin Petersonbac79492012-01-14 13:34:47 -05004504 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004505 return NULL;
4506 kind = PyUnicode_KIND(str);
4507 data = PyUnicode_DATA(str);
4508 len = PyUnicode_GET_LENGTH(str);
4509
4510 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004511 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004512
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004513 /* It might be possible to tighten this worst case */
4514 allocated = 8 * len;
4515 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004516 return PyErr_NoMemory();
4517
Antoine Pitrou244651a2009-05-04 18:56:13 +00004518 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004519 if (v == NULL)
4520 return NULL;
4521
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004522 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004523 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004524 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004525
Antoine Pitrou244651a2009-05-04 18:56:13 +00004526 if (inShift) {
4527 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4528 /* shifting out */
4529 if (base64bits) { /* output remaining bits */
4530 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4531 base64buffer = 0;
4532 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004533 }
4534 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004535 /* Characters not in the BASE64 set implicitly unshift the sequence
4536 so no '-' is required, except if the character is itself a '-' */
4537 if (IS_BASE64(ch) || ch == '-') {
4538 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004539 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004540 *out++ = (char) ch;
4541 }
4542 else {
4543 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004544 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004545 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004546 else { /* not in a shift sequence */
4547 if (ch == '+') {
4548 *out++ = '+';
4549 *out++ = '-';
4550 }
4551 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4552 *out++ = (char) ch;
4553 }
4554 else {
4555 *out++ = '+';
4556 inShift = 1;
4557 goto encode_char;
4558 }
4559 }
4560 continue;
4561encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004562 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004563 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004564
Antoine Pitrou244651a2009-05-04 18:56:13 +00004565 /* code first surrogate */
4566 base64bits += 16;
4567 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4568 while (base64bits >= 6) {
4569 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4570 base64bits -= 6;
4571 }
4572 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004573 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004574 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004575 base64bits += 16;
4576 base64buffer = (base64buffer << 16) | ch;
4577 while (base64bits >= 6) {
4578 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4579 base64bits -= 6;
4580 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004581 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004582 if (base64bits)
4583 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4584 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004585 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004586 if (_PyBytes_Resize(&v, out - start) < 0)
4587 return NULL;
4588 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004589}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004590PyObject *
4591PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4592 Py_ssize_t size,
4593 int base64SetO,
4594 int base64WhiteSpace,
4595 const char *errors)
4596{
4597 PyObject *result;
4598 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4599 if (tmp == NULL)
4600 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004601 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004602 base64WhiteSpace, errors);
4603 Py_DECREF(tmp);
4604 return result;
4605}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004606
Antoine Pitrou244651a2009-05-04 18:56:13 +00004607#undef IS_BASE64
4608#undef FROM_BASE64
4609#undef TO_BASE64
4610#undef DECODE_DIRECT
4611#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004612
Guido van Rossumd57fd912000-03-10 22:53:23 +00004613/* --- UTF-8 Codec -------------------------------------------------------- */
4614
Alexander Belopolsky40018472011-02-26 01:02:56 +00004615PyObject *
4616PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004617 Py_ssize_t size,
4618 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004619{
Walter Dörwald69652032004-09-07 20:24:22 +00004620 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4621}
4622
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004623#include "stringlib/asciilib.h"
4624#include "stringlib/codecs.h"
4625#include "stringlib/undef.h"
4626
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004627#include "stringlib/ucs1lib.h"
4628#include "stringlib/codecs.h"
4629#include "stringlib/undef.h"
4630
4631#include "stringlib/ucs2lib.h"
4632#include "stringlib/codecs.h"
4633#include "stringlib/undef.h"
4634
4635#include "stringlib/ucs4lib.h"
4636#include "stringlib/codecs.h"
4637#include "stringlib/undef.h"
4638
Antoine Pitrouab868312009-01-10 15:40:25 +00004639/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4640#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4641
4642/* Mask to quickly check whether a C 'long' contains a
4643 non-ASCII, UTF8-encoded char. */
4644#if (SIZEOF_LONG == 8)
4645# define ASCII_CHAR_MASK 0x8080808080808080L
4646#elif (SIZEOF_LONG == 4)
4647# define ASCII_CHAR_MASK 0x80808080L
4648#else
4649# error C 'long' size should be either 4 or 8!
4650#endif
4651
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004652static Py_ssize_t
4653ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004654{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004655 const char *p = start;
4656 const char *aligned_end = (const char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004657
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004658#if SIZEOF_LONG <= SIZEOF_VOID_P
4659 assert(!((size_t) dest & LONG_PTR_MASK));
4660 if (!((size_t) p & LONG_PTR_MASK)) {
4661 /* Fast path, see in STRINGLIB(utf8_decode) for
4662 an explanation. */
4663 /* Help register allocation */
4664 register const char *_p = p;
4665 register Py_UCS1 * q = dest;
4666 while (_p < aligned_end) {
4667 unsigned long value = *(const unsigned long *) _p;
4668 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004669 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004670 *((unsigned long *)q) = value;
4671 _p += SIZEOF_LONG;
4672 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004673 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004674 p = _p;
4675 while (p < end) {
4676 if ((unsigned char)*p & 0x80)
4677 break;
4678 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004679 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004680 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004681 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004682#endif
4683 while (p < end) {
4684 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4685 for an explanation. */
4686 if (!((size_t) p & LONG_PTR_MASK)) {
4687 /* Help register allocation */
4688 register const char *_p = p;
4689 while (_p < aligned_end) {
4690 unsigned long value = *(unsigned long *) _p;
4691 if (value & ASCII_CHAR_MASK)
4692 break;
4693 _p += SIZEOF_LONG;
4694 }
4695 p = _p;
4696 if (_p == end)
4697 break;
4698 }
4699 if ((unsigned char)*p & 0x80)
4700 break;
4701 ++p;
4702 }
4703 memcpy(dest, start, p - start);
4704 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004705}
Antoine Pitrouab868312009-01-10 15:40:25 +00004706
Victor Stinner785938e2011-12-11 20:09:03 +01004707PyObject *
4708PyUnicode_DecodeUTF8Stateful(const char *s,
4709 Py_ssize_t size,
4710 const char *errors,
4711 Py_ssize_t *consumed)
4712{
Victor Stinner785938e2011-12-11 20:09:03 +01004713 PyObject *unicode;
Victor Stinner785938e2011-12-11 20:09:03 +01004714 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004715 const char *end = s + size;
4716 Py_ssize_t outpos;
4717
4718 Py_ssize_t startinpos;
4719 Py_ssize_t endinpos;
4720 const char *errmsg = "";
4721 PyObject *errorHandler = NULL;
4722 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004723
4724 if (size == 0) {
4725 if (consumed)
4726 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004727 Py_INCREF(unicode_empty);
4728 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004729 }
4730
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004731 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4732 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004733 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004734 *consumed = 1;
4735 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004736 }
4737
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004738 unicode = PyUnicode_New(size, 127);
Victor Stinner785938e2011-12-11 20:09:03 +01004739 if (!unicode)
4740 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004741
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004742 outpos = ascii_decode(s, end, PyUnicode_1BYTE_DATA(unicode));
4743 s += outpos;
4744 while (s < end) {
4745 Py_UCS4 ch;
4746 int kind = PyUnicode_KIND(unicode);
4747 if (kind == PyUnicode_1BYTE_KIND) {
4748 if (PyUnicode_IS_ASCII(unicode))
4749 ch = asciilib_utf8_decode(&s, end,
4750 PyUnicode_1BYTE_DATA(unicode), &outpos);
4751 else
4752 ch = ucs1lib_utf8_decode(&s, end,
4753 PyUnicode_1BYTE_DATA(unicode), &outpos);
4754 } else if (kind == PyUnicode_2BYTE_KIND) {
4755 ch = ucs2lib_utf8_decode(&s, end,
4756 PyUnicode_2BYTE_DATA(unicode), &outpos);
4757 } else {
4758 assert(kind == PyUnicode_4BYTE_KIND);
4759 ch = ucs4lib_utf8_decode(&s, end,
4760 PyUnicode_4BYTE_DATA(unicode), &outpos);
4761 }
4762
4763 switch (ch) {
4764 case 0:
4765 if (s == end || consumed)
4766 goto End;
4767 errmsg = "unexpected end of data";
4768 startinpos = s - starts;
4769 endinpos = startinpos + 1;
4770 while (endinpos < size && (starts[endinpos] & 0xC0) == 0x80)
4771 endinpos++;
4772 break;
4773 case 1:
4774 errmsg = "invalid start byte";
4775 startinpos = s - starts;
4776 endinpos = startinpos + 1;
4777 break;
4778 case 2:
4779 errmsg = "invalid continuation byte";
4780 startinpos = s - starts;
4781 endinpos = startinpos + 1;
4782 while (endinpos < size && (starts[endinpos] & 0xC0) == 0x80)
4783 endinpos++;
4784 break;
4785 default:
4786 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4787 goto onError;
4788 continue;
4789 }
4790
4791 if (unicode_decode_call_errorhandler(
4792 errors, &errorHandler,
4793 "utf-8", errmsg,
4794 &starts, &end, &startinpos, &endinpos, &exc, &s,
4795 &unicode, &outpos))
4796 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004797 }
4798
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004799End:
4800 if (unicode_resize(&unicode, outpos) < 0)
4801 goto onError;
4802
4803 if (consumed)
4804 *consumed = s - starts;
4805
4806 Py_XDECREF(errorHandler);
4807 Py_XDECREF(exc);
4808 assert(_PyUnicode_CheckConsistency(unicode, 1));
4809 return unicode;
4810
4811onError:
4812 Py_XDECREF(errorHandler);
4813 Py_XDECREF(exc);
4814 Py_XDECREF(unicode);
4815 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004816}
4817
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004818#ifdef __APPLE__
4819
4820/* Simplified UTF-8 decoder using surrogateescape error handler,
4821 used to decode the command line arguments on Mac OS X. */
4822
4823wchar_t*
4824_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4825{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004826 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004827 wchar_t *unicode;
4828 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004829
4830 /* Note: size will always be longer than the resulting Unicode
4831 character count */
4832 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4833 PyErr_NoMemory();
4834 return NULL;
4835 }
4836 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4837 if (!unicode)
4838 return NULL;
4839
4840 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004841 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004842 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004843 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004844 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004845#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004846 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004847#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004848 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004849#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004850 if (ch > 0xFF) {
4851#if SIZEOF_WCHAR_T == 4
4852 assert(0);
4853#else
4854 assert(Py_UNICODE_IS_SURROGATE(ch));
4855 /* compute and append the two surrogates: */
4856 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4857 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4858#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004859 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004860 else {
4861 if (!ch && s == e)
4862 break;
4863 /* surrogateescape */
4864 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4865 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004866 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004867 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004868 return unicode;
4869}
4870
4871#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004872
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004873/* Primary internal function which creates utf8 encoded bytes objects.
4874
4875 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004876 and allocate exactly as much space needed at the end. Else allocate the
4877 maximum possible needed (4 result bytes per Unicode character), and return
4878 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004879*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004880PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004881_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004882{
Victor Stinner6099a032011-12-18 14:22:26 +01004883 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004884 void *data;
4885 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004886
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004887 if (!PyUnicode_Check(unicode)) {
4888 PyErr_BadArgument();
4889 return NULL;
4890 }
4891
4892 if (PyUnicode_READY(unicode) == -1)
4893 return NULL;
4894
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004895 if (PyUnicode_UTF8(unicode))
4896 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4897 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004898
4899 kind = PyUnicode_KIND(unicode);
4900 data = PyUnicode_DATA(unicode);
4901 size = PyUnicode_GET_LENGTH(unicode);
4902
Benjamin Petersonead6b532011-12-20 17:23:42 -06004903 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004904 default:
4905 assert(0);
4906 case PyUnicode_1BYTE_KIND:
4907 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4908 assert(!PyUnicode_IS_ASCII(unicode));
4909 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4910 case PyUnicode_2BYTE_KIND:
4911 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4912 case PyUnicode_4BYTE_KIND:
4913 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004914 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004915}
4916
Alexander Belopolsky40018472011-02-26 01:02:56 +00004917PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004918PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4919 Py_ssize_t size,
4920 const char *errors)
4921{
4922 PyObject *v, *unicode;
4923
4924 unicode = PyUnicode_FromUnicode(s, size);
4925 if (unicode == NULL)
4926 return NULL;
4927 v = _PyUnicode_AsUTF8String(unicode, errors);
4928 Py_DECREF(unicode);
4929 return v;
4930}
4931
4932PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004933PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004934{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004935 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004936}
4937
Walter Dörwald41980ca2007-08-16 21:55:45 +00004938/* --- UTF-32 Codec ------------------------------------------------------- */
4939
4940PyObject *
4941PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004942 Py_ssize_t size,
4943 const char *errors,
4944 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004945{
4946 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4947}
4948
4949PyObject *
4950PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004951 Py_ssize_t size,
4952 const char *errors,
4953 int *byteorder,
4954 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004955{
4956 const char *starts = s;
4957 Py_ssize_t startinpos;
4958 Py_ssize_t endinpos;
4959 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004960 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004961 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004962 int bo = 0; /* assume native ordering by default */
4963 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004964 /* Offsets from q for retrieving bytes in the right order. */
4965#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4966 int iorder[] = {0, 1, 2, 3};
4967#else
4968 int iorder[] = {3, 2, 1, 0};
4969#endif
4970 PyObject *errorHandler = NULL;
4971 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004972
Walter Dörwald41980ca2007-08-16 21:55:45 +00004973 q = (unsigned char *)s;
4974 e = q + size;
4975
4976 if (byteorder)
4977 bo = *byteorder;
4978
4979 /* Check for BOM marks (U+FEFF) in the input and adjust current
4980 byte order setting accordingly. In native mode, the leading BOM
4981 mark is skipped, in all other modes, it is copied to the output
4982 stream as-is (giving a ZWNBSP character). */
4983 if (bo == 0) {
4984 if (size >= 4) {
4985 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004986 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004987#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004988 if (bom == 0x0000FEFF) {
4989 q += 4;
4990 bo = -1;
4991 }
4992 else if (bom == 0xFFFE0000) {
4993 q += 4;
4994 bo = 1;
4995 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004996#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004997 if (bom == 0x0000FEFF) {
4998 q += 4;
4999 bo = 1;
5000 }
5001 else if (bom == 0xFFFE0000) {
5002 q += 4;
5003 bo = -1;
5004 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005005#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005006 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005007 }
5008
5009 if (bo == -1) {
5010 /* force LE */
5011 iorder[0] = 0;
5012 iorder[1] = 1;
5013 iorder[2] = 2;
5014 iorder[3] = 3;
5015 }
5016 else if (bo == 1) {
5017 /* force BE */
5018 iorder[0] = 3;
5019 iorder[1] = 2;
5020 iorder[2] = 1;
5021 iorder[3] = 0;
5022 }
5023
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005024 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005025 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005026 if (!unicode)
5027 return NULL;
5028 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005029 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005030 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005031
Walter Dörwald41980ca2007-08-16 21:55:45 +00005032 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005033 Py_UCS4 ch;
5034 /* remaining bytes at the end? (size should be divisible by 4) */
5035 if (e-q<4) {
5036 if (consumed)
5037 break;
5038 errmsg = "truncated data";
5039 startinpos = ((const char *)q)-starts;
5040 endinpos = ((const char *)e)-starts;
5041 goto utf32Error;
5042 /* The remaining input chars are ignored if the callback
5043 chooses to skip the input */
5044 }
5045 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5046 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005047
Benjamin Peterson29060642009-01-31 22:14:21 +00005048 if (ch >= 0x110000)
5049 {
5050 errmsg = "codepoint not in range(0x110000)";
5051 startinpos = ((const char *)q)-starts;
5052 endinpos = startinpos+4;
5053 goto utf32Error;
5054 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005055 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5056 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005057 q += 4;
5058 continue;
5059 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005060 if (unicode_decode_call_errorhandler(
5061 errors, &errorHandler,
5062 "utf32", errmsg,
5063 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005064 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005065 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005066 }
5067
5068 if (byteorder)
5069 *byteorder = bo;
5070
5071 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005072 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005073
5074 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005075 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005076 goto onError;
5077
5078 Py_XDECREF(errorHandler);
5079 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005080 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005081
Benjamin Peterson29060642009-01-31 22:14:21 +00005082 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005083 Py_DECREF(unicode);
5084 Py_XDECREF(errorHandler);
5085 Py_XDECREF(exc);
5086 return NULL;
5087}
5088
5089PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005090_PyUnicode_EncodeUTF32(PyObject *str,
5091 const char *errors,
5092 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005093{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005094 int kind;
5095 void *data;
5096 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005097 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005098 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005099 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005100 /* Offsets from p for storing byte pairs in the right order. */
5101#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5102 int iorder[] = {0, 1, 2, 3};
5103#else
5104 int iorder[] = {3, 2, 1, 0};
5105#endif
5106
Benjamin Peterson29060642009-01-31 22:14:21 +00005107#define STORECHAR(CH) \
5108 do { \
5109 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5110 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5111 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5112 p[iorder[0]] = (CH) & 0xff; \
5113 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005114 } while(0)
5115
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005116 if (!PyUnicode_Check(str)) {
5117 PyErr_BadArgument();
5118 return NULL;
5119 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005120 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005121 return NULL;
5122 kind = PyUnicode_KIND(str);
5123 data = PyUnicode_DATA(str);
5124 len = PyUnicode_GET_LENGTH(str);
5125
5126 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005127 bytesize = nsize * 4;
5128 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005129 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005130 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005131 if (v == NULL)
5132 return NULL;
5133
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005134 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005135 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005136 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005137 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005138 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005139
5140 if (byteorder == -1) {
5141 /* force LE */
5142 iorder[0] = 0;
5143 iorder[1] = 1;
5144 iorder[2] = 2;
5145 iorder[3] = 3;
5146 }
5147 else if (byteorder == 1) {
5148 /* force BE */
5149 iorder[0] = 3;
5150 iorder[1] = 2;
5151 iorder[2] = 1;
5152 iorder[3] = 0;
5153 }
5154
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005155 for (i = 0; i < len; i++)
5156 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005157
5158 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005159 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005160#undef STORECHAR
5161}
5162
Alexander Belopolsky40018472011-02-26 01:02:56 +00005163PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005164PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5165 Py_ssize_t size,
5166 const char *errors,
5167 int byteorder)
5168{
5169 PyObject *result;
5170 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5171 if (tmp == NULL)
5172 return NULL;
5173 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5174 Py_DECREF(tmp);
5175 return result;
5176}
5177
5178PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005179PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005180{
Victor Stinnerb960b342011-11-20 19:12:52 +01005181 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005182}
5183
Guido van Rossumd57fd912000-03-10 22:53:23 +00005184/* --- UTF-16 Codec ------------------------------------------------------- */
5185
Tim Peters772747b2001-08-09 22:21:55 +00005186PyObject *
5187PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005188 Py_ssize_t size,
5189 const char *errors,
5190 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005191{
Walter Dörwald69652032004-09-07 20:24:22 +00005192 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5193}
5194
5195PyObject *
5196PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005197 Py_ssize_t size,
5198 const char *errors,
5199 int *byteorder,
5200 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005201{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005202 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005203 Py_ssize_t startinpos;
5204 Py_ssize_t endinpos;
5205 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005206 PyObject *unicode;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005207 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005208 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005209 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005210 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005211 PyObject *errorHandler = NULL;
5212 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005213
Tim Peters772747b2001-08-09 22:21:55 +00005214 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005215 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005216
5217 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005218 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005219
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005220 /* Check for BOM marks (U+FEFF) in the input and adjust current
5221 byte order setting accordingly. In native mode, the leading BOM
5222 mark is skipped, in all other modes, it is copied to the output
5223 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005224 if (bo == 0 && size >= 2) {
5225 const Py_UCS4 bom = (q[1] << 8) | q[0];
5226 if (bom == 0xFEFF) {
5227 q += 2;
5228 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005229 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005230 else if (bom == 0xFFFE) {
5231 q += 2;
5232 bo = 1;
5233 }
5234 if (byteorder)
5235 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005236 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005237
Antoine Pitrou63065d72012-05-15 23:48:04 +02005238 if (q == e) {
5239 if (consumed)
5240 *consumed = size;
5241 Py_INCREF(unicode_empty);
5242 return unicode_empty;
Tim Peters772747b2001-08-09 22:21:55 +00005243 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005244
Antoine Pitrouab868312009-01-10 15:40:25 +00005245#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005246 native_ordering = bo <= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005247#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005248 native_ordering = bo >= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005249#endif
Tim Peters772747b2001-08-09 22:21:55 +00005250
Antoine Pitrou63065d72012-05-15 23:48:04 +02005251 /* Note: size will always be longer than the resulting Unicode
5252 character count */
5253 unicode = PyUnicode_New((e - q + 1) / 2, 127);
5254 if (!unicode)
5255 return NULL;
5256
5257 outpos = 0;
5258 while (1) {
5259 Py_UCS4 ch = 0;
5260 if (e - q >= 2) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005261 int kind = PyUnicode_KIND(unicode);
Antoine Pitrou63065d72012-05-15 23:48:04 +02005262 if (kind == PyUnicode_1BYTE_KIND) {
5263 if (PyUnicode_IS_ASCII(unicode))
5264 ch = asciilib_utf16_decode(&q, e,
5265 PyUnicode_1BYTE_DATA(unicode), &outpos,
5266 native_ordering);
5267 else
5268 ch = ucs1lib_utf16_decode(&q, e,
5269 PyUnicode_1BYTE_DATA(unicode), &outpos,
5270 native_ordering);
5271 } else if (kind == PyUnicode_2BYTE_KIND) {
5272 ch = ucs2lib_utf16_decode(&q, e,
5273 PyUnicode_2BYTE_DATA(unicode), &outpos,
5274 native_ordering);
5275 } else {
5276 assert(kind == PyUnicode_4BYTE_KIND);
5277 ch = ucs4lib_utf16_decode(&q, e,
5278 PyUnicode_4BYTE_DATA(unicode), &outpos,
5279 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005280 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005281 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005282
Antoine Pitrou63065d72012-05-15 23:48:04 +02005283 switch (ch)
5284 {
5285 case 0:
5286 /* remaining byte at the end? (size should be even) */
5287 if (q == e || consumed)
5288 goto End;
5289 errmsg = "truncated data";
5290 startinpos = ((const char *)q) - starts;
5291 endinpos = ((const char *)e) - starts;
5292 break;
5293 /* The remaining input chars are ignored if the callback
5294 chooses to skip the input */
5295 case 1:
5296 errmsg = "unexpected end of data";
5297 startinpos = ((const char *)q) - 2 - starts;
5298 endinpos = ((const char *)e) - starts;
5299 break;
5300 case 2:
5301 errmsg = "illegal encoding";
5302 startinpos = ((const char *)q) - 2 - starts;
5303 endinpos = startinpos + 2;
5304 break;
5305 case 3:
5306 errmsg = "illegal UTF-16 surrogate";
5307 startinpos = ((const char *)q) - 4 - starts;
5308 endinpos = startinpos + 2;
5309 break;
5310 default:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005311 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5312 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005313 continue;
5314 }
5315
Benjamin Peterson29060642009-01-31 22:14:21 +00005316 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005317 errors,
5318 &errorHandler,
5319 "utf16", errmsg,
5320 &starts,
5321 (const char **)&e,
5322 &startinpos,
5323 &endinpos,
5324 &exc,
5325 (const char **)&q,
5326 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005327 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005328 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005329 }
5330
Antoine Pitrou63065d72012-05-15 23:48:04 +02005331End:
Walter Dörwald69652032004-09-07 20:24:22 +00005332 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005333 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005334
Guido van Rossumd57fd912000-03-10 22:53:23 +00005335 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005336 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005337 goto onError;
5338
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005339 Py_XDECREF(errorHandler);
5340 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005341 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005342
Benjamin Peterson29060642009-01-31 22:14:21 +00005343 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005344 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005345 Py_XDECREF(errorHandler);
5346 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005347 return NULL;
5348}
5349
Tim Peters772747b2001-08-09 22:21:55 +00005350PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005351_PyUnicode_EncodeUTF16(PyObject *str,
5352 const char *errors,
5353 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005354{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005355 enum PyUnicode_Kind kind;
5356 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005357 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005358 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005359 unsigned short *out;
5360 Py_ssize_t bytesize;
5361 Py_ssize_t pairs;
5362#ifdef WORDS_BIGENDIAN
5363 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005364#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005365 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005366#endif
5367
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005368 if (!PyUnicode_Check(str)) {
5369 PyErr_BadArgument();
5370 return NULL;
5371 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005372 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005373 return NULL;
5374 kind = PyUnicode_KIND(str);
5375 data = PyUnicode_DATA(str);
5376 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005377
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005378 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005379 if (kind == PyUnicode_4BYTE_KIND) {
5380 const Py_UCS4 *in = (const Py_UCS4 *)data;
5381 const Py_UCS4 *end = in + len;
5382 while (in < end)
5383 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005384 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005385 }
5386 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005387 return PyErr_NoMemory();
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005388 bytesize = (len + pairs + (byteorder == 0)) * 2;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005389 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005390 if (v == NULL)
5391 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005392
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005393 /* output buffer is 2-bytes aligned */
5394 assert(((Py_uintptr_t)PyBytes_AS_STRING(v) & 1) == 0);
5395 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005396 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005397 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005398 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005399 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005400
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005401 switch (kind) {
5402 case PyUnicode_1BYTE_KIND: {
5403 ucs1lib_utf16_encode(out, (const Py_UCS1 *)data, len, native_ordering);
5404 break;
Tim Peters772747b2001-08-09 22:21:55 +00005405 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005406 case PyUnicode_2BYTE_KIND: {
5407 ucs2lib_utf16_encode(out, (const Py_UCS2 *)data, len, native_ordering);
5408 break;
Tim Peters772747b2001-08-09 22:21:55 +00005409 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005410 case PyUnicode_4BYTE_KIND: {
5411 ucs4lib_utf16_encode(out, (const Py_UCS4 *)data, len, native_ordering);
5412 break;
5413 }
5414 default:
5415 assert(0);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005416 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005417
5418 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005419 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005420}
5421
Alexander Belopolsky40018472011-02-26 01:02:56 +00005422PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005423PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5424 Py_ssize_t size,
5425 const char *errors,
5426 int byteorder)
5427{
5428 PyObject *result;
5429 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5430 if (tmp == NULL)
5431 return NULL;
5432 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5433 Py_DECREF(tmp);
5434 return result;
5435}
5436
5437PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005438PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005439{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005440 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005441}
5442
5443/* --- Unicode Escape Codec ----------------------------------------------- */
5444
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005445/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5446 if all the escapes in the string make it still a valid ASCII string.
5447 Returns -1 if any escapes were found which cause the string to
5448 pop out of ASCII range. Otherwise returns the length of the
5449 required buffer to hold the string.
5450 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005451static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005452length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5453{
5454 const unsigned char *p = (const unsigned char *)s;
5455 const unsigned char *end = p + size;
5456 Py_ssize_t length = 0;
5457
5458 if (size < 0)
5459 return -1;
5460
5461 for (; p < end; ++p) {
5462 if (*p > 127) {
5463 /* Non-ASCII */
5464 return -1;
5465 }
5466 else if (*p != '\\') {
5467 /* Normal character */
5468 ++length;
5469 }
5470 else {
5471 /* Backslash-escape, check next char */
5472 ++p;
5473 /* Escape sequence reaches till end of string or
5474 non-ASCII follow-up. */
5475 if (p >= end || *p > 127)
5476 return -1;
5477 switch (*p) {
5478 case '\n':
5479 /* backslash + \n result in zero characters */
5480 break;
5481 case '\\': case '\'': case '\"':
5482 case 'b': case 'f': case 't':
5483 case 'n': case 'r': case 'v': case 'a':
5484 ++length;
5485 break;
5486 case '0': case '1': case '2': case '3':
5487 case '4': case '5': case '6': case '7':
5488 case 'x': case 'u': case 'U': case 'N':
5489 /* these do not guarantee ASCII characters */
5490 return -1;
5491 default:
5492 /* count the backslash + the other character */
5493 length += 2;
5494 }
5495 }
5496 }
5497 return length;
5498}
5499
Fredrik Lundh06d12682001-01-24 07:59:11 +00005500static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005501
Alexander Belopolsky40018472011-02-26 01:02:56 +00005502PyObject *
5503PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005504 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005505 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005506{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005507 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005508 Py_ssize_t startinpos;
5509 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005510 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005511 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005512 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005513 char* message;
5514 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005515 PyObject *errorHandler = NULL;
5516 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005517 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005518 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005519
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005520 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005521
5522 /* After length_of_escaped_ascii_string() there are two alternatives,
5523 either the string is pure ASCII with named escapes like \n, etc.
5524 and we determined it's exact size (common case)
5525 or it contains \x, \u, ... escape sequences. then we create a
5526 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005527 if (len >= 0) {
5528 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005529 if (!v)
5530 goto onError;
5531 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005532 }
5533 else {
5534 /* Escaped strings will always be longer than the resulting
5535 Unicode string, so we start with size here and then reduce the
5536 length after conversion to the true value.
5537 (but if the error callback returns a long replacement string
5538 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005539 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005540 if (!v)
5541 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005542 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005543 }
5544
Guido van Rossumd57fd912000-03-10 22:53:23 +00005545 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005546 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005547 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005548 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005549
Guido van Rossumd57fd912000-03-10 22:53:23 +00005550 while (s < end) {
5551 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005552 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005553 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005554
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005555 /* The only case in which i == ascii_length is a backslash
5556 followed by a newline. */
5557 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005558
Guido van Rossumd57fd912000-03-10 22:53:23 +00005559 /* Non-escape characters are interpreted as Unicode ordinals */
5560 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005561 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5562 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005563 continue;
5564 }
5565
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005566 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005567 /* \ - Escapes */
5568 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005569 c = *s++;
5570 if (s > end)
5571 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005572
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005573 /* The only case in which i == ascii_length is a backslash
5574 followed by a newline. */
5575 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005576
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005577 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005578
Benjamin Peterson29060642009-01-31 22:14:21 +00005579 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005580#define WRITECHAR(ch) \
5581 do { \
5582 if (unicode_putchar(&v, &i, ch) < 0) \
5583 goto onError; \
5584 }while(0)
5585
Guido van Rossumd57fd912000-03-10 22:53:23 +00005586 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005587 case '\\': WRITECHAR('\\'); break;
5588 case '\'': WRITECHAR('\''); break;
5589 case '\"': WRITECHAR('\"'); break;
5590 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005591 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005592 case 'f': WRITECHAR('\014'); break;
5593 case 't': WRITECHAR('\t'); break;
5594 case 'n': WRITECHAR('\n'); break;
5595 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005596 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005597 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005598 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005599 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005600
Benjamin Peterson29060642009-01-31 22:14:21 +00005601 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005602 case '0': case '1': case '2': case '3':
5603 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005604 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005605 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005606 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005607 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005608 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005609 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005610 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005611 break;
5612
Benjamin Peterson29060642009-01-31 22:14:21 +00005613 /* hex escapes */
5614 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005615 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005616 digits = 2;
5617 message = "truncated \\xXX escape";
5618 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005619
Benjamin Peterson29060642009-01-31 22:14:21 +00005620 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005621 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005622 digits = 4;
5623 message = "truncated \\uXXXX escape";
5624 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005625
Benjamin Peterson29060642009-01-31 22:14:21 +00005626 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005627 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005628 digits = 8;
5629 message = "truncated \\UXXXXXXXX escape";
5630 hexescape:
5631 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005632 if (s+digits>end) {
5633 endinpos = size;
5634 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005635 errors, &errorHandler,
5636 "unicodeescape", "end of string in escape sequence",
5637 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005638 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005639 goto onError;
5640 goto nextByte;
5641 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005642 for (j = 0; j < digits; ++j) {
5643 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005644 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005645 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005646 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005647 errors, &errorHandler,
5648 "unicodeescape", message,
5649 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005650 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005651 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005652 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005653 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005654 }
5655 chr = (chr<<4) & ~0xF;
5656 if (c >= '0' && c <= '9')
5657 chr += c - '0';
5658 else if (c >= 'a' && c <= 'f')
5659 chr += 10 + c - 'a';
5660 else
5661 chr += 10 + c - 'A';
5662 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005663 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005664 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005665 /* _decoding_error will have already written into the
5666 target buffer. */
5667 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005668 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005669 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005670 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005671 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005672 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005673 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005674 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005675 errors, &errorHandler,
5676 "unicodeescape", "illegal Unicode character",
5677 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005678 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005679 goto onError;
5680 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005681 break;
5682
Benjamin Peterson29060642009-01-31 22:14:21 +00005683 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005684 case 'N':
5685 message = "malformed \\N character escape";
5686 if (ucnhash_CAPI == NULL) {
5687 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005688 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5689 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005690 if (ucnhash_CAPI == NULL)
5691 goto ucnhashError;
5692 }
5693 if (*s == '{') {
5694 const char *start = s+1;
5695 /* look for the closing brace */
5696 while (*s != '}' && s < end)
5697 s++;
5698 if (s > start && s < end && *s == '}') {
5699 /* found a name. look it up in the unicode database */
5700 message = "unknown Unicode character name";
5701 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005702 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005703 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005704 goto store;
5705 }
5706 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005707 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005708 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005709 errors, &errorHandler,
5710 "unicodeescape", message,
5711 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005712 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005713 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005714 break;
5715
5716 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005717 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005718 message = "\\ at end of string";
5719 s--;
5720 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005721 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005722 errors, &errorHandler,
5723 "unicodeescape", message,
5724 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005725 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005726 goto onError;
5727 }
5728 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005729 WRITECHAR('\\');
5730 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005731 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005732 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005733 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005734 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005735 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005736 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005737#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005738
Victor Stinner16e6a802011-12-12 13:24:15 +01005739 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005740 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005741 Py_XDECREF(errorHandler);
5742 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005743 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005744
Benjamin Peterson29060642009-01-31 22:14:21 +00005745 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005746 PyErr_SetString(
5747 PyExc_UnicodeError,
5748 "\\N escapes not supported (can't load unicodedata module)"
5749 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005750 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005751 Py_XDECREF(errorHandler);
5752 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005753 return NULL;
5754
Benjamin Peterson29060642009-01-31 22:14:21 +00005755 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005756 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005757 Py_XDECREF(errorHandler);
5758 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005759 return NULL;
5760}
5761
5762/* Return a Unicode-Escape string version of the Unicode object.
5763
5764 If quotes is true, the string is enclosed in u"" or u'' quotes as
5765 appropriate.
5766
5767*/
5768
Alexander Belopolsky40018472011-02-26 01:02:56 +00005769PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005770PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005771{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005772 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005773 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005774 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005775 int kind;
5776 void *data;
5777 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005778
Thomas Wouters89f507f2006-12-13 04:49:30 +00005779 /* Initial allocation is based on the longest-possible unichr
5780 escape.
5781
5782 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5783 unichr, so in this case it's the longest unichr escape. In
5784 narrow (UTF-16) builds this is five chars per source unichr
5785 since there are two unichrs in the surrogate pair, so in narrow
5786 (UTF-16) builds it's not the longest unichr escape.
5787
5788 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5789 so in the narrow (UTF-16) build case it's the longest unichr
5790 escape.
5791 */
5792
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005793 if (!PyUnicode_Check(unicode)) {
5794 PyErr_BadArgument();
5795 return NULL;
5796 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005797 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005798 return NULL;
5799 len = PyUnicode_GET_LENGTH(unicode);
5800 kind = PyUnicode_KIND(unicode);
5801 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005802 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005803 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5804 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5805 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5806 }
5807
5808 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005809 return PyBytes_FromStringAndSize(NULL, 0);
5810
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005811 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005812 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005813
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005814 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005815 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005816 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005817 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005818 if (repr == NULL)
5819 return NULL;
5820
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005821 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005822
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005823 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005824 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005825
Walter Dörwald79e913e2007-05-12 11:08:06 +00005826 /* Escape backslashes */
5827 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005828 *p++ = '\\';
5829 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005830 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005831 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005832
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005833 /* Map 21-bit characters to '\U00xxxxxx' */
5834 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005835 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005836 *p++ = '\\';
5837 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005838 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5839 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5840 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5841 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5842 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5843 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5844 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5845 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005846 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005847 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005848
Guido van Rossumd57fd912000-03-10 22:53:23 +00005849 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005850 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005851 *p++ = '\\';
5852 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005853 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5854 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5855 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5856 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005857 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005858
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005859 /* Map special whitespace to '\t', \n', '\r' */
5860 else if (ch == '\t') {
5861 *p++ = '\\';
5862 *p++ = 't';
5863 }
5864 else if (ch == '\n') {
5865 *p++ = '\\';
5866 *p++ = 'n';
5867 }
5868 else if (ch == '\r') {
5869 *p++ = '\\';
5870 *p++ = 'r';
5871 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005872
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005873 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005874 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005875 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005876 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005877 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5878 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005879 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005880
Guido van Rossumd57fd912000-03-10 22:53:23 +00005881 /* Copy everything else as-is */
5882 else
5883 *p++ = (char) ch;
5884 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005885
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005886 assert(p - PyBytes_AS_STRING(repr) > 0);
5887 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5888 return NULL;
5889 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005890}
5891
Alexander Belopolsky40018472011-02-26 01:02:56 +00005892PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005893PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5894 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005895{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005896 PyObject *result;
5897 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5898 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005899 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005900 result = PyUnicode_AsUnicodeEscapeString(tmp);
5901 Py_DECREF(tmp);
5902 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005903}
5904
5905/* --- Raw Unicode Escape Codec ------------------------------------------- */
5906
Alexander Belopolsky40018472011-02-26 01:02:56 +00005907PyObject *
5908PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005909 Py_ssize_t size,
5910 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005911{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005912 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005913 Py_ssize_t startinpos;
5914 Py_ssize_t endinpos;
5915 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005916 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005917 const char *end;
5918 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005919 PyObject *errorHandler = NULL;
5920 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005921
Guido van Rossumd57fd912000-03-10 22:53:23 +00005922 /* Escaped strings will always be longer than the resulting
5923 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005924 length after conversion to the true value. (But decoding error
5925 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005926 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005927 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005928 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005930 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005931 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005932 end = s + size;
5933 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005934 unsigned char c;
5935 Py_UCS4 x;
5936 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005937 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005938
Benjamin Peterson29060642009-01-31 22:14:21 +00005939 /* Non-escape characters are interpreted as Unicode ordinals */
5940 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005941 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5942 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005943 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005944 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005945 startinpos = s-starts;
5946
5947 /* \u-escapes are only interpreted iff the number of leading
5948 backslashes if odd */
5949 bs = s;
5950 for (;s < end;) {
5951 if (*s != '\\')
5952 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005953 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5954 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005955 }
5956 if (((s - bs) & 1) == 0 ||
5957 s >= end ||
5958 (*s != 'u' && *s != 'U')) {
5959 continue;
5960 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005961 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00005962 count = *s=='u' ? 4 : 8;
5963 s++;
5964
5965 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00005966 for (x = 0, i = 0; i < count; ++i, ++s) {
5967 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005968 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005969 endinpos = s-starts;
5970 if (unicode_decode_call_errorhandler(
5971 errors, &errorHandler,
5972 "rawunicodeescape", "truncated \\uXXXX",
5973 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005974 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005975 goto onError;
5976 goto nextByte;
5977 }
5978 x = (x<<4) & ~0xF;
5979 if (c >= '0' && c <= '9')
5980 x += c - '0';
5981 else if (c >= 'a' && c <= 'f')
5982 x += 10 + c - 'a';
5983 else
5984 x += 10 + c - 'A';
5985 }
Victor Stinner8faf8212011-12-08 22:14:11 +01005986 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005987 if (unicode_putchar(&v, &outpos, x) < 0)
5988 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005989 } else {
5990 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005991 if (unicode_decode_call_errorhandler(
5992 errors, &errorHandler,
5993 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005994 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005995 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005996 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005997 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005998 nextByte:
5999 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006000 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006001 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006002 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006003 Py_XDECREF(errorHandler);
6004 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006005 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006006
Benjamin Peterson29060642009-01-31 22:14:21 +00006007 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006008 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006009 Py_XDECREF(errorHandler);
6010 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006011 return NULL;
6012}
6013
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006014
Alexander Belopolsky40018472011-02-26 01:02:56 +00006015PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006016PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006017{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006018 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006019 char *p;
6020 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006021 Py_ssize_t expandsize, pos;
6022 int kind;
6023 void *data;
6024 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006025
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006026 if (!PyUnicode_Check(unicode)) {
6027 PyErr_BadArgument();
6028 return NULL;
6029 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006030 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006031 return NULL;
6032 kind = PyUnicode_KIND(unicode);
6033 data = PyUnicode_DATA(unicode);
6034 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006035 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6036 bytes, and 1 byte characters 4. */
6037 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006038
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006039 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006040 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006041
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006042 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043 if (repr == NULL)
6044 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006045 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006046 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006047
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006048 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006049 for (pos = 0; pos < len; pos++) {
6050 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006051 /* Map 32-bit characters to '\Uxxxxxxxx' */
6052 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006053 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006054 *p++ = '\\';
6055 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006056 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6057 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6058 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6059 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6060 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6061 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6062 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6063 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006064 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006065 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006066 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006067 *p++ = '\\';
6068 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006069 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6070 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6071 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6072 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006073 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006074 /* Copy everything else as-is */
6075 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006076 *p++ = (char) ch;
6077 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006078
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006079 assert(p > q);
6080 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006081 return NULL;
6082 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006083}
6084
Alexander Belopolsky40018472011-02-26 01:02:56 +00006085PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006086PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6087 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006088{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006089 PyObject *result;
6090 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6091 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006092 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006093 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6094 Py_DECREF(tmp);
6095 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006096}
6097
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006098/* --- Unicode Internal Codec ------------------------------------------- */
6099
Alexander Belopolsky40018472011-02-26 01:02:56 +00006100PyObject *
6101_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006102 Py_ssize_t size,
6103 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006104{
6105 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006106 Py_ssize_t startinpos;
6107 Py_ssize_t endinpos;
6108 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006109 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006110 const char *end;
6111 const char *reason;
6112 PyObject *errorHandler = NULL;
6113 PyObject *exc = NULL;
6114
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006115 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006116 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006117 1))
6118 return NULL;
6119
Thomas Wouters89f507f2006-12-13 04:49:30 +00006120 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006121 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006122 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006123 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006124 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006125 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006126 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006127 end = s + size;
6128
6129 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006130 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006131 Py_UCS4 ch;
6132 /* We copy the raw representation one byte at a time because the
6133 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006134 ((char *) &uch)[0] = s[0];
6135 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006136#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006137 ((char *) &uch)[2] = s[2];
6138 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006139#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006140 ch = uch;
6141
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006142 /* We have to sanity check the raw data, otherwise doom looms for
6143 some malformed UCS-4 data. */
6144 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006145#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006146 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006147#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006148 end-s < Py_UNICODE_SIZE
6149 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006150 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006151 startinpos = s - starts;
6152 if (end-s < Py_UNICODE_SIZE) {
6153 endinpos = end-starts;
6154 reason = "truncated input";
6155 }
6156 else {
6157 endinpos = s - starts + Py_UNICODE_SIZE;
6158 reason = "illegal code point (> 0x10FFFF)";
6159 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006160 if (unicode_decode_call_errorhandler(
6161 errors, &errorHandler,
6162 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006163 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006164 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006165 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006166 continue;
6167 }
6168
6169 s += Py_UNICODE_SIZE;
6170#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006171 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006172 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006173 Py_UNICODE uch2;
6174 ((char *) &uch2)[0] = s[0];
6175 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006176 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006177 {
Victor Stinner551ac952011-11-29 22:58:13 +01006178 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006179 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006180 }
6181 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006182#endif
6183
6184 if (unicode_putchar(&v, &outpos, ch) < 0)
6185 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006186 }
6187
Victor Stinner16e6a802011-12-12 13:24:15 +01006188 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006189 goto onError;
6190 Py_XDECREF(errorHandler);
6191 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006192 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006193
Benjamin Peterson29060642009-01-31 22:14:21 +00006194 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006195 Py_XDECREF(v);
6196 Py_XDECREF(errorHandler);
6197 Py_XDECREF(exc);
6198 return NULL;
6199}
6200
Guido van Rossumd57fd912000-03-10 22:53:23 +00006201/* --- Latin-1 Codec ------------------------------------------------------ */
6202
Alexander Belopolsky40018472011-02-26 01:02:56 +00006203PyObject *
6204PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006205 Py_ssize_t size,
6206 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006207{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006208 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006209 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006210}
6211
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006212/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006213static void
6214make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006215 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006216 PyObject *unicode,
6217 Py_ssize_t startpos, Py_ssize_t endpos,
6218 const char *reason)
6219{
6220 if (*exceptionObject == NULL) {
6221 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006222 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006223 encoding, unicode, startpos, endpos, reason);
6224 }
6225 else {
6226 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6227 goto onError;
6228 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6229 goto onError;
6230 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6231 goto onError;
6232 return;
6233 onError:
6234 Py_DECREF(*exceptionObject);
6235 *exceptionObject = NULL;
6236 }
6237}
6238
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006239/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006240static void
6241raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006242 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006243 PyObject *unicode,
6244 Py_ssize_t startpos, Py_ssize_t endpos,
6245 const char *reason)
6246{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006247 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006248 encoding, unicode, startpos, endpos, reason);
6249 if (*exceptionObject != NULL)
6250 PyCodec_StrictErrors(*exceptionObject);
6251}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006252
6253/* error handling callback helper:
6254 build arguments, call the callback and check the arguments,
6255 put the result into newpos and return the replacement string, which
6256 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006257static PyObject *
6258unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006259 PyObject **errorHandler,
6260 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006261 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006262 Py_ssize_t startpos, Py_ssize_t endpos,
6263 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006264{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006265 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006266 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006267 PyObject *restuple;
6268 PyObject *resunicode;
6269
6270 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006271 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006272 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006273 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006274 }
6275
Benjamin Petersonbac79492012-01-14 13:34:47 -05006276 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006277 return NULL;
6278 len = PyUnicode_GET_LENGTH(unicode);
6279
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006280 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006281 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006282 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006283 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006284
6285 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006286 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006287 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006288 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006289 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006290 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006291 Py_DECREF(restuple);
6292 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006293 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006294 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006295 &resunicode, newpos)) {
6296 Py_DECREF(restuple);
6297 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006298 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006299 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6300 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6301 Py_DECREF(restuple);
6302 return NULL;
6303 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006304 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006305 *newpos = len + *newpos;
6306 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006307 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6308 Py_DECREF(restuple);
6309 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006310 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006311 Py_INCREF(resunicode);
6312 Py_DECREF(restuple);
6313 return resunicode;
6314}
6315
Alexander Belopolsky40018472011-02-26 01:02:56 +00006316static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006317unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006318 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006319 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006320{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006321 /* input state */
6322 Py_ssize_t pos=0, size;
6323 int kind;
6324 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006325 /* output object */
6326 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006327 /* pointer into the output */
6328 char *str;
6329 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006330 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006331 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6332 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006333 PyObject *errorHandler = NULL;
6334 PyObject *exc = NULL;
6335 /* the following variable is used for caching string comparisons
6336 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6337 int known_errorHandler = -1;
6338
Benjamin Petersonbac79492012-01-14 13:34:47 -05006339 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006340 return NULL;
6341 size = PyUnicode_GET_LENGTH(unicode);
6342 kind = PyUnicode_KIND(unicode);
6343 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006344 /* allocate enough for a simple encoding without
6345 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006346 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006347 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006348 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006349 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006350 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006351 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006352 ressize = size;
6353
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006354 while (pos < size) {
6355 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006356
Benjamin Peterson29060642009-01-31 22:14:21 +00006357 /* can we encode this? */
6358 if (c<limit) {
6359 /* no overflow check, because we know that the space is enough */
6360 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006361 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006362 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006363 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006364 Py_ssize_t requiredsize;
6365 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006366 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006367 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006368 Py_ssize_t collstart = pos;
6369 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006370 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006371 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006372 ++collend;
6373 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6374 if (known_errorHandler==-1) {
6375 if ((errors==NULL) || (!strcmp(errors, "strict")))
6376 known_errorHandler = 1;
6377 else if (!strcmp(errors, "replace"))
6378 known_errorHandler = 2;
6379 else if (!strcmp(errors, "ignore"))
6380 known_errorHandler = 3;
6381 else if (!strcmp(errors, "xmlcharrefreplace"))
6382 known_errorHandler = 4;
6383 else
6384 known_errorHandler = 0;
6385 }
6386 switch (known_errorHandler) {
6387 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006388 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006389 goto onError;
6390 case 2: /* replace */
6391 while (collstart++<collend)
6392 *str++ = '?'; /* fall through */
6393 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006394 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006395 break;
6396 case 4: /* xmlcharrefreplace */
6397 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006398 /* determine replacement size */
6399 for (i = collstart, repsize = 0; i < collend; ++i) {
6400 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6401 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006402 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006403 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006404 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006405 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006406 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006407 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006408 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006409 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006410 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006411 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006412 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006413 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006414 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006415 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006416 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006417 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006418 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006419 if (requiredsize > ressize) {
6420 if (requiredsize<2*ressize)
6421 requiredsize = 2*ressize;
6422 if (_PyBytes_Resize(&res, requiredsize))
6423 goto onError;
6424 str = PyBytes_AS_STRING(res) + respos;
6425 ressize = requiredsize;
6426 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006427 /* generate replacement */
6428 for (i = collstart; i < collend; ++i) {
6429 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006430 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006431 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006432 break;
6433 default:
6434 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006435 encoding, reason, unicode, &exc,
6436 collstart, collend, &newpos);
6437 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006438 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006439 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006440 if (PyBytes_Check(repunicode)) {
6441 /* Directly copy bytes result to output. */
6442 repsize = PyBytes_Size(repunicode);
6443 if (repsize > 1) {
6444 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006445 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006446 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6447 Py_DECREF(repunicode);
6448 goto onError;
6449 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006450 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006451 ressize += repsize-1;
6452 }
6453 memcpy(str, PyBytes_AsString(repunicode), repsize);
6454 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006455 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006456 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006457 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006458 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006459 /* need more space? (at least enough for what we
6460 have+the replacement+the rest of the string, so
6461 we won't have to check space for encodable characters) */
6462 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006463 repsize = PyUnicode_GET_LENGTH(repunicode);
6464 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006465 if (requiredsize > ressize) {
6466 if (requiredsize<2*ressize)
6467 requiredsize = 2*ressize;
6468 if (_PyBytes_Resize(&res, requiredsize)) {
6469 Py_DECREF(repunicode);
6470 goto onError;
6471 }
6472 str = PyBytes_AS_STRING(res) + respos;
6473 ressize = requiredsize;
6474 }
6475 /* check if there is anything unencodable in the replacement
6476 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006477 for (i = 0; repsize-->0; ++i, ++str) {
6478 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006479 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006480 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006481 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006482 Py_DECREF(repunicode);
6483 goto onError;
6484 }
6485 *str = (char)c;
6486 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006487 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006488 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006489 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006490 }
6491 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006492 /* Resize if we allocated to much */
6493 size = str - PyBytes_AS_STRING(res);
6494 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006495 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006496 if (_PyBytes_Resize(&res, size) < 0)
6497 goto onError;
6498 }
6499
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006500 Py_XDECREF(errorHandler);
6501 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006502 return res;
6503
6504 onError:
6505 Py_XDECREF(res);
6506 Py_XDECREF(errorHandler);
6507 Py_XDECREF(exc);
6508 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006509}
6510
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006511/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006512PyObject *
6513PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006514 Py_ssize_t size,
6515 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006516{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006517 PyObject *result;
6518 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6519 if (unicode == NULL)
6520 return NULL;
6521 result = unicode_encode_ucs1(unicode, errors, 256);
6522 Py_DECREF(unicode);
6523 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006524}
6525
Alexander Belopolsky40018472011-02-26 01:02:56 +00006526PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006527_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006528{
6529 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006530 PyErr_BadArgument();
6531 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006532 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006533 if (PyUnicode_READY(unicode) == -1)
6534 return NULL;
6535 /* Fast path: if it is a one-byte string, construct
6536 bytes object directly. */
6537 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6538 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6539 PyUnicode_GET_LENGTH(unicode));
6540 /* Non-Latin-1 characters present. Defer to above function to
6541 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006542 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006543}
6544
6545PyObject*
6546PyUnicode_AsLatin1String(PyObject *unicode)
6547{
6548 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006549}
6550
6551/* --- 7-bit ASCII Codec -------------------------------------------------- */
6552
Alexander Belopolsky40018472011-02-26 01:02:56 +00006553PyObject *
6554PyUnicode_DecodeASCII(const char *s,
6555 Py_ssize_t size,
6556 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006557{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006558 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006559 PyObject *unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006560 int kind;
6561 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006562 Py_ssize_t startinpos;
6563 Py_ssize_t endinpos;
6564 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006565 const char *e;
6566 PyObject *errorHandler = NULL;
6567 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006568
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006569 if (size == 0) {
6570 Py_INCREF(unicode_empty);
6571 return unicode_empty;
6572 }
6573
Guido van Rossumd57fd912000-03-10 22:53:23 +00006574 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006575 if (size == 1 && (unsigned char)s[0] < 128)
6576 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006577
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006578 unicode = PyUnicode_New(size, 127);
6579 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006580 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006581
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006582 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006583 data = PyUnicode_1BYTE_DATA(unicode);
6584 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
6585 if (outpos == size)
6586 return unicode;
6587
6588 s += outpos;
6589 kind = PyUnicode_1BYTE_KIND;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006590 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006591 register unsigned char c = (unsigned char)*s;
6592 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006593 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006594 ++s;
6595 }
6596 else {
6597 startinpos = s-starts;
6598 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006599 if (unicode_decode_call_errorhandler(
6600 errors, &errorHandler,
6601 "ascii", "ordinal not in range(128)",
6602 &starts, &e, &startinpos, &endinpos, &exc, &s,
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006603 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006604 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006605 kind = PyUnicode_KIND(unicode);
6606 data = PyUnicode_DATA(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00006607 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006608 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006609 if (unicode_resize(&unicode, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006610 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006611 Py_XDECREF(errorHandler);
6612 Py_XDECREF(exc);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006613 assert(_PyUnicode_CheckConsistency(unicode, 1));
6614 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00006615
Benjamin Peterson29060642009-01-31 22:14:21 +00006616 onError:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006617 Py_XDECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006618 Py_XDECREF(errorHandler);
6619 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006620 return NULL;
6621}
6622
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006623/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006624PyObject *
6625PyUnicode_EncodeASCII(const Py_UNICODE *p,
6626 Py_ssize_t size,
6627 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006628{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006629 PyObject *result;
6630 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6631 if (unicode == NULL)
6632 return NULL;
6633 result = unicode_encode_ucs1(unicode, errors, 128);
6634 Py_DECREF(unicode);
6635 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006636}
6637
Alexander Belopolsky40018472011-02-26 01:02:56 +00006638PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006639_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006640{
6641 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006642 PyErr_BadArgument();
6643 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006644 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006645 if (PyUnicode_READY(unicode) == -1)
6646 return NULL;
6647 /* Fast path: if it is an ASCII-only string, construct bytes object
6648 directly. Else defer to above function to raise the exception. */
6649 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6650 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6651 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006652 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006653}
6654
6655PyObject *
6656PyUnicode_AsASCIIString(PyObject *unicode)
6657{
6658 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006659}
6660
Victor Stinner99b95382011-07-04 14:23:54 +02006661#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006662
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006663/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006664
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006665#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006666#define NEED_RETRY
6667#endif
6668
Victor Stinner3a50e702011-10-18 21:21:00 +02006669#ifndef WC_ERR_INVALID_CHARS
6670# define WC_ERR_INVALID_CHARS 0x0080
6671#endif
6672
6673static char*
6674code_page_name(UINT code_page, PyObject **obj)
6675{
6676 *obj = NULL;
6677 if (code_page == CP_ACP)
6678 return "mbcs";
6679 if (code_page == CP_UTF7)
6680 return "CP_UTF7";
6681 if (code_page == CP_UTF8)
6682 return "CP_UTF8";
6683
6684 *obj = PyBytes_FromFormat("cp%u", code_page);
6685 if (*obj == NULL)
6686 return NULL;
6687 return PyBytes_AS_STRING(*obj);
6688}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006689
Alexander Belopolsky40018472011-02-26 01:02:56 +00006690static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006691is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006692{
6693 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006694 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006695
Victor Stinner3a50e702011-10-18 21:21:00 +02006696 if (!IsDBCSLeadByteEx(code_page, *curr))
6697 return 0;
6698
6699 prev = CharPrevExA(code_page, s, curr, 0);
6700 if (prev == curr)
6701 return 1;
6702 /* FIXME: This code is limited to "true" double-byte encodings,
6703 as it assumes an incomplete character consists of a single
6704 byte. */
6705 if (curr - prev == 2)
6706 return 1;
6707 if (!IsDBCSLeadByteEx(code_page, *prev))
6708 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006709 return 0;
6710}
6711
Victor Stinner3a50e702011-10-18 21:21:00 +02006712static DWORD
6713decode_code_page_flags(UINT code_page)
6714{
6715 if (code_page == CP_UTF7) {
6716 /* The CP_UTF7 decoder only supports flags=0 */
6717 return 0;
6718 }
6719 else
6720 return MB_ERR_INVALID_CHARS;
6721}
6722
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006723/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006724 * Decode a byte string from a Windows code page into unicode object in strict
6725 * mode.
6726 *
6727 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6728 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006729 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006730static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006731decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006732 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006733 const char *in,
6734 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006735{
Victor Stinner3a50e702011-10-18 21:21:00 +02006736 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006737 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006738 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006739
6740 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006741 assert(insize > 0);
6742 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6743 if (outsize <= 0)
6744 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006745
6746 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006747 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006748 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006749 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006750 if (*v == NULL)
6751 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006752 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006753 }
6754 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006755 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006756 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006757 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006758 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006759 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006760 }
6761
6762 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006763 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6764 if (outsize <= 0)
6765 goto error;
6766 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006767
Victor Stinner3a50e702011-10-18 21:21:00 +02006768error:
6769 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6770 return -2;
6771 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006772 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006773}
6774
Victor Stinner3a50e702011-10-18 21:21:00 +02006775/*
6776 * Decode a byte string from a code page into unicode object with an error
6777 * handler.
6778 *
6779 * Returns consumed size if succeed, or raise a WindowsError or
6780 * UnicodeDecodeError exception and returns -1 on error.
6781 */
6782static int
6783decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006784 PyObject **v,
6785 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006786 const char *errors)
6787{
6788 const char *startin = in;
6789 const char *endin = in + size;
6790 const DWORD flags = decode_code_page_flags(code_page);
6791 /* Ideally, we should get reason from FormatMessage. This is the Windows
6792 2000 English version of the message. */
6793 const char *reason = "No mapping for the Unicode character exists "
6794 "in the target code page.";
6795 /* each step cannot decode more than 1 character, but a character can be
6796 represented as a surrogate pair */
6797 wchar_t buffer[2], *startout, *out;
6798 int insize, outsize;
6799 PyObject *errorHandler = NULL;
6800 PyObject *exc = NULL;
6801 PyObject *encoding_obj = NULL;
6802 char *encoding;
6803 DWORD err;
6804 int ret = -1;
6805
6806 assert(size > 0);
6807
6808 encoding = code_page_name(code_page, &encoding_obj);
6809 if (encoding == NULL)
6810 return -1;
6811
6812 if (errors == NULL || strcmp(errors, "strict") == 0) {
6813 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6814 UnicodeDecodeError. */
6815 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6816 if (exc != NULL) {
6817 PyCodec_StrictErrors(exc);
6818 Py_CLEAR(exc);
6819 }
6820 goto error;
6821 }
6822
6823 if (*v == NULL) {
6824 /* Create unicode object */
6825 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6826 PyErr_NoMemory();
6827 goto error;
6828 }
Victor Stinnerab595942011-12-17 04:59:06 +01006829 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006830 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006831 if (*v == NULL)
6832 goto error;
6833 startout = PyUnicode_AS_UNICODE(*v);
6834 }
6835 else {
6836 /* Extend unicode object */
6837 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6838 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6839 PyErr_NoMemory();
6840 goto error;
6841 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006842 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006843 goto error;
6844 startout = PyUnicode_AS_UNICODE(*v) + n;
6845 }
6846
6847 /* Decode the byte string character per character */
6848 out = startout;
6849 while (in < endin)
6850 {
6851 /* Decode a character */
6852 insize = 1;
6853 do
6854 {
6855 outsize = MultiByteToWideChar(code_page, flags,
6856 in, insize,
6857 buffer, Py_ARRAY_LENGTH(buffer));
6858 if (outsize > 0)
6859 break;
6860 err = GetLastError();
6861 if (err != ERROR_NO_UNICODE_TRANSLATION
6862 && err != ERROR_INSUFFICIENT_BUFFER)
6863 {
6864 PyErr_SetFromWindowsErr(0);
6865 goto error;
6866 }
6867 insize++;
6868 }
6869 /* 4=maximum length of a UTF-8 sequence */
6870 while (insize <= 4 && (in + insize) <= endin);
6871
6872 if (outsize <= 0) {
6873 Py_ssize_t startinpos, endinpos, outpos;
6874
6875 startinpos = in - startin;
6876 endinpos = startinpos + 1;
6877 outpos = out - PyUnicode_AS_UNICODE(*v);
6878 if (unicode_decode_call_errorhandler(
6879 errors, &errorHandler,
6880 encoding, reason,
6881 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006882 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006883 {
6884 goto error;
6885 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006886 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006887 }
6888 else {
6889 in += insize;
6890 memcpy(out, buffer, outsize * sizeof(wchar_t));
6891 out += outsize;
6892 }
6893 }
6894
6895 /* write a NUL character at the end */
6896 *out = 0;
6897
6898 /* Extend unicode object */
6899 outsize = out - startout;
6900 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006901 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006902 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01006903 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006904
6905error:
6906 Py_XDECREF(encoding_obj);
6907 Py_XDECREF(errorHandler);
6908 Py_XDECREF(exc);
6909 return ret;
6910}
6911
Victor Stinner3a50e702011-10-18 21:21:00 +02006912static PyObject *
6913decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006914 const char *s, Py_ssize_t size,
6915 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006916{
Victor Stinner76a31a62011-11-04 00:05:13 +01006917 PyObject *v = NULL;
6918 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006919
Victor Stinner3a50e702011-10-18 21:21:00 +02006920 if (code_page < 0) {
6921 PyErr_SetString(PyExc_ValueError, "invalid code page number");
6922 return NULL;
6923 }
6924
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006925 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006926 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006927
Victor Stinner76a31a62011-11-04 00:05:13 +01006928 do
6929 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006930#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01006931 if (size > INT_MAX) {
6932 chunk_size = INT_MAX;
6933 final = 0;
6934 done = 0;
6935 }
6936 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006937#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01006938 {
6939 chunk_size = (int)size;
6940 final = (consumed == NULL);
6941 done = 1;
6942 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006943
Victor Stinner76a31a62011-11-04 00:05:13 +01006944 /* Skip trailing lead-byte unless 'final' is set */
6945 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
6946 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006947
Victor Stinner76a31a62011-11-04 00:05:13 +01006948 if (chunk_size == 0 && done) {
6949 if (v != NULL)
6950 break;
6951 Py_INCREF(unicode_empty);
6952 return unicode_empty;
6953 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006954
Victor Stinner76a31a62011-11-04 00:05:13 +01006955
6956 converted = decode_code_page_strict(code_page, &v,
6957 s, chunk_size);
6958 if (converted == -2)
6959 converted = decode_code_page_errors(code_page, &v,
6960 s, chunk_size,
6961 errors);
6962 assert(converted != 0);
6963
6964 if (converted < 0) {
6965 Py_XDECREF(v);
6966 return NULL;
6967 }
6968
6969 if (consumed)
6970 *consumed += converted;
6971
6972 s += converted;
6973 size -= converted;
6974 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02006975
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006976 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006977}
6978
Alexander Belopolsky40018472011-02-26 01:02:56 +00006979PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02006980PyUnicode_DecodeCodePageStateful(int code_page,
6981 const char *s,
6982 Py_ssize_t size,
6983 const char *errors,
6984 Py_ssize_t *consumed)
6985{
6986 return decode_code_page_stateful(code_page, s, size, errors, consumed);
6987}
6988
6989PyObject *
6990PyUnicode_DecodeMBCSStateful(const char *s,
6991 Py_ssize_t size,
6992 const char *errors,
6993 Py_ssize_t *consumed)
6994{
6995 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
6996}
6997
6998PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006999PyUnicode_DecodeMBCS(const char *s,
7000 Py_ssize_t size,
7001 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007002{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007003 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7004}
7005
Victor Stinner3a50e702011-10-18 21:21:00 +02007006static DWORD
7007encode_code_page_flags(UINT code_page, const char *errors)
7008{
7009 if (code_page == CP_UTF8) {
7010 if (winver.dwMajorVersion >= 6)
7011 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7012 and later */
7013 return WC_ERR_INVALID_CHARS;
7014 else
7015 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7016 return 0;
7017 }
7018 else if (code_page == CP_UTF7) {
7019 /* CP_UTF7 only supports flags=0 */
7020 return 0;
7021 }
7022 else {
7023 if (errors != NULL && strcmp(errors, "replace") == 0)
7024 return 0;
7025 else
7026 return WC_NO_BEST_FIT_CHARS;
7027 }
7028}
7029
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007030/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007031 * Encode a Unicode string to a Windows code page into a byte string in strict
7032 * mode.
7033 *
7034 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7035 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007036 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007037static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007038encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007039 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007040 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007041{
Victor Stinner554f3f02010-06-16 23:33:54 +00007042 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007043 BOOL *pusedDefaultChar = &usedDefaultChar;
7044 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007045 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007046 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007047 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007048 const DWORD flags = encode_code_page_flags(code_page, NULL);
7049 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007050 /* Create a substring so that we can get the UTF-16 representation
7051 of just the slice under consideration. */
7052 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007053
Martin v. Löwis3d325192011-11-04 18:23:06 +01007054 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007055
Victor Stinner3a50e702011-10-18 21:21:00 +02007056 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007057 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007058 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007059 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007060
Victor Stinner2fc507f2011-11-04 20:06:39 +01007061 substring = PyUnicode_Substring(unicode, offset, offset+len);
7062 if (substring == NULL)
7063 return -1;
7064 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7065 if (p == NULL) {
7066 Py_DECREF(substring);
7067 return -1;
7068 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007069
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007070 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007071 outsize = WideCharToMultiByte(code_page, flags,
7072 p, size,
7073 NULL, 0,
7074 NULL, pusedDefaultChar);
7075 if (outsize <= 0)
7076 goto error;
7077 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007078 if (pusedDefaultChar && *pusedDefaultChar) {
7079 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007080 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007081 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007082
Victor Stinner3a50e702011-10-18 21:21:00 +02007083 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007084 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007085 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007086 if (*outbytes == NULL) {
7087 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007088 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007089 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007090 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007091 }
7092 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007093 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007094 const Py_ssize_t n = PyBytes_Size(*outbytes);
7095 if (outsize > PY_SSIZE_T_MAX - n) {
7096 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007097 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007098 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007099 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007100 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7101 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007102 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007103 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007104 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007105 }
7106
7107 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007108 outsize = WideCharToMultiByte(code_page, flags,
7109 p, size,
7110 out, outsize,
7111 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007112 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007113 if (outsize <= 0)
7114 goto error;
7115 if (pusedDefaultChar && *pusedDefaultChar)
7116 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007117 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007118
Victor Stinner3a50e702011-10-18 21:21:00 +02007119error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007120 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007121 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7122 return -2;
7123 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007124 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007125}
7126
Victor Stinner3a50e702011-10-18 21:21:00 +02007127/*
7128 * Encode a Unicode string to a Windows code page into a byte string using a
7129 * error handler.
7130 *
7131 * Returns consumed characters if succeed, or raise a WindowsError and returns
7132 * -1 on other error.
7133 */
7134static int
7135encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007136 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007137 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007138{
Victor Stinner3a50e702011-10-18 21:21:00 +02007139 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007140 Py_ssize_t pos = unicode_offset;
7141 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007142 /* Ideally, we should get reason from FormatMessage. This is the Windows
7143 2000 English version of the message. */
7144 const char *reason = "invalid character";
7145 /* 4=maximum length of a UTF-8 sequence */
7146 char buffer[4];
7147 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7148 Py_ssize_t outsize;
7149 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007150 PyObject *errorHandler = NULL;
7151 PyObject *exc = NULL;
7152 PyObject *encoding_obj = NULL;
7153 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007154 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007155 PyObject *rep;
7156 int ret = -1;
7157
7158 assert(insize > 0);
7159
7160 encoding = code_page_name(code_page, &encoding_obj);
7161 if (encoding == NULL)
7162 return -1;
7163
7164 if (errors == NULL || strcmp(errors, "strict") == 0) {
7165 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7166 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007167 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007168 if (exc != NULL) {
7169 PyCodec_StrictErrors(exc);
7170 Py_DECREF(exc);
7171 }
7172 Py_XDECREF(encoding_obj);
7173 return -1;
7174 }
7175
7176 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7177 pusedDefaultChar = &usedDefaultChar;
7178 else
7179 pusedDefaultChar = NULL;
7180
7181 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7182 PyErr_NoMemory();
7183 goto error;
7184 }
7185 outsize = insize * Py_ARRAY_LENGTH(buffer);
7186
7187 if (*outbytes == NULL) {
7188 /* Create string object */
7189 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7190 if (*outbytes == NULL)
7191 goto error;
7192 out = PyBytes_AS_STRING(*outbytes);
7193 }
7194 else {
7195 /* Extend string object */
7196 Py_ssize_t n = PyBytes_Size(*outbytes);
7197 if (n > PY_SSIZE_T_MAX - outsize) {
7198 PyErr_NoMemory();
7199 goto error;
7200 }
7201 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7202 goto error;
7203 out = PyBytes_AS_STRING(*outbytes) + n;
7204 }
7205
7206 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007207 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007208 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007209 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7210 wchar_t chars[2];
7211 int charsize;
7212 if (ch < 0x10000) {
7213 chars[0] = (wchar_t)ch;
7214 charsize = 1;
7215 }
7216 else {
7217 ch -= 0x10000;
7218 chars[0] = 0xd800 + (ch >> 10);
7219 chars[1] = 0xdc00 + (ch & 0x3ff);
7220 charsize = 2;
7221 }
7222
Victor Stinner3a50e702011-10-18 21:21:00 +02007223 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007224 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007225 buffer, Py_ARRAY_LENGTH(buffer),
7226 NULL, pusedDefaultChar);
7227 if (outsize > 0) {
7228 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7229 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007230 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007231 memcpy(out, buffer, outsize);
7232 out += outsize;
7233 continue;
7234 }
7235 }
7236 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7237 PyErr_SetFromWindowsErr(0);
7238 goto error;
7239 }
7240
Victor Stinner3a50e702011-10-18 21:21:00 +02007241 rep = unicode_encode_call_errorhandler(
7242 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007243 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007244 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007245 if (rep == NULL)
7246 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007247 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007248
7249 if (PyBytes_Check(rep)) {
7250 outsize = PyBytes_GET_SIZE(rep);
7251 if (outsize != 1) {
7252 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7253 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7254 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7255 Py_DECREF(rep);
7256 goto error;
7257 }
7258 out = PyBytes_AS_STRING(*outbytes) + offset;
7259 }
7260 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7261 out += outsize;
7262 }
7263 else {
7264 Py_ssize_t i;
7265 enum PyUnicode_Kind kind;
7266 void *data;
7267
Benjamin Petersonbac79492012-01-14 13:34:47 -05007268 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007269 Py_DECREF(rep);
7270 goto error;
7271 }
7272
7273 outsize = PyUnicode_GET_LENGTH(rep);
7274 if (outsize != 1) {
7275 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7276 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7277 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7278 Py_DECREF(rep);
7279 goto error;
7280 }
7281 out = PyBytes_AS_STRING(*outbytes) + offset;
7282 }
7283 kind = PyUnicode_KIND(rep);
7284 data = PyUnicode_DATA(rep);
7285 for (i=0; i < outsize; i++) {
7286 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7287 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007288 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007289 encoding, unicode,
7290 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007291 "unable to encode error handler result to ASCII");
7292 Py_DECREF(rep);
7293 goto error;
7294 }
7295 *out = (unsigned char)ch;
7296 out++;
7297 }
7298 }
7299 Py_DECREF(rep);
7300 }
7301 /* write a NUL byte */
7302 *out = 0;
7303 outsize = out - PyBytes_AS_STRING(*outbytes);
7304 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7305 if (_PyBytes_Resize(outbytes, outsize) < 0)
7306 goto error;
7307 ret = 0;
7308
7309error:
7310 Py_XDECREF(encoding_obj);
7311 Py_XDECREF(errorHandler);
7312 Py_XDECREF(exc);
7313 return ret;
7314}
7315
Victor Stinner3a50e702011-10-18 21:21:00 +02007316static PyObject *
7317encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007318 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007319 const char *errors)
7320{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007321 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007322 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007323 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007324 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007325
Benjamin Petersonbac79492012-01-14 13:34:47 -05007326 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007327 return NULL;
7328 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007329
Victor Stinner3a50e702011-10-18 21:21:00 +02007330 if (code_page < 0) {
7331 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7332 return NULL;
7333 }
7334
Martin v. Löwis3d325192011-11-04 18:23:06 +01007335 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007336 return PyBytes_FromStringAndSize(NULL, 0);
7337
Victor Stinner7581cef2011-11-03 22:32:33 +01007338 offset = 0;
7339 do
7340 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007341#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007342 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007343 chunks. */
7344 if (len > INT_MAX/2) {
7345 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007346 done = 0;
7347 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007348 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007349#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007350 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007351 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007352 done = 1;
7353 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007354
Victor Stinner76a31a62011-11-04 00:05:13 +01007355 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007356 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007357 errors);
7358 if (ret == -2)
7359 ret = encode_code_page_errors(code_page, &outbytes,
7360 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007361 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007362 if (ret < 0) {
7363 Py_XDECREF(outbytes);
7364 return NULL;
7365 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007366
Victor Stinner7581cef2011-11-03 22:32:33 +01007367 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007368 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007369 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007370
Victor Stinner3a50e702011-10-18 21:21:00 +02007371 return outbytes;
7372}
7373
7374PyObject *
7375PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7376 Py_ssize_t size,
7377 const char *errors)
7378{
Victor Stinner7581cef2011-11-03 22:32:33 +01007379 PyObject *unicode, *res;
7380 unicode = PyUnicode_FromUnicode(p, size);
7381 if (unicode == NULL)
7382 return NULL;
7383 res = encode_code_page(CP_ACP, unicode, errors);
7384 Py_DECREF(unicode);
7385 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007386}
7387
7388PyObject *
7389PyUnicode_EncodeCodePage(int code_page,
7390 PyObject *unicode,
7391 const char *errors)
7392{
Victor Stinner7581cef2011-11-03 22:32:33 +01007393 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007394}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007395
Alexander Belopolsky40018472011-02-26 01:02:56 +00007396PyObject *
7397PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007398{
7399 if (!PyUnicode_Check(unicode)) {
7400 PyErr_BadArgument();
7401 return NULL;
7402 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007403 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007404}
7405
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007406#undef NEED_RETRY
7407
Victor Stinner99b95382011-07-04 14:23:54 +02007408#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007409
Guido van Rossumd57fd912000-03-10 22:53:23 +00007410/* --- Character Mapping Codec -------------------------------------------- */
7411
Alexander Belopolsky40018472011-02-26 01:02:56 +00007412PyObject *
7413PyUnicode_DecodeCharmap(const char *s,
7414 Py_ssize_t size,
7415 PyObject *mapping,
7416 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007417{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007418 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007419 Py_ssize_t startinpos;
7420 Py_ssize_t endinpos;
7421 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007422 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007423 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007424 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007425 PyObject *errorHandler = NULL;
7426 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007427
Guido van Rossumd57fd912000-03-10 22:53:23 +00007428 /* Default to Latin-1 */
7429 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007430 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007431
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007432 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007433 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007434 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007435 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007436 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007437 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007438 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007439 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007440 Py_ssize_t maplen;
7441 enum PyUnicode_Kind kind;
7442 void *data;
7443 Py_UCS4 x;
7444
Benjamin Petersonbac79492012-01-14 13:34:47 -05007445 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007446 return NULL;
7447
7448 maplen = PyUnicode_GET_LENGTH(mapping);
7449 data = PyUnicode_DATA(mapping);
7450 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007451 while (s < e) {
7452 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007453
Benjamin Peterson29060642009-01-31 22:14:21 +00007454 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007455 x = PyUnicode_READ(kind, data, ch);
7456 else
7457 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007458
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007459 if (x == 0xfffe)
7460 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007461 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007462 startinpos = s-starts;
7463 endinpos = startinpos+1;
7464 if (unicode_decode_call_errorhandler(
7465 errors, &errorHandler,
7466 "charmap", "character maps to <undefined>",
7467 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007468 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007469 goto onError;
7470 }
7471 continue;
7472 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007473
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007474 if (unicode_putchar(&v, &outpos, x) < 0)
7475 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007476 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007477 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007478 }
7479 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007480 while (s < e) {
7481 unsigned char ch = *s;
7482 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007483
Benjamin Peterson29060642009-01-31 22:14:21 +00007484 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7485 w = PyLong_FromLong((long)ch);
7486 if (w == NULL)
7487 goto onError;
7488 x = PyObject_GetItem(mapping, w);
7489 Py_DECREF(w);
7490 if (x == NULL) {
7491 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7492 /* No mapping found means: mapping is undefined. */
7493 PyErr_Clear();
7494 x = Py_None;
7495 Py_INCREF(x);
7496 } else
7497 goto onError;
7498 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007499
Benjamin Peterson29060642009-01-31 22:14:21 +00007500 /* Apply mapping */
7501 if (PyLong_Check(x)) {
7502 long value = PyLong_AS_LONG(x);
7503 if (value < 0 || value > 65535) {
7504 PyErr_SetString(PyExc_TypeError,
7505 "character mapping must be in range(65536)");
7506 Py_DECREF(x);
7507 goto onError;
7508 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007509 if (unicode_putchar(&v, &outpos, value) < 0)
7510 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007511 }
7512 else if (x == Py_None) {
7513 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007514 startinpos = s-starts;
7515 endinpos = startinpos+1;
7516 if (unicode_decode_call_errorhandler(
7517 errors, &errorHandler,
7518 "charmap", "character maps to <undefined>",
7519 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007520 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007521 Py_DECREF(x);
7522 goto onError;
7523 }
7524 Py_DECREF(x);
7525 continue;
7526 }
7527 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007528 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007529
Benjamin Petersonbac79492012-01-14 13:34:47 -05007530 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007531 goto onError;
7532 targetsize = PyUnicode_GET_LENGTH(x);
7533
7534 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007535 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007536 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007537 PyUnicode_READ_CHAR(x, 0)) < 0)
7538 goto onError;
7539 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007540 else if (targetsize > 1) {
7541 /* 1-n mapping */
7542 if (targetsize > extrachars) {
7543 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007544 Py_ssize_t needed = (targetsize - extrachars) + \
7545 (targetsize << 2);
7546 extrachars += needed;
7547 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007548 if (unicode_resize(&v,
7549 PyUnicode_GET_LENGTH(v) + needed) < 0)
7550 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007551 Py_DECREF(x);
7552 goto onError;
7553 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007554 }
Victor Stinner1b487b42012-05-03 12:29:04 +02007555 if (unicode_widen(&v, outpos, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007556 goto onError;
7557 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7558 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007559 extrachars -= targetsize;
7560 }
7561 /* 1-0 mapping: skip the character */
7562 }
7563 else {
7564 /* wrong return value */
7565 PyErr_SetString(PyExc_TypeError,
7566 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007567 Py_DECREF(x);
7568 goto onError;
7569 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007570 Py_DECREF(x);
7571 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007572 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007573 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007574 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007575 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007576 Py_XDECREF(errorHandler);
7577 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007578 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007579
Benjamin Peterson29060642009-01-31 22:14:21 +00007580 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007581 Py_XDECREF(errorHandler);
7582 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007583 Py_XDECREF(v);
7584 return NULL;
7585}
7586
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007587/* Charmap encoding: the lookup table */
7588
Alexander Belopolsky40018472011-02-26 01:02:56 +00007589struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007590 PyObject_HEAD
7591 unsigned char level1[32];
7592 int count2, count3;
7593 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007594};
7595
7596static PyObject*
7597encoding_map_size(PyObject *obj, PyObject* args)
7598{
7599 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007600 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007601 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007602}
7603
7604static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007605 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007606 PyDoc_STR("Return the size (in bytes) of this object") },
7607 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007608};
7609
7610static void
7611encoding_map_dealloc(PyObject* o)
7612{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007613 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007614}
7615
7616static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007617 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007618 "EncodingMap", /*tp_name*/
7619 sizeof(struct encoding_map), /*tp_basicsize*/
7620 0, /*tp_itemsize*/
7621 /* methods */
7622 encoding_map_dealloc, /*tp_dealloc*/
7623 0, /*tp_print*/
7624 0, /*tp_getattr*/
7625 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007626 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007627 0, /*tp_repr*/
7628 0, /*tp_as_number*/
7629 0, /*tp_as_sequence*/
7630 0, /*tp_as_mapping*/
7631 0, /*tp_hash*/
7632 0, /*tp_call*/
7633 0, /*tp_str*/
7634 0, /*tp_getattro*/
7635 0, /*tp_setattro*/
7636 0, /*tp_as_buffer*/
7637 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7638 0, /*tp_doc*/
7639 0, /*tp_traverse*/
7640 0, /*tp_clear*/
7641 0, /*tp_richcompare*/
7642 0, /*tp_weaklistoffset*/
7643 0, /*tp_iter*/
7644 0, /*tp_iternext*/
7645 encoding_map_methods, /*tp_methods*/
7646 0, /*tp_members*/
7647 0, /*tp_getset*/
7648 0, /*tp_base*/
7649 0, /*tp_dict*/
7650 0, /*tp_descr_get*/
7651 0, /*tp_descr_set*/
7652 0, /*tp_dictoffset*/
7653 0, /*tp_init*/
7654 0, /*tp_alloc*/
7655 0, /*tp_new*/
7656 0, /*tp_free*/
7657 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007658};
7659
7660PyObject*
7661PyUnicode_BuildEncodingMap(PyObject* string)
7662{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007663 PyObject *result;
7664 struct encoding_map *mresult;
7665 int i;
7666 int need_dict = 0;
7667 unsigned char level1[32];
7668 unsigned char level2[512];
7669 unsigned char *mlevel1, *mlevel2, *mlevel3;
7670 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007671 int kind;
7672 void *data;
7673 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007674
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007675 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007676 PyErr_BadArgument();
7677 return NULL;
7678 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007679 kind = PyUnicode_KIND(string);
7680 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007681 memset(level1, 0xFF, sizeof level1);
7682 memset(level2, 0xFF, sizeof level2);
7683
7684 /* If there isn't a one-to-one mapping of NULL to \0,
7685 or if there are non-BMP characters, we need to use
7686 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007687 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007688 need_dict = 1;
7689 for (i = 1; i < 256; i++) {
7690 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007691 ch = PyUnicode_READ(kind, data, i);
7692 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007693 need_dict = 1;
7694 break;
7695 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007696 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007697 /* unmapped character */
7698 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007699 l1 = ch >> 11;
7700 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007701 if (level1[l1] == 0xFF)
7702 level1[l1] = count2++;
7703 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007704 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007705 }
7706
7707 if (count2 >= 0xFF || count3 >= 0xFF)
7708 need_dict = 1;
7709
7710 if (need_dict) {
7711 PyObject *result = PyDict_New();
7712 PyObject *key, *value;
7713 if (!result)
7714 return NULL;
7715 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007716 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007717 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007718 if (!key || !value)
7719 goto failed1;
7720 if (PyDict_SetItem(result, key, value) == -1)
7721 goto failed1;
7722 Py_DECREF(key);
7723 Py_DECREF(value);
7724 }
7725 return result;
7726 failed1:
7727 Py_XDECREF(key);
7728 Py_XDECREF(value);
7729 Py_DECREF(result);
7730 return NULL;
7731 }
7732
7733 /* Create a three-level trie */
7734 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7735 16*count2 + 128*count3 - 1);
7736 if (!result)
7737 return PyErr_NoMemory();
7738 PyObject_Init(result, &EncodingMapType);
7739 mresult = (struct encoding_map*)result;
7740 mresult->count2 = count2;
7741 mresult->count3 = count3;
7742 mlevel1 = mresult->level1;
7743 mlevel2 = mresult->level23;
7744 mlevel3 = mresult->level23 + 16*count2;
7745 memcpy(mlevel1, level1, 32);
7746 memset(mlevel2, 0xFF, 16*count2);
7747 memset(mlevel3, 0, 128*count3);
7748 count3 = 0;
7749 for (i = 1; i < 256; i++) {
7750 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007751 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007752 /* unmapped character */
7753 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007754 o1 = PyUnicode_READ(kind, data, i)>>11;
7755 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007756 i2 = 16*mlevel1[o1] + o2;
7757 if (mlevel2[i2] == 0xFF)
7758 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007759 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007760 i3 = 128*mlevel2[i2] + o3;
7761 mlevel3[i3] = i;
7762 }
7763 return result;
7764}
7765
7766static int
Victor Stinner22168992011-11-20 17:09:18 +01007767encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007768{
7769 struct encoding_map *map = (struct encoding_map*)mapping;
7770 int l1 = c>>11;
7771 int l2 = (c>>7) & 0xF;
7772 int l3 = c & 0x7F;
7773 int i;
7774
Victor Stinner22168992011-11-20 17:09:18 +01007775 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007776 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007777 if (c == 0)
7778 return 0;
7779 /* level 1*/
7780 i = map->level1[l1];
7781 if (i == 0xFF) {
7782 return -1;
7783 }
7784 /* level 2*/
7785 i = map->level23[16*i+l2];
7786 if (i == 0xFF) {
7787 return -1;
7788 }
7789 /* level 3 */
7790 i = map->level23[16*map->count2 + 128*i + l3];
7791 if (i == 0) {
7792 return -1;
7793 }
7794 return i;
7795}
7796
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007797/* Lookup the character ch in the mapping. If the character
7798 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007799 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007800static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007801charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007802{
Christian Heimes217cfd12007-12-02 14:31:20 +00007803 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007804 PyObject *x;
7805
7806 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007807 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007808 x = PyObject_GetItem(mapping, w);
7809 Py_DECREF(w);
7810 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007811 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7812 /* No mapping found means: mapping is undefined. */
7813 PyErr_Clear();
7814 x = Py_None;
7815 Py_INCREF(x);
7816 return x;
7817 } else
7818 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007819 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007820 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007821 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007822 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007823 long value = PyLong_AS_LONG(x);
7824 if (value < 0 || value > 255) {
7825 PyErr_SetString(PyExc_TypeError,
7826 "character mapping must be in range(256)");
7827 Py_DECREF(x);
7828 return NULL;
7829 }
7830 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007831 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007832 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007833 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007834 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007835 /* wrong return value */
7836 PyErr_Format(PyExc_TypeError,
7837 "character mapping must return integer, bytes or None, not %.400s",
7838 x->ob_type->tp_name);
7839 Py_DECREF(x);
7840 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007841 }
7842}
7843
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007844static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007845charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007846{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007847 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7848 /* exponentially overallocate to minimize reallocations */
7849 if (requiredsize < 2*outsize)
7850 requiredsize = 2*outsize;
7851 if (_PyBytes_Resize(outobj, requiredsize))
7852 return -1;
7853 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007854}
7855
Benjamin Peterson14339b62009-01-31 16:36:08 +00007856typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007857 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007858} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007859/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007860 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007861 space is available. Return a new reference to the object that
7862 was put in the output buffer, or Py_None, if the mapping was undefined
7863 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007864 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007865static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01007866charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007867 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007868{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007869 PyObject *rep;
7870 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007871 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007872
Christian Heimes90aa7642007-12-19 02:45:37 +00007873 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007874 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007875 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007876 if (res == -1)
7877 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007878 if (outsize<requiredsize)
7879 if (charmapencode_resize(outobj, outpos, requiredsize))
7880 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007881 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007882 outstart[(*outpos)++] = (char)res;
7883 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007884 }
7885
7886 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007887 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007888 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007889 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007890 Py_DECREF(rep);
7891 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007892 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007893 if (PyLong_Check(rep)) {
7894 Py_ssize_t requiredsize = *outpos+1;
7895 if (outsize<requiredsize)
7896 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7897 Py_DECREF(rep);
7898 return enc_EXCEPTION;
7899 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007900 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007901 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007902 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007903 else {
7904 const char *repchars = PyBytes_AS_STRING(rep);
7905 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7906 Py_ssize_t requiredsize = *outpos+repsize;
7907 if (outsize<requiredsize)
7908 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7909 Py_DECREF(rep);
7910 return enc_EXCEPTION;
7911 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007912 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007913 memcpy(outstart + *outpos, repchars, repsize);
7914 *outpos += repsize;
7915 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007916 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007917 Py_DECREF(rep);
7918 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007919}
7920
7921/* handle an error in PyUnicode_EncodeCharmap
7922 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007923static int
7924charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007925 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007926 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007927 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007928 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007929{
7930 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007931 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007932 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007933 enum PyUnicode_Kind kind;
7934 void *data;
7935 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007936 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007937 Py_ssize_t collstartpos = *inpos;
7938 Py_ssize_t collendpos = *inpos+1;
7939 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007940 char *encoding = "charmap";
7941 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007942 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007943 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05007944 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007945
Benjamin Petersonbac79492012-01-14 13:34:47 -05007946 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007947 return -1;
7948 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007949 /* find all unencodable characters */
7950 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007951 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007952 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007953 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05007954 val = encoding_map_lookup(ch, mapping);
7955 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007956 break;
7957 ++collendpos;
7958 continue;
7959 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007960
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007961 ch = PyUnicode_READ_CHAR(unicode, collendpos);
7962 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007963 if (rep==NULL)
7964 return -1;
7965 else if (rep!=Py_None) {
7966 Py_DECREF(rep);
7967 break;
7968 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007969 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007970 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007971 }
7972 /* cache callback name lookup
7973 * (if not done yet, i.e. it's the first error) */
7974 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007975 if ((errors==NULL) || (!strcmp(errors, "strict")))
7976 *known_errorHandler = 1;
7977 else if (!strcmp(errors, "replace"))
7978 *known_errorHandler = 2;
7979 else if (!strcmp(errors, "ignore"))
7980 *known_errorHandler = 3;
7981 else if (!strcmp(errors, "xmlcharrefreplace"))
7982 *known_errorHandler = 4;
7983 else
7984 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007985 }
7986 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007987 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007988 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007989 return -1;
7990 case 2: /* replace */
7991 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007992 x = charmapencode_output('?', mapping, res, respos);
7993 if (x==enc_EXCEPTION) {
7994 return -1;
7995 }
7996 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007997 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00007998 return -1;
7999 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008000 }
8001 /* fall through */
8002 case 3: /* ignore */
8003 *inpos = collendpos;
8004 break;
8005 case 4: /* xmlcharrefreplace */
8006 /* generate replacement (temporarily (mis)uses p) */
8007 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008008 char buffer[2+29+1+1];
8009 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008010 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008011 for (cp = buffer; *cp; ++cp) {
8012 x = charmapencode_output(*cp, mapping, res, respos);
8013 if (x==enc_EXCEPTION)
8014 return -1;
8015 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008016 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008017 return -1;
8018 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008019 }
8020 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008021 *inpos = collendpos;
8022 break;
8023 default:
8024 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008025 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008026 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008027 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008028 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008029 if (PyBytes_Check(repunicode)) {
8030 /* Directly copy bytes result to output. */
8031 Py_ssize_t outsize = PyBytes_Size(*res);
8032 Py_ssize_t requiredsize;
8033 repsize = PyBytes_Size(repunicode);
8034 requiredsize = *respos + repsize;
8035 if (requiredsize > outsize)
8036 /* Make room for all additional bytes. */
8037 if (charmapencode_resize(res, respos, requiredsize)) {
8038 Py_DECREF(repunicode);
8039 return -1;
8040 }
8041 memcpy(PyBytes_AsString(*res) + *respos,
8042 PyBytes_AsString(repunicode), repsize);
8043 *respos += repsize;
8044 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008045 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008046 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008047 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008048 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008049 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008050 Py_DECREF(repunicode);
8051 return -1;
8052 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008053 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008054 data = PyUnicode_DATA(repunicode);
8055 kind = PyUnicode_KIND(repunicode);
8056 for (index = 0; index < repsize; index++) {
8057 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8058 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008059 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008060 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008061 return -1;
8062 }
8063 else if (x==enc_FAILED) {
8064 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008065 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008066 return -1;
8067 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008068 }
8069 *inpos = newpos;
8070 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008071 }
8072 return 0;
8073}
8074
Alexander Belopolsky40018472011-02-26 01:02:56 +00008075PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008076_PyUnicode_EncodeCharmap(PyObject *unicode,
8077 PyObject *mapping,
8078 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008079{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008080 /* output object */
8081 PyObject *res = NULL;
8082 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008083 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008084 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008085 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008086 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008087 PyObject *errorHandler = NULL;
8088 PyObject *exc = NULL;
8089 /* the following variable is used for caching string comparisons
8090 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8091 * 3=ignore, 4=xmlcharrefreplace */
8092 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008093
Benjamin Petersonbac79492012-01-14 13:34:47 -05008094 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008095 return NULL;
8096 size = PyUnicode_GET_LENGTH(unicode);
8097
Guido van Rossumd57fd912000-03-10 22:53:23 +00008098 /* Default to Latin-1 */
8099 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008100 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008101
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008102 /* allocate enough for a simple encoding without
8103 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008104 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008105 if (res == NULL)
8106 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008107 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008108 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008109
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008110 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008111 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008112 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008113 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008114 if (x==enc_EXCEPTION) /* error */
8115 goto onError;
8116 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008117 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008118 &exc,
8119 &known_errorHandler, &errorHandler, errors,
8120 &res, &respos)) {
8121 goto onError;
8122 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008123 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008124 else
8125 /* done with this character => adjust input position */
8126 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008127 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008128
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008129 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008130 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008131 if (_PyBytes_Resize(&res, respos) < 0)
8132 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008133
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008134 Py_XDECREF(exc);
8135 Py_XDECREF(errorHandler);
8136 return res;
8137
Benjamin Peterson29060642009-01-31 22:14:21 +00008138 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008139 Py_XDECREF(res);
8140 Py_XDECREF(exc);
8141 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008142 return NULL;
8143}
8144
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008145/* Deprecated */
8146PyObject *
8147PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8148 Py_ssize_t size,
8149 PyObject *mapping,
8150 const char *errors)
8151{
8152 PyObject *result;
8153 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8154 if (unicode == NULL)
8155 return NULL;
8156 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8157 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008158 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008159}
8160
Alexander Belopolsky40018472011-02-26 01:02:56 +00008161PyObject *
8162PyUnicode_AsCharmapString(PyObject *unicode,
8163 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008164{
8165 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008166 PyErr_BadArgument();
8167 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008168 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008169 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008170}
8171
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008172/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008173static void
8174make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008175 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008176 Py_ssize_t startpos, Py_ssize_t endpos,
8177 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008178{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008179 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008180 *exceptionObject = _PyUnicodeTranslateError_Create(
8181 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008182 }
8183 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008184 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8185 goto onError;
8186 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8187 goto onError;
8188 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8189 goto onError;
8190 return;
8191 onError:
8192 Py_DECREF(*exceptionObject);
8193 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008194 }
8195}
8196
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008197/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008198static void
8199raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008200 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008201 Py_ssize_t startpos, Py_ssize_t endpos,
8202 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008203{
8204 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008205 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008206 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008207 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008208}
8209
8210/* error handling callback helper:
8211 build arguments, call the callback and check the arguments,
8212 put the result into newpos and return the replacement string, which
8213 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008214static PyObject *
8215unicode_translate_call_errorhandler(const char *errors,
8216 PyObject **errorHandler,
8217 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008218 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008219 Py_ssize_t startpos, Py_ssize_t endpos,
8220 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008221{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008222 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008223
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008224 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008225 PyObject *restuple;
8226 PyObject *resunicode;
8227
8228 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008229 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008230 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008231 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008232 }
8233
8234 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008235 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008236 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008237 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008238
8239 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008240 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008241 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008242 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008243 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008244 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008245 Py_DECREF(restuple);
8246 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008247 }
8248 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008249 &resunicode, &i_newpos)) {
8250 Py_DECREF(restuple);
8251 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008252 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008253 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008254 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008255 else
8256 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008257 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008258 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8259 Py_DECREF(restuple);
8260 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008261 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008262 Py_INCREF(resunicode);
8263 Py_DECREF(restuple);
8264 return resunicode;
8265}
8266
8267/* Lookup the character ch in the mapping and put the result in result,
8268 which must be decrefed by the caller.
8269 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008270static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008271charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008272{
Christian Heimes217cfd12007-12-02 14:31:20 +00008273 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008274 PyObject *x;
8275
8276 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008277 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008278 x = PyObject_GetItem(mapping, w);
8279 Py_DECREF(w);
8280 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008281 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8282 /* No mapping found means: use 1:1 mapping. */
8283 PyErr_Clear();
8284 *result = NULL;
8285 return 0;
8286 } else
8287 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008288 }
8289 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008290 *result = x;
8291 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008292 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008293 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008294 long value = PyLong_AS_LONG(x);
8295 long max = PyUnicode_GetMax();
8296 if (value < 0 || value > max) {
8297 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008298 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008299 Py_DECREF(x);
8300 return -1;
8301 }
8302 *result = x;
8303 return 0;
8304 }
8305 else if (PyUnicode_Check(x)) {
8306 *result = x;
8307 return 0;
8308 }
8309 else {
8310 /* wrong return value */
8311 PyErr_SetString(PyExc_TypeError,
8312 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008313 Py_DECREF(x);
8314 return -1;
8315 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008316}
8317/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008318 if not reallocate and adjust various state variables.
8319 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008320static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008321charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008322 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008323{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008324 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008325 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008326 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008327 /* exponentially overallocate to minimize reallocations */
8328 if (requiredsize < 2 * oldsize)
8329 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008330 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8331 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008332 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008333 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008334 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008335 }
8336 return 0;
8337}
8338/* lookup the character, put the result in the output string and adjust
8339 various state variables. Return a new reference to the object that
8340 was put in the output buffer in *result, or Py_None, if the mapping was
8341 undefined (in which case no character was written).
8342 The called must decref result.
8343 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008344static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008345charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8346 PyObject *mapping, Py_UCS4 **output,
8347 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008348 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008349{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008350 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8351 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008352 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008353 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008354 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008355 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008356 }
8357 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008358 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008359 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008360 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008361 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008362 }
8363 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008364 Py_ssize_t repsize;
8365 if (PyUnicode_READY(*res) == -1)
8366 return -1;
8367 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008368 if (repsize==1) {
8369 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008370 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008371 }
8372 else if (repsize!=0) {
8373 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008374 Py_ssize_t requiredsize = *opos +
8375 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008377 Py_ssize_t i;
8378 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008379 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008380 for(i = 0; i < repsize; i++)
8381 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008382 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008383 }
8384 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008385 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008386 return 0;
8387}
8388
Alexander Belopolsky40018472011-02-26 01:02:56 +00008389PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008390_PyUnicode_TranslateCharmap(PyObject *input,
8391 PyObject *mapping,
8392 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008393{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008394 /* input object */
8395 char *idata;
8396 Py_ssize_t size, i;
8397 int kind;
8398 /* output buffer */
8399 Py_UCS4 *output = NULL;
8400 Py_ssize_t osize;
8401 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008402 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008403 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008404 char *reason = "character maps to <undefined>";
8405 PyObject *errorHandler = NULL;
8406 PyObject *exc = NULL;
8407 /* the following variable is used for caching string comparisons
8408 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8409 * 3=ignore, 4=xmlcharrefreplace */
8410 int known_errorHandler = -1;
8411
Guido van Rossumd57fd912000-03-10 22:53:23 +00008412 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008413 PyErr_BadArgument();
8414 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008415 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008416
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008417 if (PyUnicode_READY(input) == -1)
8418 return NULL;
8419 idata = (char*)PyUnicode_DATA(input);
8420 kind = PyUnicode_KIND(input);
8421 size = PyUnicode_GET_LENGTH(input);
8422 i = 0;
8423
8424 if (size == 0) {
8425 Py_INCREF(input);
8426 return input;
8427 }
8428
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008429 /* allocate enough for a simple 1:1 translation without
8430 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008431 osize = size;
8432 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8433 opos = 0;
8434 if (output == NULL) {
8435 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008436 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008437 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008438
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008439 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008440 /* try to encode it */
8441 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008442 if (charmaptranslate_output(input, i, mapping,
8443 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008444 Py_XDECREF(x);
8445 goto onError;
8446 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008447 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008448 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008449 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008450 else { /* untranslatable character */
8451 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8452 Py_ssize_t repsize;
8453 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008454 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008455 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008456 Py_ssize_t collstart = i;
8457 Py_ssize_t collend = i+1;
8458 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008459
Benjamin Peterson29060642009-01-31 22:14:21 +00008460 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008461 while (collend < size) {
8462 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008463 goto onError;
8464 Py_XDECREF(x);
8465 if (x!=Py_None)
8466 break;
8467 ++collend;
8468 }
8469 /* cache callback name lookup
8470 * (if not done yet, i.e. it's the first error) */
8471 if (known_errorHandler==-1) {
8472 if ((errors==NULL) || (!strcmp(errors, "strict")))
8473 known_errorHandler = 1;
8474 else if (!strcmp(errors, "replace"))
8475 known_errorHandler = 2;
8476 else if (!strcmp(errors, "ignore"))
8477 known_errorHandler = 3;
8478 else if (!strcmp(errors, "xmlcharrefreplace"))
8479 known_errorHandler = 4;
8480 else
8481 known_errorHandler = 0;
8482 }
8483 switch (known_errorHandler) {
8484 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008485 raise_translate_exception(&exc, input, collstart,
8486 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008487 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008488 case 2: /* replace */
8489 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008490 for (coll = collstart; coll<collend; coll++)
8491 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008492 /* fall through */
8493 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008494 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008495 break;
8496 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008497 /* generate replacement (temporarily (mis)uses i) */
8498 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008499 char buffer[2+29+1+1];
8500 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008501 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8502 if (charmaptranslate_makespace(&output, &osize,
8503 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008504 goto onError;
8505 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008506 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008507 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008508 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008509 break;
8510 default:
8511 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008512 reason, input, &exc,
8513 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008514 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008515 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008516 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008517 Py_DECREF(repunicode);
8518 goto onError;
8519 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008520 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008521 repsize = PyUnicode_GET_LENGTH(repunicode);
8522 if (charmaptranslate_makespace(&output, &osize,
8523 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008524 Py_DECREF(repunicode);
8525 goto onError;
8526 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008527 for (uni2 = 0; repsize-->0; ++uni2)
8528 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8529 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008530 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008531 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008532 }
8533 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008534 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8535 if (!res)
8536 goto onError;
8537 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008538 Py_XDECREF(exc);
8539 Py_XDECREF(errorHandler);
8540 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008541
Benjamin Peterson29060642009-01-31 22:14:21 +00008542 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008543 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008544 Py_XDECREF(exc);
8545 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008546 return NULL;
8547}
8548
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008549/* Deprecated. Use PyUnicode_Translate instead. */
8550PyObject *
8551PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8552 Py_ssize_t size,
8553 PyObject *mapping,
8554 const char *errors)
8555{
8556 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8557 if (!unicode)
8558 return NULL;
8559 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8560}
8561
Alexander Belopolsky40018472011-02-26 01:02:56 +00008562PyObject *
8563PyUnicode_Translate(PyObject *str,
8564 PyObject *mapping,
8565 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008566{
8567 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008568
Guido van Rossumd57fd912000-03-10 22:53:23 +00008569 str = PyUnicode_FromObject(str);
8570 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008571 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008572 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008573 Py_DECREF(str);
8574 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008575
Benjamin Peterson29060642009-01-31 22:14:21 +00008576 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008577 Py_XDECREF(str);
8578 return NULL;
8579}
Tim Petersced69f82003-09-16 20:30:58 +00008580
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008581static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008582fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008583{
8584 /* No need to call PyUnicode_READY(self) because this function is only
8585 called as a callback from fixup() which does it already. */
8586 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8587 const int kind = PyUnicode_KIND(self);
8588 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008589 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008590 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008591 Py_ssize_t i;
8592
8593 for (i = 0; i < len; ++i) {
8594 ch = PyUnicode_READ(kind, data, i);
8595 fixed = 0;
8596 if (ch > 127) {
8597 if (Py_UNICODE_ISSPACE(ch))
8598 fixed = ' ';
8599 else {
8600 const int decimal = Py_UNICODE_TODECIMAL(ch);
8601 if (decimal >= 0)
8602 fixed = '0' + decimal;
8603 }
8604 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008605 modified = 1;
Victor Stinnere6abb482012-05-02 01:15:40 +02008606 maxchar = MAX_MAXCHAR(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008607 PyUnicode_WRITE(kind, data, i, fixed);
8608 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008609 else
8610 maxchar = MAX_MAXCHAR(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008611 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008612 }
8613
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008614 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008615}
8616
8617PyObject *
8618_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8619{
8620 if (!PyUnicode_Check(unicode)) {
8621 PyErr_BadInternalCall();
8622 return NULL;
8623 }
8624 if (PyUnicode_READY(unicode) == -1)
8625 return NULL;
8626 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8627 /* If the string is already ASCII, just return the same string */
8628 Py_INCREF(unicode);
8629 return unicode;
8630 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008631 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008632}
8633
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008634PyObject *
8635PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8636 Py_ssize_t length)
8637{
Victor Stinnerf0124502011-11-21 23:12:56 +01008638 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008639 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008640 Py_UCS4 maxchar;
8641 enum PyUnicode_Kind kind;
8642 void *data;
8643
Victor Stinner99d7ad02012-02-22 13:37:39 +01008644 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008645 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008646 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008647 if (ch > 127) {
8648 int decimal = Py_UNICODE_TODECIMAL(ch);
8649 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008650 ch = '0' + decimal;
Victor Stinnere6abb482012-05-02 01:15:40 +02008651 maxchar = MAX_MAXCHAR(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008652 }
8653 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008654
8655 /* Copy to a new string */
8656 decimal = PyUnicode_New(length, maxchar);
8657 if (decimal == NULL)
8658 return decimal;
8659 kind = PyUnicode_KIND(decimal);
8660 data = PyUnicode_DATA(decimal);
8661 /* Iterate over code points */
8662 for (i = 0; i < length; i++) {
8663 Py_UNICODE ch = s[i];
8664 if (ch > 127) {
8665 int decimal = Py_UNICODE_TODECIMAL(ch);
8666 if (decimal >= 0)
8667 ch = '0' + decimal;
8668 }
8669 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008670 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008671 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008672}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008673/* --- Decimal Encoder ---------------------------------------------------- */
8674
Alexander Belopolsky40018472011-02-26 01:02:56 +00008675int
8676PyUnicode_EncodeDecimal(Py_UNICODE *s,
8677 Py_ssize_t length,
8678 char *output,
8679 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008680{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008681 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008682 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008683 enum PyUnicode_Kind kind;
8684 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008685
8686 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008687 PyErr_BadArgument();
8688 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008689 }
8690
Victor Stinner42bf7752011-11-21 22:52:58 +01008691 unicode = PyUnicode_FromUnicode(s, length);
8692 if (unicode == NULL)
8693 return -1;
8694
Benjamin Petersonbac79492012-01-14 13:34:47 -05008695 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008696 Py_DECREF(unicode);
8697 return -1;
8698 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008699 kind = PyUnicode_KIND(unicode);
8700 data = PyUnicode_DATA(unicode);
8701
Victor Stinnerb84d7232011-11-22 01:50:07 +01008702 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008703 PyObject *exc;
8704 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008705 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008706 Py_ssize_t startpos;
8707
8708 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008709
Benjamin Peterson29060642009-01-31 22:14:21 +00008710 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008711 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008712 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008713 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008714 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008715 decimal = Py_UNICODE_TODECIMAL(ch);
8716 if (decimal >= 0) {
8717 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008718 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008719 continue;
8720 }
8721 if (0 < ch && ch < 256) {
8722 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008723 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008724 continue;
8725 }
Victor Stinner6345be92011-11-25 20:09:01 +01008726
Victor Stinner42bf7752011-11-21 22:52:58 +01008727 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008728 exc = NULL;
8729 raise_encode_exception(&exc, "decimal", unicode,
8730 startpos, startpos+1,
8731 "invalid decimal Unicode string");
8732 Py_XDECREF(exc);
8733 Py_DECREF(unicode);
8734 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008735 }
8736 /* 0-terminate the output string */
8737 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008738 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008739 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008740}
8741
Guido van Rossumd57fd912000-03-10 22:53:23 +00008742/* --- Helpers ------------------------------------------------------------ */
8743
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008744static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008745any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008746 Py_ssize_t start,
8747 Py_ssize_t end)
8748{
8749 int kind1, kind2, kind;
8750 void *buf1, *buf2;
8751 Py_ssize_t len1, len2, result;
8752
8753 kind1 = PyUnicode_KIND(s1);
8754 kind2 = PyUnicode_KIND(s2);
8755 kind = kind1 > kind2 ? kind1 : kind2;
8756 buf1 = PyUnicode_DATA(s1);
8757 buf2 = PyUnicode_DATA(s2);
8758 if (kind1 != kind)
8759 buf1 = _PyUnicode_AsKind(s1, kind);
8760 if (!buf1)
8761 return -2;
8762 if (kind2 != kind)
8763 buf2 = _PyUnicode_AsKind(s2, kind);
8764 if (!buf2) {
8765 if (kind1 != kind) PyMem_Free(buf1);
8766 return -2;
8767 }
8768 len1 = PyUnicode_GET_LENGTH(s1);
8769 len2 = PyUnicode_GET_LENGTH(s2);
8770
Victor Stinner794d5672011-10-10 03:21:36 +02008771 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008772 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008773 case PyUnicode_1BYTE_KIND:
8774 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8775 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8776 else
8777 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8778 break;
8779 case PyUnicode_2BYTE_KIND:
8780 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8781 break;
8782 case PyUnicode_4BYTE_KIND:
8783 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8784 break;
8785 default:
8786 assert(0); result = -2;
8787 }
8788 }
8789 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008790 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008791 case PyUnicode_1BYTE_KIND:
8792 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8793 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8794 else
8795 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8796 break;
8797 case PyUnicode_2BYTE_KIND:
8798 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8799 break;
8800 case PyUnicode_4BYTE_KIND:
8801 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8802 break;
8803 default:
8804 assert(0); result = -2;
8805 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008806 }
8807
8808 if (kind1 != kind)
8809 PyMem_Free(buf1);
8810 if (kind2 != kind)
8811 PyMem_Free(buf2);
8812
8813 return result;
8814}
8815
8816Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01008817_PyUnicode_InsertThousandsGrouping(
8818 PyObject *unicode, Py_ssize_t index,
8819 Py_ssize_t n_buffer,
8820 void *digits, Py_ssize_t n_digits,
8821 Py_ssize_t min_width,
8822 const char *grouping, PyObject *thousands_sep,
8823 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008824{
Victor Stinner41a863c2012-02-24 00:37:51 +01008825 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008826 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01008827 Py_ssize_t thousands_sep_len;
8828 Py_ssize_t len;
8829
8830 if (unicode != NULL) {
8831 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008832 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01008833 }
8834 else {
8835 kind = PyUnicode_1BYTE_KIND;
8836 data = NULL;
8837 }
8838 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
8839 thousands_sep_data = PyUnicode_DATA(thousands_sep);
8840 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
8841 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01008842 if (thousands_sep_kind < kind) {
8843 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
8844 if (!thousands_sep_data)
8845 return -1;
8846 }
8847 else {
8848 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
8849 if (!data)
8850 return -1;
8851 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008852 }
8853
Benjamin Petersonead6b532011-12-20 17:23:42 -06008854 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008855 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008856 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01008857 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008858 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008859 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008860 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02008861 else
Victor Stinner41a863c2012-02-24 00:37:51 +01008862 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008863 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008864 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008865 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008866 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008867 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008868 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008869 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008870 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008871 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008872 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008873 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008874 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008875 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008876 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008877 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008878 break;
8879 default:
8880 assert(0);
8881 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008882 }
Victor Stinner90f50d42012-02-24 01:44:47 +01008883 if (unicode != NULL && thousands_sep_kind != kind) {
8884 if (thousands_sep_kind < kind)
8885 PyMem_Free(thousands_sep_data);
8886 else
8887 PyMem_Free(data);
8888 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008889 if (unicode == NULL) {
8890 *maxchar = 127;
8891 if (len != n_digits) {
Victor Stinnere6abb482012-05-02 01:15:40 +02008892 *maxchar = MAX_MAXCHAR(*maxchar,
8893 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01008894 }
8895 }
8896 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008897}
8898
8899
Thomas Wouters477c8d52006-05-27 19:21:47 +00008900/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008901#define ADJUST_INDICES(start, end, len) \
8902 if (end > len) \
8903 end = len; \
8904 else if (end < 0) { \
8905 end += len; \
8906 if (end < 0) \
8907 end = 0; \
8908 } \
8909 if (start < 0) { \
8910 start += len; \
8911 if (start < 0) \
8912 start = 0; \
8913 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008914
Alexander Belopolsky40018472011-02-26 01:02:56 +00008915Py_ssize_t
8916PyUnicode_Count(PyObject *str,
8917 PyObject *substr,
8918 Py_ssize_t start,
8919 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008920{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008921 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008922 PyObject* str_obj;
8923 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008924 int kind1, kind2, kind;
8925 void *buf1 = NULL, *buf2 = NULL;
8926 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008927
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008928 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008929 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008930 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008931 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008932 if (!sub_obj) {
8933 Py_DECREF(str_obj);
8934 return -1;
8935 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06008936 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06008937 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008938 Py_DECREF(str_obj);
8939 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008940 }
Tim Petersced69f82003-09-16 20:30:58 +00008941
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008942 kind1 = PyUnicode_KIND(str_obj);
8943 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008944 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008945 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008946 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008947 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02008948 if (kind2 > kind) {
8949 Py_DECREF(sub_obj);
8950 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008951 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02008952 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01008953 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008954 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008955 if (!buf2)
8956 goto onError;
8957 len1 = PyUnicode_GET_LENGTH(str_obj);
8958 len2 = PyUnicode_GET_LENGTH(sub_obj);
8959
8960 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06008961 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008962 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008963 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8964 result = asciilib_count(
8965 ((Py_UCS1*)buf1) + start, end - start,
8966 buf2, len2, PY_SSIZE_T_MAX
8967 );
8968 else
8969 result = ucs1lib_count(
8970 ((Py_UCS1*)buf1) + start, end - start,
8971 buf2, len2, PY_SSIZE_T_MAX
8972 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008973 break;
8974 case PyUnicode_2BYTE_KIND:
8975 result = ucs2lib_count(
8976 ((Py_UCS2*)buf1) + start, end - start,
8977 buf2, len2, PY_SSIZE_T_MAX
8978 );
8979 break;
8980 case PyUnicode_4BYTE_KIND:
8981 result = ucs4lib_count(
8982 ((Py_UCS4*)buf1) + start, end - start,
8983 buf2, len2, PY_SSIZE_T_MAX
8984 );
8985 break;
8986 default:
8987 assert(0); result = 0;
8988 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008989
8990 Py_DECREF(sub_obj);
8991 Py_DECREF(str_obj);
8992
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008993 if (kind2 != kind)
8994 PyMem_Free(buf2);
8995
Guido van Rossumd57fd912000-03-10 22:53:23 +00008996 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008997 onError:
8998 Py_DECREF(sub_obj);
8999 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009000 if (kind2 != kind && buf2)
9001 PyMem_Free(buf2);
9002 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009003}
9004
Alexander Belopolsky40018472011-02-26 01:02:56 +00009005Py_ssize_t
9006PyUnicode_Find(PyObject *str,
9007 PyObject *sub,
9008 Py_ssize_t start,
9009 Py_ssize_t end,
9010 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009011{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009012 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009013
Guido van Rossumd57fd912000-03-10 22:53:23 +00009014 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009015 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009016 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009017 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009018 if (!sub) {
9019 Py_DECREF(str);
9020 return -2;
9021 }
9022 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9023 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009024 Py_DECREF(str);
9025 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009026 }
Tim Petersced69f82003-09-16 20:30:58 +00009027
Victor Stinner794d5672011-10-10 03:21:36 +02009028 result = any_find_slice(direction,
9029 str, sub, start, end
9030 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009031
Guido van Rossumd57fd912000-03-10 22:53:23 +00009032 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009033 Py_DECREF(sub);
9034
Guido van Rossumd57fd912000-03-10 22:53:23 +00009035 return result;
9036}
9037
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009038Py_ssize_t
9039PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9040 Py_ssize_t start, Py_ssize_t end,
9041 int direction)
9042{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009043 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009044 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009045 if (PyUnicode_READY(str) == -1)
9046 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009047 if (start < 0 || end < 0) {
9048 PyErr_SetString(PyExc_IndexError, "string index out of range");
9049 return -2;
9050 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009051 if (end > PyUnicode_GET_LENGTH(str))
9052 end = PyUnicode_GET_LENGTH(str);
9053 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009054 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9055 kind, end-start, ch, direction);
9056 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009057 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009058 else
9059 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009060}
9061
Alexander Belopolsky40018472011-02-26 01:02:56 +00009062static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009063tailmatch(PyObject *self,
9064 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009065 Py_ssize_t start,
9066 Py_ssize_t end,
9067 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009068{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009069 int kind_self;
9070 int kind_sub;
9071 void *data_self;
9072 void *data_sub;
9073 Py_ssize_t offset;
9074 Py_ssize_t i;
9075 Py_ssize_t end_sub;
9076
9077 if (PyUnicode_READY(self) == -1 ||
9078 PyUnicode_READY(substring) == -1)
9079 return 0;
9080
9081 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009082 return 1;
9083
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009084 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9085 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009086 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009087 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009088
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009089 kind_self = PyUnicode_KIND(self);
9090 data_self = PyUnicode_DATA(self);
9091 kind_sub = PyUnicode_KIND(substring);
9092 data_sub = PyUnicode_DATA(substring);
9093 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9094
9095 if (direction > 0)
9096 offset = end;
9097 else
9098 offset = start;
9099
9100 if (PyUnicode_READ(kind_self, data_self, offset) ==
9101 PyUnicode_READ(kind_sub, data_sub, 0) &&
9102 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9103 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9104 /* If both are of the same kind, memcmp is sufficient */
9105 if (kind_self == kind_sub) {
9106 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009107 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009108 data_sub,
9109 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009110 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009111 }
9112 /* otherwise we have to compare each character by first accesing it */
9113 else {
9114 /* We do not need to compare 0 and len(substring)-1 because
9115 the if statement above ensured already that they are equal
9116 when we end up here. */
9117 // TODO: honor direction and do a forward or backwards search
9118 for (i = 1; i < end_sub; ++i) {
9119 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9120 PyUnicode_READ(kind_sub, data_sub, i))
9121 return 0;
9122 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009123 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009124 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009125 }
9126
9127 return 0;
9128}
9129
Alexander Belopolsky40018472011-02-26 01:02:56 +00009130Py_ssize_t
9131PyUnicode_Tailmatch(PyObject *str,
9132 PyObject *substr,
9133 Py_ssize_t start,
9134 Py_ssize_t end,
9135 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009136{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009137 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009138
Guido van Rossumd57fd912000-03-10 22:53:23 +00009139 str = PyUnicode_FromObject(str);
9140 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009141 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009142 substr = PyUnicode_FromObject(substr);
9143 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009144 Py_DECREF(str);
9145 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009146 }
Tim Petersced69f82003-09-16 20:30:58 +00009147
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009148 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009149 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009150 Py_DECREF(str);
9151 Py_DECREF(substr);
9152 return result;
9153}
9154
Guido van Rossumd57fd912000-03-10 22:53:23 +00009155/* Apply fixfct filter to the Unicode object self and return a
9156 reference to the modified object */
9157
Alexander Belopolsky40018472011-02-26 01:02:56 +00009158static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009159fixup(PyObject *self,
9160 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009161{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009162 PyObject *u;
9163 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009164 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009165
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009166 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009167 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009168 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009169 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009170
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009171 /* fix functions return the new maximum character in a string,
9172 if the kind of the resulting unicode object does not change,
9173 everything is fine. Otherwise we need to change the string kind
9174 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009175 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009176
9177 if (maxchar_new == 0) {
9178 /* no changes */;
9179 if (PyUnicode_CheckExact(self)) {
9180 Py_DECREF(u);
9181 Py_INCREF(self);
9182 return self;
9183 }
9184 else
9185 return u;
9186 }
9187
Victor Stinnere6abb482012-05-02 01:15:40 +02009188 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009189
Victor Stinnereaab6042011-12-11 22:22:39 +01009190 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009191 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009192
9193 /* In case the maximum character changed, we need to
9194 convert the string to the new category. */
9195 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9196 if (v == NULL) {
9197 Py_DECREF(u);
9198 return NULL;
9199 }
9200 if (maxchar_new > maxchar_old) {
9201 /* If the maxchar increased so that the kind changed, not all
9202 characters are representable anymore and we need to fix the
9203 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009204 _PyUnicode_FastCopyCharacters(v, 0,
9205 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009206 maxchar_old = fixfct(v);
9207 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009208 }
9209 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009210 _PyUnicode_FastCopyCharacters(v, 0,
9211 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009212 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009213 Py_DECREF(u);
9214 assert(_PyUnicode_CheckConsistency(v, 1));
9215 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009216}
9217
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009218static PyObject *
9219ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009220{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009221 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9222 char *resdata, *data = PyUnicode_DATA(self);
9223 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009224
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009225 res = PyUnicode_New(len, 127);
9226 if (res == NULL)
9227 return NULL;
9228 resdata = PyUnicode_DATA(res);
9229 if (lower)
9230 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009231 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009232 _Py_bytes_upper(resdata, data, len);
9233 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009234}
9235
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009236static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009237handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009238{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009239 Py_ssize_t j;
9240 int final_sigma;
9241 Py_UCS4 c;
9242 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009243
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009244 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9245
9246 where ! is a negation and \p{xxx} is a character with property xxx.
9247 */
9248 for (j = i - 1; j >= 0; j--) {
9249 c = PyUnicode_READ(kind, data, j);
9250 if (!_PyUnicode_IsCaseIgnorable(c))
9251 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009252 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009253 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9254 if (final_sigma) {
9255 for (j = i + 1; j < length; j++) {
9256 c = PyUnicode_READ(kind, data, j);
9257 if (!_PyUnicode_IsCaseIgnorable(c))
9258 break;
9259 }
9260 final_sigma = j == length || !_PyUnicode_IsCased(c);
9261 }
9262 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009263}
9264
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009265static int
9266lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9267 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009268{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009269 /* Obscure special case. */
9270 if (c == 0x3A3) {
9271 mapped[0] = handle_capital_sigma(kind, data, length, i);
9272 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009273 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009274 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009275}
9276
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009277static Py_ssize_t
9278do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009279{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009280 Py_ssize_t i, k = 0;
9281 int n_res, j;
9282 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009283
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009284 c = PyUnicode_READ(kind, data, 0);
9285 n_res = _PyUnicode_ToUpperFull(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];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009289 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009290 for (i = 1; i < length; i++) {
9291 c = PyUnicode_READ(kind, data, i);
9292 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9293 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009294 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009295 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009296 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009297 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009298 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009299}
9300
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009301static Py_ssize_t
9302do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9303 Py_ssize_t i, k = 0;
9304
9305 for (i = 0; i < length; i++) {
9306 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9307 int n_res, j;
9308 if (Py_UNICODE_ISUPPER(c)) {
9309 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9310 }
9311 else if (Py_UNICODE_ISLOWER(c)) {
9312 n_res = _PyUnicode_ToUpperFull(c, mapped);
9313 }
9314 else {
9315 n_res = 1;
9316 mapped[0] = c;
9317 }
9318 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009319 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009320 res[k++] = mapped[j];
9321 }
9322 }
9323 return k;
9324}
9325
9326static Py_ssize_t
9327do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9328 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009329{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009330 Py_ssize_t i, k = 0;
9331
9332 for (i = 0; i < length; i++) {
9333 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9334 int n_res, j;
9335 if (lower)
9336 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9337 else
9338 n_res = _PyUnicode_ToUpperFull(c, mapped);
9339 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009340 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009341 res[k++] = mapped[j];
9342 }
9343 }
9344 return k;
9345}
9346
9347static Py_ssize_t
9348do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9349{
9350 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9351}
9352
9353static Py_ssize_t
9354do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9355{
9356 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9357}
9358
Benjamin Petersone51757f2012-01-12 21:10:29 -05009359static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009360do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9361{
9362 Py_ssize_t i, k = 0;
9363
9364 for (i = 0; i < length; i++) {
9365 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9366 Py_UCS4 mapped[3];
9367 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9368 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009369 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009370 res[k++] = mapped[j];
9371 }
9372 }
9373 return k;
9374}
9375
9376static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009377do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9378{
9379 Py_ssize_t i, k = 0;
9380 int previous_is_cased;
9381
9382 previous_is_cased = 0;
9383 for (i = 0; i < length; i++) {
9384 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9385 Py_UCS4 mapped[3];
9386 int n_res, j;
9387
9388 if (previous_is_cased)
9389 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9390 else
9391 n_res = _PyUnicode_ToTitleFull(c, mapped);
9392
9393 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009394 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009395 res[k++] = mapped[j];
9396 }
9397
9398 previous_is_cased = _PyUnicode_IsCased(c);
9399 }
9400 return k;
9401}
9402
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009403static PyObject *
9404case_operation(PyObject *self,
9405 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9406{
9407 PyObject *res = NULL;
9408 Py_ssize_t length, newlength = 0;
9409 int kind, outkind;
9410 void *data, *outdata;
9411 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9412
Benjamin Petersoneea48462012-01-16 14:28:50 -05009413 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009414
9415 kind = PyUnicode_KIND(self);
9416 data = PyUnicode_DATA(self);
9417 length = PyUnicode_GET_LENGTH(self);
9418 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9419 if (tmp == NULL)
9420 return PyErr_NoMemory();
9421 newlength = perform(kind, data, length, tmp, &maxchar);
9422 res = PyUnicode_New(newlength, maxchar);
9423 if (res == NULL)
9424 goto leave;
9425 tmpend = tmp + newlength;
9426 outdata = PyUnicode_DATA(res);
9427 outkind = PyUnicode_KIND(res);
9428 switch (outkind) {
9429 case PyUnicode_1BYTE_KIND:
9430 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9431 break;
9432 case PyUnicode_2BYTE_KIND:
9433 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9434 break;
9435 case PyUnicode_4BYTE_KIND:
9436 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9437 break;
9438 default:
9439 assert(0);
9440 break;
9441 }
9442 leave:
9443 PyMem_FREE(tmp);
9444 return res;
9445}
9446
Tim Peters8ce9f162004-08-27 01:49:32 +00009447PyObject *
9448PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009449{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009450 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009451 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009452 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009453 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009454 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9455 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009456 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009457 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009458 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009459 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009460 int use_memcpy;
9461 unsigned char *res_data = NULL, *sep_data = NULL;
9462 PyObject *last_obj;
9463 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464
Tim Peters05eba1f2004-08-27 21:32:02 +00009465 fseq = PySequence_Fast(seq, "");
9466 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009467 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009468 }
9469
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009470 /* NOTE: the following code can't call back into Python code,
9471 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009472 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009473
Tim Peters05eba1f2004-08-27 21:32:02 +00009474 seqlen = PySequence_Fast_GET_SIZE(fseq);
9475 /* If empty sequence, return u"". */
9476 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009477 Py_DECREF(fseq);
9478 Py_INCREF(unicode_empty);
9479 res = unicode_empty;
9480 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009481 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009482
Tim Peters05eba1f2004-08-27 21:32:02 +00009483 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009484 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009485 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009486 if (seqlen == 1) {
9487 if (PyUnicode_CheckExact(items[0])) {
9488 res = items[0];
9489 Py_INCREF(res);
9490 Py_DECREF(fseq);
9491 return res;
9492 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009493 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009494 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009495 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009496 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009497 /* Set up sep and seplen */
9498 if (separator == NULL) {
9499 /* fall back to a blank space separator */
9500 sep = PyUnicode_FromOrdinal(' ');
9501 if (!sep)
9502 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009503 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009504 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009505 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009506 else {
9507 if (!PyUnicode_Check(separator)) {
9508 PyErr_Format(PyExc_TypeError,
9509 "separator: expected str instance,"
9510 " %.80s found",
9511 Py_TYPE(separator)->tp_name);
9512 goto onError;
9513 }
9514 if (PyUnicode_READY(separator))
9515 goto onError;
9516 sep = separator;
9517 seplen = PyUnicode_GET_LENGTH(separator);
9518 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9519 /* inc refcount to keep this code path symmetric with the
9520 above case of a blank separator */
9521 Py_INCREF(sep);
9522 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009523 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009524 }
9525
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009526 /* There are at least two things to join, or else we have a subclass
9527 * of str in the sequence.
9528 * Do a pre-pass to figure out the total amount of space we'll
9529 * need (sz), and see whether all argument are strings.
9530 */
9531 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009532#ifdef Py_DEBUG
9533 use_memcpy = 0;
9534#else
9535 use_memcpy = 1;
9536#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009537 for (i = 0; i < seqlen; i++) {
9538 const Py_ssize_t old_sz = sz;
9539 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009540 if (!PyUnicode_Check(item)) {
9541 PyErr_Format(PyExc_TypeError,
9542 "sequence item %zd: expected str instance,"
9543 " %.80s found",
9544 i, Py_TYPE(item)->tp_name);
9545 goto onError;
9546 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009547 if (PyUnicode_READY(item) == -1)
9548 goto onError;
9549 sz += PyUnicode_GET_LENGTH(item);
9550 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnere6abb482012-05-02 01:15:40 +02009551 maxchar = MAX_MAXCHAR(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009552 if (i != 0)
9553 sz += seplen;
9554 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9555 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009556 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009557 goto onError;
9558 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009559 if (use_memcpy && last_obj != NULL) {
9560 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9561 use_memcpy = 0;
9562 }
9563 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009564 }
Tim Petersced69f82003-09-16 20:30:58 +00009565
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009566 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009567 if (res == NULL)
9568 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009569
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009570 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009571#ifdef Py_DEBUG
9572 use_memcpy = 0;
9573#else
9574 if (use_memcpy) {
9575 res_data = PyUnicode_1BYTE_DATA(res);
9576 kind = PyUnicode_KIND(res);
9577 if (seplen != 0)
9578 sep_data = PyUnicode_1BYTE_DATA(sep);
9579 }
9580#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009581 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009582 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009583 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009584 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009585 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009586 if (use_memcpy) {
9587 Py_MEMCPY(res_data,
9588 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009589 kind * seplen);
9590 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009591 }
9592 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009593 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009594 res_offset += seplen;
9595 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009596 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009597 itemlen = PyUnicode_GET_LENGTH(item);
9598 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009599 if (use_memcpy) {
9600 Py_MEMCPY(res_data,
9601 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009602 kind * itemlen);
9603 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009604 }
9605 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009606 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009607 res_offset += itemlen;
9608 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009609 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009610 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009611 if (use_memcpy)
9612 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009613 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009614 else
9615 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009616
Tim Peters05eba1f2004-08-27 21:32:02 +00009617 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009618 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009619 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009620 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009621
Benjamin Peterson29060642009-01-31 22:14:21 +00009622 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009623 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009624 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009625 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009626 return NULL;
9627}
9628
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009629#define FILL(kind, data, value, start, length) \
9630 do { \
9631 Py_ssize_t i_ = 0; \
9632 assert(kind != PyUnicode_WCHAR_KIND); \
9633 switch ((kind)) { \
9634 case PyUnicode_1BYTE_KIND: { \
9635 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009636 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009637 break; \
9638 } \
9639 case PyUnicode_2BYTE_KIND: { \
9640 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9641 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9642 break; \
9643 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009644 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009645 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9646 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9647 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009648 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009649 } \
9650 } \
9651 } while (0)
9652
Victor Stinnerd3f08822012-05-29 12:57:52 +02009653void
9654_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9655 Py_UCS4 fill_char)
9656{
9657 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9658 const void *data = PyUnicode_DATA(unicode);
9659 assert(PyUnicode_IS_READY(unicode));
9660 assert(unicode_modifiable(unicode));
9661 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9662 assert(start >= 0);
9663 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9664 FILL(kind, data, fill_char, start, length);
9665}
9666
Victor Stinner3fe55312012-01-04 00:33:50 +01009667Py_ssize_t
9668PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9669 Py_UCS4 fill_char)
9670{
9671 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009672
9673 if (!PyUnicode_Check(unicode)) {
9674 PyErr_BadInternalCall();
9675 return -1;
9676 }
9677 if (PyUnicode_READY(unicode) == -1)
9678 return -1;
9679 if (unicode_check_modifiable(unicode))
9680 return -1;
9681
Victor Stinnerd3f08822012-05-29 12:57:52 +02009682 if (start < 0) {
9683 PyErr_SetString(PyExc_IndexError, "string index out of range");
9684 return -1;
9685 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009686 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9687 PyErr_SetString(PyExc_ValueError,
9688 "fill character is bigger than "
9689 "the string maximum character");
9690 return -1;
9691 }
9692
9693 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9694 length = Py_MIN(maxlen, length);
9695 if (length <= 0)
9696 return 0;
9697
Victor Stinnerd3f08822012-05-29 12:57:52 +02009698 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009699 return length;
9700}
9701
Victor Stinner9310abb2011-10-05 00:59:23 +02009702static PyObject *
9703pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009704 Py_ssize_t left,
9705 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009706 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009707{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009708 PyObject *u;
9709 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009710 int kind;
9711 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009712
9713 if (left < 0)
9714 left = 0;
9715 if (right < 0)
9716 right = 0;
9717
Victor Stinnerc4b49542011-12-11 22:44:26 +01009718 if (left == 0 && right == 0)
9719 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009720
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009721 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9722 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009723 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9724 return NULL;
9725 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009726 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009727 maxchar = MAX_MAXCHAR(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009728 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009729 if (!u)
9730 return NULL;
9731
9732 kind = PyUnicode_KIND(u);
9733 data = PyUnicode_DATA(u);
9734 if (left)
9735 FILL(kind, data, fill, 0, left);
9736 if (right)
9737 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009738 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009739 assert(_PyUnicode_CheckConsistency(u, 1));
9740 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009741}
9742
Alexander Belopolsky40018472011-02-26 01:02:56 +00009743PyObject *
9744PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009745{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009746 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009747
9748 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009749 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009750 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009751 if (PyUnicode_READY(string) == -1) {
9752 Py_DECREF(string);
9753 return NULL;
9754 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009755
Benjamin Petersonead6b532011-12-20 17:23:42 -06009756 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009757 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009758 if (PyUnicode_IS_ASCII(string))
9759 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009760 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009761 PyUnicode_GET_LENGTH(string), keepends);
9762 else
9763 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009764 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009765 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009766 break;
9767 case PyUnicode_2BYTE_KIND:
9768 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009769 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009770 PyUnicode_GET_LENGTH(string), keepends);
9771 break;
9772 case PyUnicode_4BYTE_KIND:
9773 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009774 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009775 PyUnicode_GET_LENGTH(string), keepends);
9776 break;
9777 default:
9778 assert(0);
9779 list = 0;
9780 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009781 Py_DECREF(string);
9782 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009783}
9784
Alexander Belopolsky40018472011-02-26 01:02:56 +00009785static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009786split(PyObject *self,
9787 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009788 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009789{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009790 int kind1, kind2, kind;
9791 void *buf1, *buf2;
9792 Py_ssize_t len1, len2;
9793 PyObject* out;
9794
Guido van Rossumd57fd912000-03-10 22:53:23 +00009795 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009796 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009797
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009798 if (PyUnicode_READY(self) == -1)
9799 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009800
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009801 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009802 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009803 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009804 if (PyUnicode_IS_ASCII(self))
9805 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009806 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009807 PyUnicode_GET_LENGTH(self), maxcount
9808 );
9809 else
9810 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009811 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009812 PyUnicode_GET_LENGTH(self), maxcount
9813 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009814 case PyUnicode_2BYTE_KIND:
9815 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009816 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009817 PyUnicode_GET_LENGTH(self), maxcount
9818 );
9819 case PyUnicode_4BYTE_KIND:
9820 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009821 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009822 PyUnicode_GET_LENGTH(self), maxcount
9823 );
9824 default:
9825 assert(0);
9826 return NULL;
9827 }
9828
9829 if (PyUnicode_READY(substring) == -1)
9830 return NULL;
9831
9832 kind1 = PyUnicode_KIND(self);
9833 kind2 = PyUnicode_KIND(substring);
9834 kind = kind1 > kind2 ? kind1 : kind2;
9835 buf1 = PyUnicode_DATA(self);
9836 buf2 = PyUnicode_DATA(substring);
9837 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009838 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009839 if (!buf1)
9840 return NULL;
9841 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009842 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009843 if (!buf2) {
9844 if (kind1 != kind) PyMem_Free(buf1);
9845 return NULL;
9846 }
9847 len1 = PyUnicode_GET_LENGTH(self);
9848 len2 = PyUnicode_GET_LENGTH(substring);
9849
Benjamin Petersonead6b532011-12-20 17:23:42 -06009850 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009851 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009852 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9853 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009854 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009855 else
9856 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009857 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009858 break;
9859 case PyUnicode_2BYTE_KIND:
9860 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009861 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009862 break;
9863 case PyUnicode_4BYTE_KIND:
9864 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009865 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009866 break;
9867 default:
9868 out = NULL;
9869 }
9870 if (kind1 != kind)
9871 PyMem_Free(buf1);
9872 if (kind2 != kind)
9873 PyMem_Free(buf2);
9874 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009875}
9876
Alexander Belopolsky40018472011-02-26 01:02:56 +00009877static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009878rsplit(PyObject *self,
9879 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009880 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009881{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009882 int kind1, kind2, kind;
9883 void *buf1, *buf2;
9884 Py_ssize_t len1, len2;
9885 PyObject* out;
9886
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009887 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009888 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009889
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009890 if (PyUnicode_READY(self) == -1)
9891 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009892
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009893 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009894 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009895 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009896 if (PyUnicode_IS_ASCII(self))
9897 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009898 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009899 PyUnicode_GET_LENGTH(self), maxcount
9900 );
9901 else
9902 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009903 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009904 PyUnicode_GET_LENGTH(self), maxcount
9905 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009906 case PyUnicode_2BYTE_KIND:
9907 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009908 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009909 PyUnicode_GET_LENGTH(self), maxcount
9910 );
9911 case PyUnicode_4BYTE_KIND:
9912 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009913 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009914 PyUnicode_GET_LENGTH(self), maxcount
9915 );
9916 default:
9917 assert(0);
9918 return NULL;
9919 }
9920
9921 if (PyUnicode_READY(substring) == -1)
9922 return NULL;
9923
9924 kind1 = PyUnicode_KIND(self);
9925 kind2 = PyUnicode_KIND(substring);
9926 kind = kind1 > kind2 ? kind1 : kind2;
9927 buf1 = PyUnicode_DATA(self);
9928 buf2 = PyUnicode_DATA(substring);
9929 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009930 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009931 if (!buf1)
9932 return NULL;
9933 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009934 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009935 if (!buf2) {
9936 if (kind1 != kind) PyMem_Free(buf1);
9937 return NULL;
9938 }
9939 len1 = PyUnicode_GET_LENGTH(self);
9940 len2 = PyUnicode_GET_LENGTH(substring);
9941
Benjamin Petersonead6b532011-12-20 17:23:42 -06009942 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009943 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009944 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9945 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009946 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009947 else
9948 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009949 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009950 break;
9951 case PyUnicode_2BYTE_KIND:
9952 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009953 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009954 break;
9955 case PyUnicode_4BYTE_KIND:
9956 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009957 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009958 break;
9959 default:
9960 out = NULL;
9961 }
9962 if (kind1 != kind)
9963 PyMem_Free(buf1);
9964 if (kind2 != kind)
9965 PyMem_Free(buf2);
9966 return out;
9967}
9968
9969static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009970anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9971 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009972{
Benjamin Petersonead6b532011-12-20 17:23:42 -06009973 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009974 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009975 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9976 return asciilib_find(buf1, len1, buf2, len2, offset);
9977 else
9978 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009979 case PyUnicode_2BYTE_KIND:
9980 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9981 case PyUnicode_4BYTE_KIND:
9982 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9983 }
9984 assert(0);
9985 return -1;
9986}
9987
9988static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009989anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
9990 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009991{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -06009992 switch (kind) {
9993 case PyUnicode_1BYTE_KIND:
9994 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
9995 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
9996 else
9997 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
9998 case PyUnicode_2BYTE_KIND:
9999 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10000 case PyUnicode_4BYTE_KIND:
10001 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10002 }
10003 assert(0);
10004 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010005}
10006
Alexander Belopolsky40018472011-02-26 01:02:56 +000010007static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010008replace(PyObject *self, PyObject *str1,
10009 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010010{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010011 PyObject *u;
10012 char *sbuf = PyUnicode_DATA(self);
10013 char *buf1 = PyUnicode_DATA(str1);
10014 char *buf2 = PyUnicode_DATA(str2);
10015 int srelease = 0, release1 = 0, release2 = 0;
10016 int skind = PyUnicode_KIND(self);
10017 int kind1 = PyUnicode_KIND(str1);
10018 int kind2 = PyUnicode_KIND(str2);
10019 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10020 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10021 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010022 int mayshrink;
10023 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010024
10025 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010026 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010027 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010028 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010029
Victor Stinner59de0ee2011-10-07 10:01:28 +020010030 if (str1 == str2)
10031 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010032 if (skind < kind1)
10033 /* substring too wide to be present */
10034 goto nothing;
10035
Victor Stinner49a0a212011-10-12 23:46:10 +020010036 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10037 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10038 /* Replacing str1 with str2 may cause a maxchar reduction in the
10039 result string. */
10040 mayshrink = (maxchar_str2 < maxchar);
Victor Stinnere6abb482012-05-02 01:15:40 +020010041 maxchar = MAX_MAXCHAR(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010042
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010043 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010044 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010045 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010046 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010047 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010048 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010049 Py_UCS4 u1, u2;
10050 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010051 Py_ssize_t index, pos;
10052 char *src;
10053
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010054 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010055 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10056 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010057 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010058 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010059 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010060 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010061 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010062 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010063 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010064
10065 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10066 index = 0;
10067 src = sbuf;
10068 while (--maxcount)
10069 {
10070 pos++;
10071 src += pos * PyUnicode_KIND(self);
10072 slen -= pos;
10073 index += pos;
10074 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10075 if (pos < 0)
10076 break;
10077 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10078 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010079 }
10080 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010081 int rkind = skind;
10082 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010083 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010084
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010085 if (kind1 < rkind) {
10086 /* widen substring */
10087 buf1 = _PyUnicode_AsKind(str1, rkind);
10088 if (!buf1) goto error;
10089 release1 = 1;
10090 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010091 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010092 if (i < 0)
10093 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 if (rkind > kind2) {
10095 /* widen replacement */
10096 buf2 = _PyUnicode_AsKind(str2, rkind);
10097 if (!buf2) goto error;
10098 release2 = 1;
10099 }
10100 else if (rkind < kind2) {
10101 /* widen self and buf1 */
10102 rkind = kind2;
10103 if (release1) PyMem_Free(buf1);
10104 sbuf = _PyUnicode_AsKind(self, rkind);
10105 if (!sbuf) goto error;
10106 srelease = 1;
10107 buf1 = _PyUnicode_AsKind(str1, rkind);
10108 if (!buf1) goto error;
10109 release1 = 1;
10110 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010111 u = PyUnicode_New(slen, maxchar);
10112 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010113 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010114 assert(PyUnicode_KIND(u) == rkind);
10115 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010116
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010117 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010118 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010119 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010120 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010121 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010122 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010123
10124 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010125 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010126 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010127 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010128 if (i == -1)
10129 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010130 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010131 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010132 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010133 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010134 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010135 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010136 }
10137 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 Py_ssize_t n, i, j, ires;
10139 Py_ssize_t product, new_size;
10140 int rkind = skind;
10141 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010142
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010143 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010144 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010145 buf1 = _PyUnicode_AsKind(str1, rkind);
10146 if (!buf1) goto error;
10147 release1 = 1;
10148 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010149 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010150 if (n == 0)
10151 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010153 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 buf2 = _PyUnicode_AsKind(str2, rkind);
10155 if (!buf2) goto error;
10156 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010157 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010159 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010160 rkind = kind2;
10161 sbuf = _PyUnicode_AsKind(self, rkind);
10162 if (!sbuf) goto error;
10163 srelease = 1;
10164 if (release1) PyMem_Free(buf1);
10165 buf1 = _PyUnicode_AsKind(str1, rkind);
10166 if (!buf1) goto error;
10167 release1 = 1;
10168 }
10169 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10170 PyUnicode_GET_LENGTH(str1))); */
10171 product = n * (len2-len1);
10172 if ((product / (len2-len1)) != n) {
10173 PyErr_SetString(PyExc_OverflowError,
10174 "replace string is too long");
10175 goto error;
10176 }
10177 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010178 if (new_size == 0) {
10179 Py_INCREF(unicode_empty);
10180 u = unicode_empty;
10181 goto done;
10182 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10184 PyErr_SetString(PyExc_OverflowError,
10185 "replace string is too long");
10186 goto error;
10187 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010188 u = PyUnicode_New(new_size, maxchar);
10189 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010191 assert(PyUnicode_KIND(u) == rkind);
10192 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010193 ires = i = 0;
10194 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010195 while (n-- > 0) {
10196 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010197 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010198 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010199 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010200 if (j == -1)
10201 break;
10202 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010203 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010204 memcpy(res + rkind * ires,
10205 sbuf + rkind * i,
10206 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010208 }
10209 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010210 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010211 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010212 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010213 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010214 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010215 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010216 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010217 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010218 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010219 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010220 memcpy(res + rkind * ires,
10221 sbuf + rkind * i,
10222 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010223 }
10224 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010225 /* interleave */
10226 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010227 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010228 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010229 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010230 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010231 if (--n <= 0)
10232 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010233 memcpy(res + rkind * ires,
10234 sbuf + rkind * i,
10235 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010236 ires++;
10237 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010238 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010239 memcpy(res + rkind * ires,
10240 sbuf + rkind * i,
10241 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010242 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010243 }
10244
10245 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010246 unicode_adjust_maxchar(&u);
10247 if (u == NULL)
10248 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010249 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010250
10251 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010252 if (srelease)
10253 PyMem_FREE(sbuf);
10254 if (release1)
10255 PyMem_FREE(buf1);
10256 if (release2)
10257 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010258 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010259 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010260
Benjamin Peterson29060642009-01-31 22:14:21 +000010261 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010262 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010263 if (srelease)
10264 PyMem_FREE(sbuf);
10265 if (release1)
10266 PyMem_FREE(buf1);
10267 if (release2)
10268 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010269 return unicode_result_unchanged(self);
10270
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010271 error:
10272 if (srelease && sbuf)
10273 PyMem_FREE(sbuf);
10274 if (release1 && buf1)
10275 PyMem_FREE(buf1);
10276 if (release2 && buf2)
10277 PyMem_FREE(buf2);
10278 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010279}
10280
10281/* --- Unicode Object Methods --------------------------------------------- */
10282
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010283PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010284 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010285\n\
10286Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010287characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010288
10289static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010290unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010291{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010292 if (PyUnicode_READY(self) == -1)
10293 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010294 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010295}
10296
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010297PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010298 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010299\n\
10300Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010301have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010302
10303static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010304unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010305{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010306 if (PyUnicode_READY(self) == -1)
10307 return NULL;
10308 if (PyUnicode_GET_LENGTH(self) == 0)
10309 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010310 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010311}
10312
Benjamin Petersond5890c82012-01-14 13:23:30 -050010313PyDoc_STRVAR(casefold__doc__,
10314 "S.casefold() -> str\n\
10315\n\
10316Return a version of S suitable for caseless comparisons.");
10317
10318static PyObject *
10319unicode_casefold(PyObject *self)
10320{
10321 if (PyUnicode_READY(self) == -1)
10322 return NULL;
10323 if (PyUnicode_IS_ASCII(self))
10324 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010325 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010326}
10327
10328
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010329/* Argument converter. Coerces to a single unicode character */
10330
10331static int
10332convert_uc(PyObject *obj, void *addr)
10333{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010334 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010335 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010336
Benjamin Peterson14339b62009-01-31 16:36:08 +000010337 uniobj = PyUnicode_FromObject(obj);
10338 if (uniobj == NULL) {
10339 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010340 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010341 return 0;
10342 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010343 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010344 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010345 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010346 Py_DECREF(uniobj);
10347 return 0;
10348 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010349 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010350 Py_DECREF(uniobj);
10351 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010352}
10353
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010354PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010355 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010356\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010357Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010358done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010359
10360static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010361unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010362{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010363 Py_ssize_t marg, left;
10364 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010365 Py_UCS4 fillchar = ' ';
10366
Victor Stinnere9a29352011-10-01 02:14:59 +020010367 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010368 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010369
Benjamin Petersonbac79492012-01-14 13:34:47 -050010370 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010371 return NULL;
10372
Victor Stinnerc4b49542011-12-11 22:44:26 +010010373 if (PyUnicode_GET_LENGTH(self) >= width)
10374 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010375
Victor Stinnerc4b49542011-12-11 22:44:26 +010010376 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010377 left = marg / 2 + (marg & width & 1);
10378
Victor Stinner9310abb2011-10-05 00:59:23 +020010379 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010380}
10381
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010382/* This function assumes that str1 and str2 are readied by the caller. */
10383
Marc-André Lemburge5034372000-08-08 08:04:29 +000010384static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010385unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010386{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010387 int kind1, kind2;
10388 void *data1, *data2;
10389 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010390
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010391 kind1 = PyUnicode_KIND(str1);
10392 kind2 = PyUnicode_KIND(str2);
10393 data1 = PyUnicode_DATA(str1);
10394 data2 = PyUnicode_DATA(str2);
10395 len1 = PyUnicode_GET_LENGTH(str1);
10396 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010397
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010398 for (i = 0; i < len1 && i < len2; ++i) {
10399 Py_UCS4 c1, c2;
10400 c1 = PyUnicode_READ(kind1, data1, i);
10401 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010402
10403 if (c1 != c2)
10404 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010405 }
10406
10407 return (len1 < len2) ? -1 : (len1 != len2);
10408}
10409
Alexander Belopolsky40018472011-02-26 01:02:56 +000010410int
10411PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010412{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010413 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10414 if (PyUnicode_READY(left) == -1 ||
10415 PyUnicode_READY(right) == -1)
10416 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010417 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010418 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010419 PyErr_Format(PyExc_TypeError,
10420 "Can't compare %.100s and %.100s",
10421 left->ob_type->tp_name,
10422 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010423 return -1;
10424}
10425
Martin v. Löwis5b222132007-06-10 09:51:05 +000010426int
10427PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10428{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010429 Py_ssize_t i;
10430 int kind;
10431 void *data;
10432 Py_UCS4 chr;
10433
Victor Stinner910337b2011-10-03 03:20:16 +020010434 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010435 if (PyUnicode_READY(uni) == -1)
10436 return -1;
10437 kind = PyUnicode_KIND(uni);
10438 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010439 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010440 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10441 if (chr != str[i])
10442 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010443 /* This check keeps Python strings that end in '\0' from comparing equal
10444 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010445 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010446 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010447 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010448 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010449 return 0;
10450}
10451
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010452
Benjamin Peterson29060642009-01-31 22:14:21 +000010453#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010454 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010455
Alexander Belopolsky40018472011-02-26 01:02:56 +000010456PyObject *
10457PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010458{
10459 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010460
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010461 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10462 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010463 if (PyUnicode_READY(left) == -1 ||
10464 PyUnicode_READY(right) == -1)
10465 return NULL;
10466 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10467 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010468 if (op == Py_EQ) {
10469 Py_INCREF(Py_False);
10470 return Py_False;
10471 }
10472 if (op == Py_NE) {
10473 Py_INCREF(Py_True);
10474 return Py_True;
10475 }
10476 }
10477 if (left == right)
10478 result = 0;
10479 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010480 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010481
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010482 /* Convert the return value to a Boolean */
10483 switch (op) {
10484 case Py_EQ:
10485 v = TEST_COND(result == 0);
10486 break;
10487 case Py_NE:
10488 v = TEST_COND(result != 0);
10489 break;
10490 case Py_LE:
10491 v = TEST_COND(result <= 0);
10492 break;
10493 case Py_GE:
10494 v = TEST_COND(result >= 0);
10495 break;
10496 case Py_LT:
10497 v = TEST_COND(result == -1);
10498 break;
10499 case Py_GT:
10500 v = TEST_COND(result == 1);
10501 break;
10502 default:
10503 PyErr_BadArgument();
10504 return NULL;
10505 }
10506 Py_INCREF(v);
10507 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010508 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010509
Brian Curtindfc80e32011-08-10 20:28:54 -050010510 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010511}
10512
Alexander Belopolsky40018472011-02-26 01:02:56 +000010513int
10514PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010515{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010516 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 int kind1, kind2, kind;
10518 void *buf1, *buf2;
10519 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010520 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010521
10522 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010523 sub = PyUnicode_FromObject(element);
10524 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010525 PyErr_Format(PyExc_TypeError,
10526 "'in <string>' requires string as left operand, not %s",
10527 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010528 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010529 }
10530
Thomas Wouters477c8d52006-05-27 19:21:47 +000010531 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010532 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010533 Py_DECREF(sub);
10534 return -1;
10535 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010536 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10537 Py_DECREF(sub);
10538 Py_DECREF(str);
10539 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010540
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010541 kind1 = PyUnicode_KIND(str);
10542 kind2 = PyUnicode_KIND(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010543 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010544 buf1 = PyUnicode_DATA(str);
10545 buf2 = PyUnicode_DATA(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010546 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010547 if (kind2 > kind) {
10548 Py_DECREF(sub);
10549 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010550 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010551 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010010552 buf2 = _PyUnicode_AsKind(sub, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010553 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010554 if (!buf2) {
10555 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010556 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010557 return -1;
10558 }
10559 len1 = PyUnicode_GET_LENGTH(str);
10560 len2 = PyUnicode_GET_LENGTH(sub);
10561
Benjamin Petersonead6b532011-12-20 17:23:42 -060010562 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010563 case PyUnicode_1BYTE_KIND:
10564 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10565 break;
10566 case PyUnicode_2BYTE_KIND:
10567 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10568 break;
10569 case PyUnicode_4BYTE_KIND:
10570 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10571 break;
10572 default:
10573 result = -1;
10574 assert(0);
10575 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010576
10577 Py_DECREF(str);
10578 Py_DECREF(sub);
10579
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010580 if (kind2 != kind)
10581 PyMem_Free(buf2);
10582
Guido van Rossum403d68b2000-03-13 15:55:09 +000010583 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010584}
10585
Guido van Rossumd57fd912000-03-10 22:53:23 +000010586/* Concat to string or Unicode object giving a new Unicode object. */
10587
Alexander Belopolsky40018472011-02-26 01:02:56 +000010588PyObject *
10589PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010590{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010591 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010592 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010593 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010594
10595 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010596 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010597 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010598 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010599 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010600 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010601 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010602
10603 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010604 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010605 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010606 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010607 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010608 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010609 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010610 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010611 }
10612
Victor Stinner488fa492011-12-12 00:01:39 +010010613 u_len = PyUnicode_GET_LENGTH(u);
10614 v_len = PyUnicode_GET_LENGTH(v);
10615 if (u_len > PY_SSIZE_T_MAX - v_len) {
10616 PyErr_SetString(PyExc_OverflowError,
10617 "strings are too large to concat");
10618 goto onError;
10619 }
10620 new_len = u_len + v_len;
10621
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010622 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010623 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Victor Stinnere6abb482012-05-02 01:15:40 +020010624 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010625
Guido van Rossumd57fd912000-03-10 22:53:23 +000010626 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010627 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010628 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010629 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010630 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10631 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010632 Py_DECREF(u);
10633 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010634 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010636
Benjamin Peterson29060642009-01-31 22:14:21 +000010637 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010638 Py_XDECREF(u);
10639 Py_XDECREF(v);
10640 return NULL;
10641}
10642
Walter Dörwald1ab83302007-05-18 17:15:44 +000010643void
Victor Stinner23e56682011-10-03 03:54:37 +020010644PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010645{
Victor Stinner23e56682011-10-03 03:54:37 +020010646 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010647 Py_UCS4 maxchar, maxchar2;
10648 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010649
10650 if (p_left == NULL) {
10651 if (!PyErr_Occurred())
10652 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010653 return;
10654 }
Victor Stinner23e56682011-10-03 03:54:37 +020010655 left = *p_left;
10656 if (right == NULL || !PyUnicode_Check(left)) {
10657 if (!PyErr_Occurred())
10658 PyErr_BadInternalCall();
10659 goto error;
10660 }
10661
Benjamin Petersonbac79492012-01-14 13:34:47 -050010662 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010663 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010664 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010665 goto error;
10666
Victor Stinner488fa492011-12-12 00:01:39 +010010667 /* Shortcuts */
10668 if (left == unicode_empty) {
10669 Py_DECREF(left);
10670 Py_INCREF(right);
10671 *p_left = right;
10672 return;
10673 }
10674 if (right == unicode_empty)
10675 return;
10676
10677 left_len = PyUnicode_GET_LENGTH(left);
10678 right_len = PyUnicode_GET_LENGTH(right);
10679 if (left_len > PY_SSIZE_T_MAX - right_len) {
10680 PyErr_SetString(PyExc_OverflowError,
10681 "strings are too large to concat");
10682 goto error;
10683 }
10684 new_len = left_len + right_len;
10685
10686 if (unicode_modifiable(left)
10687 && PyUnicode_CheckExact(right)
10688 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010689 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10690 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010691 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010692 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010693 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10694 {
10695 /* append inplace */
10696 if (unicode_resize(p_left, new_len) != 0) {
10697 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10698 * deallocated so it cannot be put back into
10699 * 'variable'. The MemoryError is raised when there
10700 * is no value in 'variable', which might (very
10701 * remotely) be a cause of incompatibilities.
10702 */
10703 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010704 }
Victor Stinner488fa492011-12-12 00:01:39 +010010705 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerd3f08822012-05-29 12:57:52 +020010706 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010707 }
Victor Stinner488fa492011-12-12 00:01:39 +010010708 else {
10709 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10710 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Victor Stinnere6abb482012-05-02 01:15:40 +020010711 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010712
Victor Stinner488fa492011-12-12 00:01:39 +010010713 /* Concat the two Unicode strings */
10714 res = PyUnicode_New(new_len, maxchar);
10715 if (res == NULL)
10716 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010717 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10718 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010719 Py_DECREF(left);
10720 *p_left = res;
10721 }
10722 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010723 return;
10724
10725error:
Victor Stinner488fa492011-12-12 00:01:39 +010010726 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010727}
10728
10729void
10730PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10731{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010732 PyUnicode_Append(pleft, right);
10733 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010734}
10735
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010736PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010737 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010738\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010739Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010740string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010741interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010742
10743static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010744unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010745{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010746 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010747 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010748 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010749 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010750 int kind1, kind2, kind;
10751 void *buf1, *buf2;
10752 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010753
Jesus Ceaac451502011-04-20 17:09:23 +020010754 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10755 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010756 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010757
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010758 kind1 = PyUnicode_KIND(self);
10759 kind2 = PyUnicode_KIND(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010760 if (kind2 > kind1)
10761 return PyLong_FromLong(0);
10762 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010763 buf1 = PyUnicode_DATA(self);
10764 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010765 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010766 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010767 if (!buf2) {
10768 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010769 return NULL;
10770 }
10771 len1 = PyUnicode_GET_LENGTH(self);
10772 len2 = PyUnicode_GET_LENGTH(substring);
10773
10774 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010775 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010776 case PyUnicode_1BYTE_KIND:
10777 iresult = ucs1lib_count(
10778 ((Py_UCS1*)buf1) + start, end - start,
10779 buf2, len2, PY_SSIZE_T_MAX
10780 );
10781 break;
10782 case PyUnicode_2BYTE_KIND:
10783 iresult = ucs2lib_count(
10784 ((Py_UCS2*)buf1) + start, end - start,
10785 buf2, len2, PY_SSIZE_T_MAX
10786 );
10787 break;
10788 case PyUnicode_4BYTE_KIND:
10789 iresult = ucs4lib_count(
10790 ((Py_UCS4*)buf1) + start, end - start,
10791 buf2, len2, PY_SSIZE_T_MAX
10792 );
10793 break;
10794 default:
10795 assert(0); iresult = 0;
10796 }
10797
10798 result = PyLong_FromSsize_t(iresult);
10799
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010800 if (kind2 != kind)
10801 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010802
10803 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010804
Guido van Rossumd57fd912000-03-10 22:53:23 +000010805 return result;
10806}
10807
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010808PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010809 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010810\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010811Encode S using the codec registered for encoding. Default encoding\n\
10812is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010813handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010814a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10815'xmlcharrefreplace' as well as any other name registered with\n\
10816codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010817
10818static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010819unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010820{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010821 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010822 char *encoding = NULL;
10823 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010824
Benjamin Peterson308d6372009-09-18 21:42:35 +000010825 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10826 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010827 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010828 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010829}
10830
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010831PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010832 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010833\n\
10834Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010835If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010836
10837static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010838unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010839{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010840 Py_ssize_t i, j, line_pos, src_len, incr;
10841 Py_UCS4 ch;
10842 PyObject *u;
10843 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010844 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010845 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010846 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010847
10848 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010849 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010850
Antoine Pitrou22425222011-10-04 19:10:51 +020010851 if (PyUnicode_READY(self) == -1)
10852 return NULL;
10853
Thomas Wouters7e474022000-07-16 12:04:32 +000010854 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010855 src_len = PyUnicode_GET_LENGTH(self);
10856 i = j = line_pos = 0;
10857 kind = PyUnicode_KIND(self);
10858 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010859 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010860 for (; i < src_len; i++) {
10861 ch = PyUnicode_READ(kind, src_data, i);
10862 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010863 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010864 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010865 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010866 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010867 goto overflow;
10868 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010869 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010870 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010871 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010872 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010873 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010874 goto overflow;
10875 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010876 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010877 if (ch == '\n' || ch == '\r')
10878 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010879 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010880 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010010881 if (!found)
10882 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010883
Guido van Rossumd57fd912000-03-10 22:53:23 +000010884 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010885 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010886 if (!u)
10887 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010888 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010889
Antoine Pitroue71d5742011-10-04 15:55:09 +020010890 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010891
Antoine Pitroue71d5742011-10-04 15:55:09 +020010892 for (; i < src_len; i++) {
10893 ch = PyUnicode_READ(kind, src_data, i);
10894 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010895 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010896 incr = tabsize - (line_pos % tabsize);
10897 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010010898 FILL(kind, dest_data, ' ', j, incr);
10899 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010900 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010901 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010902 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010903 line_pos++;
10904 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010905 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010906 if (ch == '\n' || ch == '\r')
10907 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010908 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010909 }
10910 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010911 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010912
Antoine Pitroue71d5742011-10-04 15:55:09 +020010913 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010914 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10915 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010916}
10917
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010918PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010919 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010920\n\
10921Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010922such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010923arguments start and end are interpreted as in slice notation.\n\
10924\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010925Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010926
10927static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010928unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010929{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010930 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010931 Py_ssize_t start;
10932 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010933 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010934
Jesus Ceaac451502011-04-20 17:09:23 +020010935 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10936 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010937 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010938
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010939 if (PyUnicode_READY(self) == -1)
10940 return NULL;
10941 if (PyUnicode_READY(substring) == -1)
10942 return NULL;
10943
Victor Stinner7931d9a2011-11-04 00:22:48 +010010944 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010945
10946 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010947
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010948 if (result == -2)
10949 return NULL;
10950
Christian Heimes217cfd12007-12-02 14:31:20 +000010951 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010952}
10953
10954static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010955unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010956{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010957 void *data;
10958 enum PyUnicode_Kind kind;
10959 Py_UCS4 ch;
10960 PyObject *res;
10961
10962 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
10963 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010964 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010965 }
10966 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
10967 PyErr_SetString(PyExc_IndexError, "string index out of range");
10968 return NULL;
10969 }
10970 kind = PyUnicode_KIND(self);
10971 data = PyUnicode_DATA(self);
10972 ch = PyUnicode_READ(kind, data, index);
10973 if (ch < 256)
10974 return get_latin1_char(ch);
10975
10976 res = PyUnicode_New(1, ch);
10977 if (res == NULL)
10978 return NULL;
10979 kind = PyUnicode_KIND(res);
10980 data = PyUnicode_DATA(res);
10981 PyUnicode_WRITE(kind, data, 0, ch);
10982 assert(_PyUnicode_CheckConsistency(res, 1));
10983 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010984}
10985
Guido van Rossumc2504932007-09-18 19:42:40 +000010986/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010010987 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000010988static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010989unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010990{
Guido van Rossumc2504932007-09-18 19:42:40 +000010991 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010010992 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010993
Benjamin Petersonf6622c82012-04-09 14:53:07 -040010994#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050010995 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040010996#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010997 if (_PyUnicode_HASH(self) != -1)
10998 return _PyUnicode_HASH(self);
10999 if (PyUnicode_READY(self) == -1)
11000 return -1;
11001 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011002 /*
11003 We make the hash of the empty string be 0, rather than using
11004 (prefix ^ suffix), since this slightly obfuscates the hash secret
11005 */
11006 if (len == 0) {
11007 _PyUnicode_HASH(self) = 0;
11008 return 0;
11009 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011010
11011 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011012#define HASH(P) \
11013 x ^= (Py_uhash_t) *P << 7; \
11014 while (--len >= 0) \
11015 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011016
Georg Brandl2fb477c2012-02-21 00:33:36 +010011017 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011018 switch (PyUnicode_KIND(self)) {
11019 case PyUnicode_1BYTE_KIND: {
11020 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11021 HASH(c);
11022 break;
11023 }
11024 case PyUnicode_2BYTE_KIND: {
11025 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11026 HASH(s);
11027 break;
11028 }
11029 default: {
11030 Py_UCS4 *l;
11031 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11032 "Impossible switch case in unicode_hash");
11033 l = PyUnicode_4BYTE_DATA(self);
11034 HASH(l);
11035 break;
11036 }
11037 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011038 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11039 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011040
Guido van Rossumc2504932007-09-18 19:42:40 +000011041 if (x == -1)
11042 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011043 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011044 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011045}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011046#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011047
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011048PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011049 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011050\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011051Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011052
11053static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011054unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011055{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011056 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011057 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011058 Py_ssize_t start;
11059 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011060
Jesus Ceaac451502011-04-20 17:09:23 +020011061 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11062 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011063 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011064
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011065 if (PyUnicode_READY(self) == -1)
11066 return NULL;
11067 if (PyUnicode_READY(substring) == -1)
11068 return NULL;
11069
Victor Stinner7931d9a2011-11-04 00:22:48 +010011070 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011071
11072 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011073
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011074 if (result == -2)
11075 return NULL;
11076
Guido van Rossumd57fd912000-03-10 22:53:23 +000011077 if (result < 0) {
11078 PyErr_SetString(PyExc_ValueError, "substring not found");
11079 return NULL;
11080 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011081
Christian Heimes217cfd12007-12-02 14:31:20 +000011082 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011083}
11084
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011085PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011086 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011087\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011088Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011089at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011090
11091static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011092unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011093{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011094 Py_ssize_t i, length;
11095 int kind;
11096 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011097 int cased;
11098
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011099 if (PyUnicode_READY(self) == -1)
11100 return NULL;
11101 length = PyUnicode_GET_LENGTH(self);
11102 kind = PyUnicode_KIND(self);
11103 data = PyUnicode_DATA(self);
11104
Guido van Rossumd57fd912000-03-10 22:53:23 +000011105 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011106 if (length == 1)
11107 return PyBool_FromLong(
11108 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011109
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011110 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011111 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011112 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011113
Guido van Rossumd57fd912000-03-10 22:53:23 +000011114 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011115 for (i = 0; i < length; i++) {
11116 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011117
Benjamin Peterson29060642009-01-31 22:14:21 +000011118 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11119 return PyBool_FromLong(0);
11120 else if (!cased && Py_UNICODE_ISLOWER(ch))
11121 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011122 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011123 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011124}
11125
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011126PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011127 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011128\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011129Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011130at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011131
11132static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011133unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011134{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011135 Py_ssize_t i, length;
11136 int kind;
11137 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011138 int cased;
11139
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011140 if (PyUnicode_READY(self) == -1)
11141 return NULL;
11142 length = PyUnicode_GET_LENGTH(self);
11143 kind = PyUnicode_KIND(self);
11144 data = PyUnicode_DATA(self);
11145
Guido van Rossumd57fd912000-03-10 22:53:23 +000011146 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011147 if (length == 1)
11148 return PyBool_FromLong(
11149 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011150
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011151 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011152 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011153 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011154
Guido van Rossumd57fd912000-03-10 22:53:23 +000011155 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011156 for (i = 0; i < length; i++) {
11157 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011158
Benjamin Peterson29060642009-01-31 22:14:21 +000011159 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11160 return PyBool_FromLong(0);
11161 else if (!cased && Py_UNICODE_ISUPPER(ch))
11162 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011163 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011164 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011165}
11166
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011167PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011168 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011169\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011170Return True if S is a titlecased string and there is at least one\n\
11171character in S, i.e. upper- and titlecase characters may only\n\
11172follow uncased characters and lowercase characters only cased ones.\n\
11173Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174
11175static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011176unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011177{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011178 Py_ssize_t i, length;
11179 int kind;
11180 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011181 int cased, previous_is_cased;
11182
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011183 if (PyUnicode_READY(self) == -1)
11184 return NULL;
11185 length = PyUnicode_GET_LENGTH(self);
11186 kind = PyUnicode_KIND(self);
11187 data = PyUnicode_DATA(self);
11188
Guido van Rossumd57fd912000-03-10 22:53:23 +000011189 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011190 if (length == 1) {
11191 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11192 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11193 (Py_UNICODE_ISUPPER(ch) != 0));
11194 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011196 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011197 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011198 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011199
Guido van Rossumd57fd912000-03-10 22:53:23 +000011200 cased = 0;
11201 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011202 for (i = 0; i < length; i++) {
11203 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011204
Benjamin Peterson29060642009-01-31 22:14:21 +000011205 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11206 if (previous_is_cased)
11207 return PyBool_FromLong(0);
11208 previous_is_cased = 1;
11209 cased = 1;
11210 }
11211 else if (Py_UNICODE_ISLOWER(ch)) {
11212 if (!previous_is_cased)
11213 return PyBool_FromLong(0);
11214 previous_is_cased = 1;
11215 cased = 1;
11216 }
11217 else
11218 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011220 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221}
11222
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011223PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011224 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011226Return True if all characters in S are whitespace\n\
11227and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011228
11229static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011230unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011231{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011232 Py_ssize_t i, length;
11233 int kind;
11234 void *data;
11235
11236 if (PyUnicode_READY(self) == -1)
11237 return NULL;
11238 length = PyUnicode_GET_LENGTH(self);
11239 kind = PyUnicode_KIND(self);
11240 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241
Guido van Rossumd57fd912000-03-10 22:53:23 +000011242 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011243 if (length == 1)
11244 return PyBool_FromLong(
11245 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011246
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011247 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011248 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011249 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011250
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011251 for (i = 0; i < length; i++) {
11252 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011253 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011254 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011255 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011256 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011257}
11258
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011259PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011260 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011261\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011262Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011263and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011264
11265static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011266unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011267{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011268 Py_ssize_t i, length;
11269 int kind;
11270 void *data;
11271
11272 if (PyUnicode_READY(self) == -1)
11273 return NULL;
11274 length = PyUnicode_GET_LENGTH(self);
11275 kind = PyUnicode_KIND(self);
11276 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011277
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011278 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011279 if (length == 1)
11280 return PyBool_FromLong(
11281 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011282
11283 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011284 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011285 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011286
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011287 for (i = 0; i < length; i++) {
11288 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011289 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011290 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011291 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011292}
11293
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011294PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011295 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011296\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011297Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011298and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011299
11300static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011301unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011302{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011303 int kind;
11304 void *data;
11305 Py_ssize_t len, i;
11306
11307 if (PyUnicode_READY(self) == -1)
11308 return NULL;
11309
11310 kind = PyUnicode_KIND(self);
11311 data = PyUnicode_DATA(self);
11312 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011313
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011314 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011315 if (len == 1) {
11316 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11317 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11318 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011319
11320 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011321 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011322 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011323
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011324 for (i = 0; i < len; i++) {
11325 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011326 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011327 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011328 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011329 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011330}
11331
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011332PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011333 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011334\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011335Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011336False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011337
11338static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011339unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011340{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011341 Py_ssize_t i, length;
11342 int kind;
11343 void *data;
11344
11345 if (PyUnicode_READY(self) == -1)
11346 return NULL;
11347 length = PyUnicode_GET_LENGTH(self);
11348 kind = PyUnicode_KIND(self);
11349 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350
Guido van Rossumd57fd912000-03-10 22:53:23 +000011351 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011352 if (length == 1)
11353 return PyBool_FromLong(
11354 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011355
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011356 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011357 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011358 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011359
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011360 for (i = 0; i < length; i++) {
11361 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011362 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011363 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011364 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011365}
11366
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011367PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011368 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011369\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011370Return True if all characters in S are digits\n\
11371and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011372
11373static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011374unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011375{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011376 Py_ssize_t i, length;
11377 int kind;
11378 void *data;
11379
11380 if (PyUnicode_READY(self) == -1)
11381 return NULL;
11382 length = PyUnicode_GET_LENGTH(self);
11383 kind = PyUnicode_KIND(self);
11384 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011385
Guido van Rossumd57fd912000-03-10 22:53:23 +000011386 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011387 if (length == 1) {
11388 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11389 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11390 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011392 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011393 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011394 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011395
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011396 for (i = 0; i < length; i++) {
11397 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011398 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011399 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011400 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011401}
11402
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011403PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011404 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011405\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011406Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011407False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011408
11409static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011410unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011412 Py_ssize_t i, length;
11413 int kind;
11414 void *data;
11415
11416 if (PyUnicode_READY(self) == -1)
11417 return NULL;
11418 length = PyUnicode_GET_LENGTH(self);
11419 kind = PyUnicode_KIND(self);
11420 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421
Guido van Rossumd57fd912000-03-10 22:53:23 +000011422 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011423 if (length == 1)
11424 return PyBool_FromLong(
11425 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011427 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011428 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011429 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011430
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011431 for (i = 0; i < length; i++) {
11432 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011433 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011434 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011435 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011436}
11437
Martin v. Löwis47383402007-08-15 07:32:56 +000011438int
11439PyUnicode_IsIdentifier(PyObject *self)
11440{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011441 int kind;
11442 void *data;
11443 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011444 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011445
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011446 if (PyUnicode_READY(self) == -1) {
11447 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011448 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011449 }
11450
11451 /* Special case for empty strings */
11452 if (PyUnicode_GET_LENGTH(self) == 0)
11453 return 0;
11454 kind = PyUnicode_KIND(self);
11455 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011456
11457 /* PEP 3131 says that the first character must be in
11458 XID_Start and subsequent characters in XID_Continue,
11459 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011460 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011461 letters, digits, underscore). However, given the current
11462 definition of XID_Start and XID_Continue, it is sufficient
11463 to check just for these, except that _ must be allowed
11464 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011465 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011466 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011467 return 0;
11468
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011469 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011470 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011471 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011472 return 1;
11473}
11474
11475PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011476 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011477\n\
11478Return True if S is a valid identifier according\n\
11479to the language definition.");
11480
11481static PyObject*
11482unicode_isidentifier(PyObject *self)
11483{
11484 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11485}
11486
Georg Brandl559e5d72008-06-11 18:37:52 +000011487PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011488 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011489\n\
11490Return True if all characters in S are considered\n\
11491printable in repr() or S is empty, False otherwise.");
11492
11493static PyObject*
11494unicode_isprintable(PyObject *self)
11495{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011496 Py_ssize_t i, length;
11497 int kind;
11498 void *data;
11499
11500 if (PyUnicode_READY(self) == -1)
11501 return NULL;
11502 length = PyUnicode_GET_LENGTH(self);
11503 kind = PyUnicode_KIND(self);
11504 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011505
11506 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011507 if (length == 1)
11508 return PyBool_FromLong(
11509 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011510
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011511 for (i = 0; i < length; i++) {
11512 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011513 Py_RETURN_FALSE;
11514 }
11515 }
11516 Py_RETURN_TRUE;
11517}
11518
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011519PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011520 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521\n\
11522Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011523iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524
11525static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011526unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011527{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011528 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529}
11530
Martin v. Löwis18e16552006-02-15 17:27:45 +000011531static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011532unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011533{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011534 if (PyUnicode_READY(self) == -1)
11535 return -1;
11536 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011537}
11538
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011539PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011540 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011542Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011543done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011544
11545static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011546unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011548 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011549 Py_UCS4 fillchar = ' ';
11550
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011551 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011552 return NULL;
11553
Benjamin Petersonbac79492012-01-14 13:34:47 -050011554 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011555 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011556
Victor Stinnerc4b49542011-12-11 22:44:26 +010011557 if (PyUnicode_GET_LENGTH(self) >= width)
11558 return unicode_result_unchanged(self);
11559
11560 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011561}
11562
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011563PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011564 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011565\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011566Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567
11568static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011569unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011571 if (PyUnicode_READY(self) == -1)
11572 return NULL;
11573 if (PyUnicode_IS_ASCII(self))
11574 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011575 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011576}
11577
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011578#define LEFTSTRIP 0
11579#define RIGHTSTRIP 1
11580#define BOTHSTRIP 2
11581
11582/* Arrays indexed by above */
11583static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11584
11585#define STRIPNAME(i) (stripformat[i]+3)
11586
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011587/* externally visible for str.strip(unicode) */
11588PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011589_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011590{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011591 void *data;
11592 int kind;
11593 Py_ssize_t i, j, len;
11594 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011595
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011596 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11597 return NULL;
11598
11599 kind = PyUnicode_KIND(self);
11600 data = PyUnicode_DATA(self);
11601 len = PyUnicode_GET_LENGTH(self);
11602 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11603 PyUnicode_DATA(sepobj),
11604 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011605
Benjamin Peterson14339b62009-01-31 16:36:08 +000011606 i = 0;
11607 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011608 while (i < len &&
11609 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011610 i++;
11611 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011612 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011613
Benjamin Peterson14339b62009-01-31 16:36:08 +000011614 j = len;
11615 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011616 do {
11617 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011618 } while (j >= i &&
11619 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011620 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011621 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011622
Victor Stinner7931d9a2011-11-04 00:22:48 +010011623 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011624}
11625
11626PyObject*
11627PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11628{
11629 unsigned char *data;
11630 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011631 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011632
Victor Stinnerde636f32011-10-01 03:55:54 +020011633 if (PyUnicode_READY(self) == -1)
11634 return NULL;
11635
Victor Stinner684d5fd2012-05-03 02:32:34 +020011636 length = PyUnicode_GET_LENGTH(self);
11637 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011638
Victor Stinner684d5fd2012-05-03 02:32:34 +020011639 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011640 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011641
Victor Stinnerde636f32011-10-01 03:55:54 +020011642 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011643 PyErr_SetString(PyExc_IndexError, "string index out of range");
11644 return NULL;
11645 }
Victor Stinner684d5fd2012-05-03 02:32:34 +020011646 if (start >= length || end < start) {
Victor Stinner3a7f79772012-05-03 03:36:40 +020011647 Py_INCREF(unicode_empty);
11648 return unicode_empty;
Victor Stinner684d5fd2012-05-03 02:32:34 +020011649 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020011650
Victor Stinner684d5fd2012-05-03 02:32:34 +020011651 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011652 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011653 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011654 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011655 }
11656 else {
11657 kind = PyUnicode_KIND(self);
11658 data = PyUnicode_1BYTE_DATA(self);
11659 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011660 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011661 length);
11662 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011663}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011664
11665static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011666do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011667{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011668 int kind;
11669 void *data;
11670 Py_ssize_t len, i, j;
11671
11672 if (PyUnicode_READY(self) == -1)
11673 return NULL;
11674
11675 kind = PyUnicode_KIND(self);
11676 data = PyUnicode_DATA(self);
11677 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011678
Benjamin Peterson14339b62009-01-31 16:36:08 +000011679 i = 0;
11680 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011682 i++;
11683 }
11684 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011685
Benjamin Peterson14339b62009-01-31 16:36:08 +000011686 j = len;
11687 if (striptype != LEFTSTRIP) {
11688 do {
11689 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011691 j++;
11692 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011693
Victor Stinner7931d9a2011-11-04 00:22:48 +010011694 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695}
11696
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011697
11698static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011699do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011700{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011701 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011702
Benjamin Peterson14339b62009-01-31 16:36:08 +000011703 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11704 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011705
Benjamin Peterson14339b62009-01-31 16:36:08 +000011706 if (sep != NULL && sep != Py_None) {
11707 if (PyUnicode_Check(sep))
11708 return _PyUnicode_XStrip(self, striptype, sep);
11709 else {
11710 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011711 "%s arg must be None or str",
11712 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011713 return NULL;
11714 }
11715 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011716
Benjamin Peterson14339b62009-01-31 16:36:08 +000011717 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011718}
11719
11720
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011721PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011722 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011723\n\
11724Return a copy of the string S with leading and trailing\n\
11725whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011726If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011727
11728static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011729unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011730{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011731 if (PyTuple_GET_SIZE(args) == 0)
11732 return do_strip(self, BOTHSTRIP); /* Common case */
11733 else
11734 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011735}
11736
11737
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011738PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011739 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011740\n\
11741Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011742If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011743
11744static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011745unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011746{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011747 if (PyTuple_GET_SIZE(args) == 0)
11748 return do_strip(self, LEFTSTRIP); /* Common case */
11749 else
11750 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011751}
11752
11753
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011754PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011755 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011756\n\
11757Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011758If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011759
11760static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011761unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011762{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011763 if (PyTuple_GET_SIZE(args) == 0)
11764 return do_strip(self, RIGHTSTRIP); /* Common case */
11765 else
11766 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011767}
11768
11769
Guido van Rossumd57fd912000-03-10 22:53:23 +000011770static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011771unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011772{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011773 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011774 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011775
Georg Brandl222de0f2009-04-12 12:01:50 +000011776 if (len < 1) {
11777 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011778 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011779 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011780
Victor Stinnerc4b49542011-12-11 22:44:26 +010011781 /* no repeat, return original string */
11782 if (len == 1)
11783 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011784
Benjamin Petersonbac79492012-01-14 13:34:47 -050011785 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011786 return NULL;
11787
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011788 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011789 PyErr_SetString(PyExc_OverflowError,
11790 "repeated string is too long");
11791 return NULL;
11792 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011793 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011794
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011795 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011796 if (!u)
11797 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011798 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011799
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011800 if (PyUnicode_GET_LENGTH(str) == 1) {
11801 const int kind = PyUnicode_KIND(str);
11802 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011803 if (kind == PyUnicode_1BYTE_KIND) {
11804 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011805 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011806 }
11807 else if (kind == PyUnicode_2BYTE_KIND) {
11808 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011809 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011810 ucs2[n] = fill_char;
11811 } else {
11812 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11813 assert(kind == PyUnicode_4BYTE_KIND);
11814 for (n = 0; n < len; ++n)
11815 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011816 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011817 }
11818 else {
11819 /* number of characters copied this far */
11820 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011821 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011822 char *to = (char *) PyUnicode_DATA(u);
11823 Py_MEMCPY(to, PyUnicode_DATA(str),
11824 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011825 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011826 n = (done <= nchars-done) ? done : nchars-done;
11827 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011828 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011829 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011830 }
11831
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011832 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011833 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011834}
11835
Alexander Belopolsky40018472011-02-26 01:02:56 +000011836PyObject *
11837PyUnicode_Replace(PyObject *obj,
11838 PyObject *subobj,
11839 PyObject *replobj,
11840 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011841{
11842 PyObject *self;
11843 PyObject *str1;
11844 PyObject *str2;
11845 PyObject *result;
11846
11847 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011848 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011849 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011850 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011851 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011852 Py_DECREF(self);
11853 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011854 }
11855 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011856 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011857 Py_DECREF(self);
11858 Py_DECREF(str1);
11859 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011861 if (PyUnicode_READY(self) == -1 ||
11862 PyUnicode_READY(str1) == -1 ||
11863 PyUnicode_READY(str2) == -1)
11864 result = NULL;
11865 else
11866 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011867 Py_DECREF(self);
11868 Py_DECREF(str1);
11869 Py_DECREF(str2);
11870 return result;
11871}
11872
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011873PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011874 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011875\n\
11876Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011877old replaced by new. If the optional argument count is\n\
11878given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011879
11880static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011881unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011882{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011883 PyObject *str1;
11884 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011885 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011886 PyObject *result;
11887
Martin v. Löwis18e16552006-02-15 17:27:45 +000011888 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011889 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060011890 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011891 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011892 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011893 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011894 return NULL;
11895 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011896 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011897 Py_DECREF(str1);
11898 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011899 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011900 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
11901 result = NULL;
11902 else
11903 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011904
11905 Py_DECREF(str1);
11906 Py_DECREF(str2);
11907 return result;
11908}
11909
Alexander Belopolsky40018472011-02-26 01:02:56 +000011910static PyObject *
11911unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011912{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011913 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011914 Py_ssize_t isize;
11915 Py_ssize_t osize, squote, dquote, i, o;
11916 Py_UCS4 max, quote;
11917 int ikind, okind;
11918 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011919
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011920 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011921 return NULL;
11922
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011923 isize = PyUnicode_GET_LENGTH(unicode);
11924 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011925
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011926 /* Compute length of output, quote characters, and
11927 maximum character */
11928 osize = 2; /* quotes */
11929 max = 127;
11930 squote = dquote = 0;
11931 ikind = PyUnicode_KIND(unicode);
11932 for (i = 0; i < isize; i++) {
11933 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11934 switch (ch) {
11935 case '\'': squote++; osize++; break;
11936 case '"': dquote++; osize++; break;
11937 case '\\': case '\t': case '\r': case '\n':
11938 osize += 2; break;
11939 default:
11940 /* Fast-path ASCII */
11941 if (ch < ' ' || ch == 0x7f)
11942 osize += 4; /* \xHH */
11943 else if (ch < 0x7f)
11944 osize++;
11945 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11946 osize++;
11947 max = ch > max ? ch : max;
11948 }
11949 else if (ch < 0x100)
11950 osize += 4; /* \xHH */
11951 else if (ch < 0x10000)
11952 osize += 6; /* \uHHHH */
11953 else
11954 osize += 10; /* \uHHHHHHHH */
11955 }
11956 }
11957
11958 quote = '\'';
11959 if (squote) {
11960 if (dquote)
11961 /* Both squote and dquote present. Use squote,
11962 and escape them */
11963 osize += squote;
11964 else
11965 quote = '"';
11966 }
11967
11968 repr = PyUnicode_New(osize, max);
11969 if (repr == NULL)
11970 return NULL;
11971 okind = PyUnicode_KIND(repr);
11972 odata = PyUnicode_DATA(repr);
11973
11974 PyUnicode_WRITE(okind, odata, 0, quote);
11975 PyUnicode_WRITE(okind, odata, osize-1, quote);
11976
11977 for (i = 0, o = 1; i < isize; i++) {
11978 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011979
11980 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011981 if ((ch == quote) || (ch == '\\')) {
11982 PyUnicode_WRITE(okind, odata, o++, '\\');
11983 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011984 continue;
11985 }
11986
Benjamin Peterson29060642009-01-31 22:14:21 +000011987 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011988 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011989 PyUnicode_WRITE(okind, odata, o++, '\\');
11990 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011991 }
11992 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011993 PyUnicode_WRITE(okind, odata, o++, '\\');
11994 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011995 }
11996 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011997 PyUnicode_WRITE(okind, odata, o++, '\\');
11998 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011999 }
12000
12001 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012002 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012003 PyUnicode_WRITE(okind, odata, o++, '\\');
12004 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012005 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12006 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012007 }
12008
Georg Brandl559e5d72008-06-11 18:37:52 +000012009 /* Copy ASCII characters as-is */
12010 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012011 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012012 }
12013
Benjamin Peterson29060642009-01-31 22:14:21 +000012014 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012015 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012016 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012017 (categories Z* and C* except ASCII space)
12018 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012019 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012020 PyUnicode_WRITE(okind, odata, o++, '\\');
Georg Brandl559e5d72008-06-11 18:37:52 +000012021 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012022 if (ch <= 0xff) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012023 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012024 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12025 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012026 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012027 /* Map 16-bit characters to '\uxxxx' */
12028 else if (ch <= 0xffff) {
12029 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012030 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12031 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12032 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12033 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012034 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012035 /* Map 21-bit characters to '\U00xxxxxx' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012036 else {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012037 PyUnicode_WRITE(okind, odata, o++, 'U');
12038 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12039 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12040 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12041 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
Victor Stinnerf5cff562011-10-14 02:13:11 +020012042 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12043 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12044 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12045 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012046 }
12047 }
12048 /* Copy characters as-is */
12049 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012050 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012051 }
12052 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012053 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012054 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012055 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012056 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012057}
12058
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012059PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012060 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012061\n\
12062Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012063such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012064arguments start and end are interpreted as in slice notation.\n\
12065\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012066Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012067
12068static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012069unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012070{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012071 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012072 Py_ssize_t start;
12073 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012074 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012075
Jesus Ceaac451502011-04-20 17:09:23 +020012076 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12077 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012078 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012079
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012080 if (PyUnicode_READY(self) == -1)
12081 return NULL;
12082 if (PyUnicode_READY(substring) == -1)
12083 return NULL;
12084
Victor Stinner7931d9a2011-11-04 00:22:48 +010012085 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012086
12087 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012088
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012089 if (result == -2)
12090 return NULL;
12091
Christian Heimes217cfd12007-12-02 14:31:20 +000012092 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012093}
12094
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012095PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012096 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012097\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012098Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012099
12100static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012101unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012102{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012103 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012104 Py_ssize_t start;
12105 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012106 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012107
Jesus Ceaac451502011-04-20 17:09:23 +020012108 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12109 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012110 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012111
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012112 if (PyUnicode_READY(self) == -1)
12113 return NULL;
12114 if (PyUnicode_READY(substring) == -1)
12115 return NULL;
12116
Victor Stinner7931d9a2011-11-04 00:22:48 +010012117 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012118
12119 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012120
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012121 if (result == -2)
12122 return NULL;
12123
Guido van Rossumd57fd912000-03-10 22:53:23 +000012124 if (result < 0) {
12125 PyErr_SetString(PyExc_ValueError, "substring not found");
12126 return NULL;
12127 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012128
Christian Heimes217cfd12007-12-02 14:31:20 +000012129 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012130}
12131
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012132PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012133 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012134\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012135Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012136done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012137
12138static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012139unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012140{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012141 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012142 Py_UCS4 fillchar = ' ';
12143
Victor Stinnere9a29352011-10-01 02:14:59 +020012144 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012145 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012146
Benjamin Petersonbac79492012-01-14 13:34:47 -050012147 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012148 return NULL;
12149
Victor Stinnerc4b49542011-12-11 22:44:26 +010012150 if (PyUnicode_GET_LENGTH(self) >= width)
12151 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012152
Victor Stinnerc4b49542011-12-11 22:44:26 +010012153 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012154}
12155
Alexander Belopolsky40018472011-02-26 01:02:56 +000012156PyObject *
12157PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012158{
12159 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012160
Guido van Rossumd57fd912000-03-10 22:53:23 +000012161 s = PyUnicode_FromObject(s);
12162 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012163 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012164 if (sep != NULL) {
12165 sep = PyUnicode_FromObject(sep);
12166 if (sep == NULL) {
12167 Py_DECREF(s);
12168 return NULL;
12169 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012170 }
12171
Victor Stinner9310abb2011-10-05 00:59:23 +020012172 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012173
12174 Py_DECREF(s);
12175 Py_XDECREF(sep);
12176 return result;
12177}
12178
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012179PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012180 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012181\n\
12182Return a list of the words in S, using sep as the\n\
12183delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012184splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012185whitespace string is a separator and empty strings are\n\
12186removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012187
12188static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012189unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012190{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012191 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012192 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012193 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012194
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012195 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12196 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012197 return NULL;
12198
12199 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012200 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012201 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012202 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012203 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012204 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012205}
12206
Thomas Wouters477c8d52006-05-27 19:21:47 +000012207PyObject *
12208PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12209{
12210 PyObject* str_obj;
12211 PyObject* sep_obj;
12212 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012213 int kind1, kind2, kind;
12214 void *buf1 = NULL, *buf2 = NULL;
12215 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012216
12217 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012218 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012219 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012220 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012221 if (!sep_obj) {
12222 Py_DECREF(str_obj);
12223 return NULL;
12224 }
12225 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12226 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012227 Py_DECREF(str_obj);
12228 return NULL;
12229 }
12230
Victor Stinner14f8f022011-10-05 20:58:25 +020012231 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012232 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012233 kind = Py_MAX(kind1, kind2);
12234 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012235 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012236 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012237 if (!buf1)
12238 goto onError;
12239 buf2 = PyUnicode_DATA(sep_obj);
12240 if (kind2 != kind)
12241 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12242 if (!buf2)
12243 goto onError;
12244 len1 = PyUnicode_GET_LENGTH(str_obj);
12245 len2 = PyUnicode_GET_LENGTH(sep_obj);
12246
Benjamin Petersonead6b532011-12-20 17:23:42 -060012247 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012248 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012249 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12250 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12251 else
12252 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012253 break;
12254 case PyUnicode_2BYTE_KIND:
12255 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12256 break;
12257 case PyUnicode_4BYTE_KIND:
12258 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12259 break;
12260 default:
12261 assert(0);
12262 out = 0;
12263 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012264
12265 Py_DECREF(sep_obj);
12266 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012267 if (kind1 != kind)
12268 PyMem_Free(buf1);
12269 if (kind2 != kind)
12270 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012271
12272 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012273 onError:
12274 Py_DECREF(sep_obj);
12275 Py_DECREF(str_obj);
12276 if (kind1 != kind && buf1)
12277 PyMem_Free(buf1);
12278 if (kind2 != kind && buf2)
12279 PyMem_Free(buf2);
12280 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012281}
12282
12283
12284PyObject *
12285PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12286{
12287 PyObject* str_obj;
12288 PyObject* sep_obj;
12289 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012290 int kind1, kind2, kind;
12291 void *buf1 = NULL, *buf2 = NULL;
12292 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012293
12294 str_obj = PyUnicode_FromObject(str_in);
12295 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012296 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012297 sep_obj = PyUnicode_FromObject(sep_in);
12298 if (!sep_obj) {
12299 Py_DECREF(str_obj);
12300 return NULL;
12301 }
12302
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012303 kind1 = PyUnicode_KIND(str_in);
12304 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012305 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012306 buf1 = PyUnicode_DATA(str_in);
12307 if (kind1 != kind)
12308 buf1 = _PyUnicode_AsKind(str_in, kind);
12309 if (!buf1)
12310 goto onError;
12311 buf2 = PyUnicode_DATA(sep_obj);
12312 if (kind2 != kind)
12313 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12314 if (!buf2)
12315 goto onError;
12316 len1 = PyUnicode_GET_LENGTH(str_obj);
12317 len2 = PyUnicode_GET_LENGTH(sep_obj);
12318
Benjamin Petersonead6b532011-12-20 17:23:42 -060012319 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012320 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012321 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12322 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12323 else
12324 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012325 break;
12326 case PyUnicode_2BYTE_KIND:
12327 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12328 break;
12329 case PyUnicode_4BYTE_KIND:
12330 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12331 break;
12332 default:
12333 assert(0);
12334 out = 0;
12335 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012336
12337 Py_DECREF(sep_obj);
12338 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012339 if (kind1 != kind)
12340 PyMem_Free(buf1);
12341 if (kind2 != kind)
12342 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012343
12344 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012345 onError:
12346 Py_DECREF(sep_obj);
12347 Py_DECREF(str_obj);
12348 if (kind1 != kind && buf1)
12349 PyMem_Free(buf1);
12350 if (kind2 != kind && buf2)
12351 PyMem_Free(buf2);
12352 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012353}
12354
12355PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012356 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012357\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012358Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012359the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012360found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012361
12362static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012363unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012364{
Victor Stinner9310abb2011-10-05 00:59:23 +020012365 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012366}
12367
12368PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012369 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012370\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012371Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012372the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012373separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012374
12375static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012376unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012377{
Victor Stinner9310abb2011-10-05 00:59:23 +020012378 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012379}
12380
Alexander Belopolsky40018472011-02-26 01:02:56 +000012381PyObject *
12382PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012383{
12384 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012385
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012386 s = PyUnicode_FromObject(s);
12387 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012388 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012389 if (sep != NULL) {
12390 sep = PyUnicode_FromObject(sep);
12391 if (sep == NULL) {
12392 Py_DECREF(s);
12393 return NULL;
12394 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012395 }
12396
Victor Stinner9310abb2011-10-05 00:59:23 +020012397 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012398
12399 Py_DECREF(s);
12400 Py_XDECREF(sep);
12401 return result;
12402}
12403
12404PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012405 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012406\n\
12407Return a list of the words in S, using sep as the\n\
12408delimiter string, starting at the end of the string and\n\
12409working to the front. If maxsplit is given, at most maxsplit\n\
12410splits are done. If sep is not specified, any whitespace string\n\
12411is a separator.");
12412
12413static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012414unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012415{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012416 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012417 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012418 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012419
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012420 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12421 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012422 return NULL;
12423
12424 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012425 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012426 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012427 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012428 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012429 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012430}
12431
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012432PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012433 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012434\n\
12435Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012436Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012437is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012438
12439static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012440unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012441{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012442 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012443 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012444
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012445 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12446 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012447 return NULL;
12448
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012449 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012450}
12451
12452static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012453PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012454{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012455 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012456}
12457
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012458PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012459 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012460\n\
12461Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012462and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012463
12464static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012465unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012466{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012467 if (PyUnicode_READY(self) == -1)
12468 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012469 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012470}
12471
Georg Brandlceee0772007-11-27 23:48:05 +000012472PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012473 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012474\n\
12475Return a translation table usable for str.translate().\n\
12476If there is only one argument, it must be a dictionary mapping Unicode\n\
12477ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012478Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012479If there are two arguments, they must be strings of equal length, and\n\
12480in the resulting dictionary, each character in x will be mapped to the\n\
12481character at the same position in y. If there is a third argument, it\n\
12482must be a string, whose characters will be mapped to None in the result.");
12483
12484static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012485unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012486{
12487 PyObject *x, *y = NULL, *z = NULL;
12488 PyObject *new = NULL, *key, *value;
12489 Py_ssize_t i = 0;
12490 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012491
Georg Brandlceee0772007-11-27 23:48:05 +000012492 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12493 return NULL;
12494 new = PyDict_New();
12495 if (!new)
12496 return NULL;
12497 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012498 int x_kind, y_kind, z_kind;
12499 void *x_data, *y_data, *z_data;
12500
Georg Brandlceee0772007-11-27 23:48:05 +000012501 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012502 if (!PyUnicode_Check(x)) {
12503 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12504 "be a string if there is a second argument");
12505 goto err;
12506 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012507 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012508 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12509 "arguments must have equal length");
12510 goto err;
12511 }
12512 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012513 x_kind = PyUnicode_KIND(x);
12514 y_kind = PyUnicode_KIND(y);
12515 x_data = PyUnicode_DATA(x);
12516 y_data = PyUnicode_DATA(y);
12517 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12518 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012519 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012520 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012521 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012522 if (!value) {
12523 Py_DECREF(key);
12524 goto err;
12525 }
Georg Brandlceee0772007-11-27 23:48:05 +000012526 res = PyDict_SetItem(new, key, value);
12527 Py_DECREF(key);
12528 Py_DECREF(value);
12529 if (res < 0)
12530 goto err;
12531 }
12532 /* create entries for deleting chars in z */
12533 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012534 z_kind = PyUnicode_KIND(z);
12535 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012536 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012537 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012538 if (!key)
12539 goto err;
12540 res = PyDict_SetItem(new, key, Py_None);
12541 Py_DECREF(key);
12542 if (res < 0)
12543 goto err;
12544 }
12545 }
12546 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012547 int kind;
12548 void *data;
12549
Georg Brandlceee0772007-11-27 23:48:05 +000012550 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012551 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012552 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12553 "to maketrans it must be a dict");
12554 goto err;
12555 }
12556 /* copy entries into the new dict, converting string keys to int keys */
12557 while (PyDict_Next(x, &i, &key, &value)) {
12558 if (PyUnicode_Check(key)) {
12559 /* convert string keys to integer keys */
12560 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012561 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012562 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12563 "table must be of length 1");
12564 goto err;
12565 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012566 kind = PyUnicode_KIND(key);
12567 data = PyUnicode_DATA(key);
12568 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012569 if (!newkey)
12570 goto err;
12571 res = PyDict_SetItem(new, newkey, value);
12572 Py_DECREF(newkey);
12573 if (res < 0)
12574 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012575 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012576 /* just keep integer keys */
12577 if (PyDict_SetItem(new, key, value) < 0)
12578 goto err;
12579 } else {
12580 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12581 "be strings or integers");
12582 goto err;
12583 }
12584 }
12585 }
12586 return new;
12587 err:
12588 Py_DECREF(new);
12589 return NULL;
12590}
12591
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012592PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012593 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012594\n\
12595Return a copy of the string S, where all characters have been mapped\n\
12596through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012597Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012598Unmapped characters are left untouched. Characters mapped to None\n\
12599are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012600
12601static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012602unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012603{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012604 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012605}
12606
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012607PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012608 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012609\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012610Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012611
12612static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012613unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012614{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012615 if (PyUnicode_READY(self) == -1)
12616 return NULL;
12617 if (PyUnicode_IS_ASCII(self))
12618 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012619 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012620}
12621
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012622PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012623 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012624\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012625Pad a numeric string S with zeros on the left, to fill a field\n\
12626of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012627
12628static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012629unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012630{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012631 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012632 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012633 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012634 int kind;
12635 void *data;
12636 Py_UCS4 chr;
12637
Martin v. Löwis18e16552006-02-15 17:27:45 +000012638 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012639 return NULL;
12640
Benjamin Petersonbac79492012-01-14 13:34:47 -050012641 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012642 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012643
Victor Stinnerc4b49542011-12-11 22:44:26 +010012644 if (PyUnicode_GET_LENGTH(self) >= width)
12645 return unicode_result_unchanged(self);
12646
12647 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012648
12649 u = pad(self, fill, 0, '0');
12650
Walter Dörwald068325e2002-04-15 13:36:47 +000012651 if (u == NULL)
12652 return NULL;
12653
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012654 kind = PyUnicode_KIND(u);
12655 data = PyUnicode_DATA(u);
12656 chr = PyUnicode_READ(kind, data, fill);
12657
12658 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012659 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012660 PyUnicode_WRITE(kind, data, 0, chr);
12661 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012662 }
12663
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012664 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012665 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012666}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012667
12668#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012669static PyObject *
12670unicode__decimal2ascii(PyObject *self)
12671{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012672 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012673}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012674#endif
12675
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012676PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012677 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012678\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012679Return True if S starts with the specified prefix, False otherwise.\n\
12680With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012681With optional end, stop comparing S at that position.\n\
12682prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012683
12684static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012685unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012686 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012687{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012688 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012689 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012690 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012691 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012692 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012693
Jesus Ceaac451502011-04-20 17:09:23 +020012694 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012695 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012696 if (PyTuple_Check(subobj)) {
12697 Py_ssize_t i;
12698 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012699 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012700 if (substring == NULL)
12701 return NULL;
12702 result = tailmatch(self, substring, start, end, -1);
12703 Py_DECREF(substring);
12704 if (result) {
12705 Py_RETURN_TRUE;
12706 }
12707 }
12708 /* nothing matched */
12709 Py_RETURN_FALSE;
12710 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012711 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012712 if (substring == NULL) {
12713 if (PyErr_ExceptionMatches(PyExc_TypeError))
12714 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12715 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012716 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012717 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012718 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012719 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012720 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012721}
12722
12723
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012724PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012725 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012726\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012727Return True if S ends with the specified suffix, False otherwise.\n\
12728With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012729With optional end, stop comparing S at that position.\n\
12730suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012731
12732static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012733unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012734 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012735{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012736 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012737 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012738 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012739 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012740 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012741
Jesus Ceaac451502011-04-20 17:09:23 +020012742 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012743 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012744 if (PyTuple_Check(subobj)) {
12745 Py_ssize_t i;
12746 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012747 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012748 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012749 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012750 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012751 result = tailmatch(self, substring, start, end, +1);
12752 Py_DECREF(substring);
12753 if (result) {
12754 Py_RETURN_TRUE;
12755 }
12756 }
12757 Py_RETURN_FALSE;
12758 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012759 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012760 if (substring == NULL) {
12761 if (PyErr_ExceptionMatches(PyExc_TypeError))
12762 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12763 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012764 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012765 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012766 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012767 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012768 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012769}
12770
Victor Stinner202fdca2012-05-07 12:47:02 +020012771Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012772_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012773{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012774 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012775 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
12776 writer->data = PyUnicode_DATA(writer->buffer);
12777 writer->kind = PyUnicode_KIND(writer->buffer);
12778}
12779
Victor Stinnerd3f08822012-05-29 12:57:52 +020012780void
12781_PyUnicodeWriter_Init(_PyUnicodeWriter *writer, Py_ssize_t min_length)
Victor Stinner202fdca2012-05-07 12:47:02 +020012782{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012783 memset(writer, 0, sizeof(*writer));
12784#ifdef Py_DEBUG
12785 writer->kind = 5; /* invalid kind */
12786#endif
12787 writer->min_length = Py_MAX(min_length, 100);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012788 writer->overallocate = (min_length > 0);
Victor Stinner202fdca2012-05-07 12:47:02 +020012789}
12790
Victor Stinnerd3f08822012-05-29 12:57:52 +020012791int
12792_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
12793 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020012794{
12795 Py_ssize_t newlen;
12796 PyObject *newbuffer;
12797
Victor Stinnerd3f08822012-05-29 12:57:52 +020012798 assert(length > 0);
12799
Victor Stinner202fdca2012-05-07 12:47:02 +020012800 if (length > PY_SSIZE_T_MAX - writer->pos) {
12801 PyErr_NoMemory();
12802 return -1;
12803 }
12804 newlen = writer->pos + length;
12805
Victor Stinnerd3f08822012-05-29 12:57:52 +020012806 if (writer->buffer == NULL) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012807 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012808 /* overallocate 25% to limit the number of resize */
12809 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12810 newlen += newlen / 4;
12811 if (newlen < writer->min_length)
12812 newlen = writer->min_length;
12813 }
12814 writer->buffer = PyUnicode_New(newlen, maxchar);
12815 if (writer->buffer == NULL)
12816 return -1;
12817 _PyUnicodeWriter_Update(writer);
12818 return 0;
12819 }
Victor Stinner202fdca2012-05-07 12:47:02 +020012820
Victor Stinnerd3f08822012-05-29 12:57:52 +020012821 if (newlen > writer->size) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012822 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012823 /* overallocate 25% to limit the number of resize */
12824 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12825 newlen += newlen / 4;
12826 if (newlen < writer->min_length)
12827 newlen = writer->min_length;
12828 }
12829
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012830 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020012831 /* resize + widen */
12832 newbuffer = PyUnicode_New(newlen, maxchar);
12833 if (newbuffer == NULL)
12834 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012835 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12836 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020012837 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012838 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020012839 }
12840 else {
12841 newbuffer = resize_compact(writer->buffer, newlen);
12842 if (newbuffer == NULL)
12843 return -1;
12844 }
12845 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012846 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012847 }
12848 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012849 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012850 newbuffer = PyUnicode_New(writer->size, maxchar);
12851 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020012852 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012853 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12854 writer->buffer, 0, writer->pos);
12855 Py_DECREF(writer->buffer);
12856 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012857 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012858 }
12859 return 0;
12860}
12861
Victor Stinnerd3f08822012-05-29 12:57:52 +020012862int
12863_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
12864{
12865 Py_UCS4 maxchar;
12866 Py_ssize_t len;
12867
12868 if (PyUnicode_READY(str) == -1)
12869 return -1;
12870 len = PyUnicode_GET_LENGTH(str);
12871 if (len == 0)
12872 return 0;
12873 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
12874 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012875 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012876 Py_INCREF(str);
12877 writer->buffer = str;
12878 _PyUnicodeWriter_Update(writer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012879 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012880 writer->size = 0;
12881 writer->pos += len;
12882 return 0;
12883 }
12884 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
12885 return -1;
12886 }
12887 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
12888 str, 0, len);
12889 writer->pos += len;
12890 return 0;
12891}
12892
12893PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012894_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012895{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012896 if (writer->pos == 0) {
12897 Py_XDECREF(writer->buffer);
12898 Py_INCREF(unicode_empty);
12899 return unicode_empty;
12900 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012901 if (writer->readonly) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012902 assert(PyUnicode_GET_LENGTH(writer->buffer) == writer->pos);
12903 return writer->buffer;
12904 }
12905 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
12906 PyObject *newbuffer;
12907 newbuffer = resize_compact(writer->buffer, writer->pos);
12908 if (newbuffer == NULL) {
12909 Py_DECREF(writer->buffer);
12910 return NULL;
12911 }
12912 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020012913 }
Victor Stinnerf59c28c2012-05-09 03:24:14 +020012914 assert(_PyUnicode_CheckConsistency(writer->buffer, 1));
Victor Stinner202fdca2012-05-07 12:47:02 +020012915 return writer->buffer;
12916}
12917
Victor Stinnerd3f08822012-05-29 12:57:52 +020012918void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012919_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012920{
12921 Py_CLEAR(writer->buffer);
12922}
12923
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012924#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012925
12926PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012927 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012928\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012929Return a formatted version of S, using substitutions from args and kwargs.\n\
12930The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012931
Eric Smith27bbca62010-11-04 17:06:58 +000012932PyDoc_STRVAR(format_map__doc__,
12933 "S.format_map(mapping) -> str\n\
12934\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012935Return a formatted version of S, using substitutions from mapping.\n\
12936The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012937
Eric Smith4a7d76d2008-05-30 18:10:19 +000012938static PyObject *
12939unicode__format__(PyObject* self, PyObject* args)
12940{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012941 PyObject *format_spec;
12942 _PyUnicodeWriter writer;
12943 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012944
12945 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12946 return NULL;
12947
Victor Stinnerd3f08822012-05-29 12:57:52 +020012948 if (PyUnicode_READY(self) == -1)
12949 return NULL;
12950 _PyUnicodeWriter_Init(&writer, 0);
12951 ret = _PyUnicode_FormatAdvancedWriter(&writer,
12952 self, format_spec, 0,
12953 PyUnicode_GET_LENGTH(format_spec));
12954 if (ret == -1) {
12955 _PyUnicodeWriter_Dealloc(&writer);
12956 return NULL;
12957 }
12958 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000012959}
12960
Eric Smith8c663262007-08-25 02:26:07 +000012961PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012962 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012963\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012964Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012965
12966static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012967unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012968{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012969 Py_ssize_t size;
12970
12971 /* If it's a compact object, account for base structure +
12972 character data. */
12973 if (PyUnicode_IS_COMPACT_ASCII(v))
12974 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12975 else if (PyUnicode_IS_COMPACT(v))
12976 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012977 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012978 else {
12979 /* If it is a two-block object, account for base object, and
12980 for character block if present. */
12981 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012982 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012983 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012984 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012985 }
12986 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012987 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012988 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012989 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012990 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012991 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012992
12993 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012994}
12995
12996PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012997 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012998
12999static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013000unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013001{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013002 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013003 if (!copy)
13004 return NULL;
13005 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013006}
13007
Guido van Rossumd57fd912000-03-10 22:53:23 +000013008static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013009 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013010 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013011 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13012 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013013 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13014 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013015 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013016 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13017 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13018 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13019 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13020 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013021 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013022 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13023 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13024 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013025 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013026 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13027 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13028 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013029 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013030 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013031 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013032 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013033 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13034 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13035 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13036 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13037 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13038 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13039 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13040 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13041 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13042 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13043 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13044 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13045 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13046 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013047 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013048 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013049 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013050 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013051 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013052 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013053 {"maketrans", (PyCFunction) unicode_maketrans,
13054 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013055 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013056#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013057 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013058 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013059#endif
13060
Benjamin Peterson14339b62009-01-31 16:36:08 +000013061 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013062 {NULL, NULL}
13063};
13064
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013065static PyObject *
13066unicode_mod(PyObject *v, PyObject *w)
13067{
Brian Curtindfc80e32011-08-10 20:28:54 -050013068 if (!PyUnicode_Check(v))
13069 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013070 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013071}
13072
13073static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013074 0, /*nb_add*/
13075 0, /*nb_subtract*/
13076 0, /*nb_multiply*/
13077 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013078};
13079
Guido van Rossumd57fd912000-03-10 22:53:23 +000013080static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013081 (lenfunc) unicode_length, /* sq_length */
13082 PyUnicode_Concat, /* sq_concat */
13083 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13084 (ssizeargfunc) unicode_getitem, /* sq_item */
13085 0, /* sq_slice */
13086 0, /* sq_ass_item */
13087 0, /* sq_ass_slice */
13088 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013089};
13090
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013091static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013092unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013093{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013094 if (PyUnicode_READY(self) == -1)
13095 return NULL;
13096
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013097 if (PyIndex_Check(item)) {
13098 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013099 if (i == -1 && PyErr_Occurred())
13100 return NULL;
13101 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013102 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013103 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013104 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013105 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013106 PyObject *result;
13107 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013108 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013109 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013110
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013111 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013112 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013113 return NULL;
13114 }
13115
13116 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013117 Py_INCREF(unicode_empty);
13118 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013119 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013120 slicelength == PyUnicode_GET_LENGTH(self)) {
13121 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013122 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013123 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013124 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013125 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013126 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013127 src_kind = PyUnicode_KIND(self);
13128 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013129 if (!PyUnicode_IS_ASCII(self)) {
13130 kind_limit = kind_maxchar_limit(src_kind);
13131 max_char = 0;
13132 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13133 ch = PyUnicode_READ(src_kind, src_data, cur);
13134 if (ch > max_char) {
13135 max_char = ch;
13136 if (max_char >= kind_limit)
13137 break;
13138 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013139 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013140 }
Victor Stinner55c99112011-10-13 01:17:06 +020013141 else
13142 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013143 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013144 if (result == NULL)
13145 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013146 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013147 dest_data = PyUnicode_DATA(result);
13148
13149 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013150 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13151 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013152 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013153 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013154 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013155 } else {
13156 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13157 return NULL;
13158 }
13159}
13160
13161static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013162 (lenfunc)unicode_length, /* mp_length */
13163 (binaryfunc)unicode_subscript, /* mp_subscript */
13164 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013165};
13166
Guido van Rossumd57fd912000-03-10 22:53:23 +000013167
Guido van Rossumd57fd912000-03-10 22:53:23 +000013168/* Helpers for PyUnicode_Format() */
13169
13170static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013171getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013172{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013173 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013174 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013175 (*p_argidx)++;
13176 if (arglen < 0)
13177 return args;
13178 else
13179 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013180 }
13181 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013182 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013183 return NULL;
13184}
13185
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013186/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013187
Victor Stinnerd3f08822012-05-29 12:57:52 +020013188static int
13189formatfloat(PyObject *v, int flags, int prec, int type,
13190 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013191{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013192 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013193 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013194 Py_ssize_t len;
Tim Petersced69f82003-09-16 20:30:58 +000013195
Guido van Rossumd57fd912000-03-10 22:53:23 +000013196 x = PyFloat_AsDouble(v);
13197 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013198 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013199
Guido van Rossumd57fd912000-03-10 22:53:23 +000013200 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013201 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013202
Eric Smith0923d1d2009-04-16 20:16:10 +000013203 p = PyOS_double_to_string(x, type, prec,
13204 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013205 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013206 return -1;
13207 len = strlen(p);
13208 if (writer) {
13209 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13210 return -1;
Victor Stinner184252a2012-06-16 02:57:41 +020013211 unicode_write_cstr(writer->buffer, writer->pos, p, len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013212 writer->pos += len;
13213 }
13214 else
13215 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013216 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013217 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013218}
13219
Victor Stinnerd0880d52012-04-27 23:40:13 +020013220/* formatlong() emulates the format codes d, u, o, x and X, and
13221 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13222 * Python's regular ints.
13223 * Return value: a new PyUnicodeObject*, or NULL if error.
13224 * The output string is of the form
13225 * "-"? ("0x" | "0X")? digit+
13226 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13227 * set in flags. The case of hex digits will be correct,
13228 * There will be at least prec digits, zero-filled on the left if
13229 * necessary to get that many.
13230 * val object to be converted
13231 * flags bitmask of format flags; only F_ALT is looked at
13232 * prec minimum number of digits; 0-fill on left if needed
13233 * type a character in [duoxX]; u acts the same as d
13234 *
13235 * CAUTION: o, x and X conversions on regular ints can never
13236 * produce a '-' sign, but can for Python's unbounded ints.
13237 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013238static PyObject*
13239formatlong(PyObject *val, int flags, int prec, int type)
13240{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013241 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013242 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013243 Py_ssize_t i;
13244 int sign; /* 1 if '-', else 0 */
13245 int len; /* number of characters */
13246 Py_ssize_t llen;
13247 int numdigits; /* len == numnondigits + numdigits */
13248 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013249
Victor Stinnerd0880d52012-04-27 23:40:13 +020013250 /* Avoid exceeding SSIZE_T_MAX */
13251 if (prec > INT_MAX-3) {
13252 PyErr_SetString(PyExc_OverflowError,
13253 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013254 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013255 }
13256
13257 assert(PyLong_Check(val));
13258
13259 switch (type) {
13260 case 'd':
13261 case 'u':
13262 /* Special-case boolean: we want 0/1 */
Victor Stinnerb11d91d2012-04-28 00:25:34 +020013263 if (PyBool_Check(val))
13264 result = PyNumber_ToBase(val, 10);
13265 else
13266 result = Py_TYPE(val)->tp_str(val);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013267 break;
13268 case 'o':
13269 numnondigits = 2;
13270 result = PyNumber_ToBase(val, 8);
13271 break;
13272 case 'x':
13273 case 'X':
13274 numnondigits = 2;
13275 result = PyNumber_ToBase(val, 16);
13276 break;
13277 default:
13278 assert(!"'type' not in [duoxX]");
13279 }
13280 if (!result)
13281 return NULL;
13282
13283 assert(unicode_modifiable(result));
13284 assert(PyUnicode_IS_READY(result));
13285 assert(PyUnicode_IS_ASCII(result));
13286
13287 /* To modify the string in-place, there can only be one reference. */
13288 if (Py_REFCNT(result) != 1) {
13289 PyErr_BadInternalCall();
13290 return NULL;
13291 }
13292 buf = PyUnicode_DATA(result);
13293 llen = PyUnicode_GET_LENGTH(result);
13294 if (llen > INT_MAX) {
13295 PyErr_SetString(PyExc_ValueError,
13296 "string too large in _PyBytes_FormatLong");
13297 return NULL;
13298 }
13299 len = (int)llen;
13300 sign = buf[0] == '-';
13301 numnondigits += sign;
13302 numdigits = len - numnondigits;
13303 assert(numdigits > 0);
13304
13305 /* Get rid of base marker unless F_ALT */
13306 if (((flags & F_ALT) == 0 &&
13307 (type == 'o' || type == 'x' || type == 'X'))) {
13308 assert(buf[sign] == '0');
13309 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13310 buf[sign+1] == 'o');
13311 numnondigits -= 2;
13312 buf += 2;
13313 len -= 2;
13314 if (sign)
13315 buf[0] = '-';
13316 assert(len == numnondigits + numdigits);
13317 assert(numdigits > 0);
13318 }
13319
13320 /* Fill with leading zeroes to meet minimum width. */
13321 if (prec > numdigits) {
13322 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13323 numnondigits + prec);
13324 char *b1;
13325 if (!r1) {
13326 Py_DECREF(result);
13327 return NULL;
13328 }
13329 b1 = PyBytes_AS_STRING(r1);
13330 for (i = 0; i < numnondigits; ++i)
13331 *b1++ = *buf++;
13332 for (i = 0; i < prec - numdigits; i++)
13333 *b1++ = '0';
13334 for (i = 0; i < numdigits; i++)
13335 *b1++ = *buf++;
13336 *b1 = '\0';
13337 Py_DECREF(result);
13338 result = r1;
13339 buf = PyBytes_AS_STRING(result);
13340 len = numnondigits + prec;
13341 }
13342
13343 /* Fix up case for hex conversions. */
13344 if (type == 'X') {
13345 /* Need to convert all lower case letters to upper case.
13346 and need to convert 0x to 0X (and -0x to -0X). */
13347 for (i = 0; i < len; i++)
13348 if (buf[i] >= 'a' && buf[i] <= 'x')
13349 buf[i] -= 'a'-'A';
13350 }
13351 if (!PyUnicode_Check(result) || len != PyUnicode_GET_LENGTH(result)) {
13352 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013353 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013354 Py_DECREF(result);
13355 result = unicode;
13356 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013357 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013358}
13359
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013360static Py_UCS4
13361formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013362{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013363 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013364 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013365 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013366 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013367 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013368 goto onError;
13369 }
13370 else {
13371 /* Integer input truncated to a character */
13372 long x;
13373 x = PyLong_AsLong(v);
13374 if (x == -1 && PyErr_Occurred())
13375 goto onError;
13376
Victor Stinner8faf8212011-12-08 22:14:11 +010013377 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013378 PyErr_SetString(PyExc_OverflowError,
13379 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013380 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013381 }
13382
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013383 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013384 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013385
Benjamin Peterson29060642009-01-31 22:14:21 +000013386 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013387 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013388 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013389 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013390}
13391
Alexander Belopolsky40018472011-02-26 01:02:56 +000013392PyObject *
13393PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013394{
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013395 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013396 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013397 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013398 PyObject *temp = NULL;
13399 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013400 PyObject *uformat;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013401 void *fmt;
13402 enum PyUnicode_Kind kind, fmtkind;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013403 _PyUnicodeWriter writer;
Victor Stinneree4544c2012-05-09 22:24:08 +020013404 Py_ssize_t sublen;
13405 Py_UCS4 maxchar;
Tim Petersced69f82003-09-16 20:30:58 +000013406
Guido van Rossumd57fd912000-03-10 22:53:23 +000013407 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013408 PyErr_BadInternalCall();
13409 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013410 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013411 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013412 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013413 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013414 if (PyUnicode_READY(uformat) == -1)
13415 Py_DECREF(uformat);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013416
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013417 fmt = PyUnicode_DATA(uformat);
13418 fmtkind = PyUnicode_KIND(uformat);
13419 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13420 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013421
Victor Stinnerd3f08822012-05-29 12:57:52 +020013422 _PyUnicodeWriter_Init(&writer, fmtcnt + 100);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013423
Guido van Rossumd57fd912000-03-10 22:53:23 +000013424 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013425 arglen = PyTuple_Size(args);
13426 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013427 }
13428 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013429 arglen = -1;
13430 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013431 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013432 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013433 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013434 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013435
13436 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013437 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013438 Py_ssize_t nonfmtpos;
13439 nonfmtpos = fmtpos++;
13440 while (fmtcnt >= 0 &&
13441 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13442 fmtpos++;
13443 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013444 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013445 if (fmtcnt < 0)
13446 fmtpos--;
Victor Stinneree4544c2012-05-09 22:24:08 +020013447 sublen = fmtpos - nonfmtpos;
13448 maxchar = _PyUnicode_FindMaxChar(uformat,
13449 nonfmtpos, nonfmtpos + sublen);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013450 if (_PyUnicodeWriter_Prepare(&writer, sublen, maxchar) == -1)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013451 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013452
Victor Stinnerd3f08822012-05-29 12:57:52 +020013453 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13454 uformat, nonfmtpos, sublen);
Victor Stinneree4544c2012-05-09 22:24:08 +020013455 writer.pos += sublen;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013456 }
13457 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013458 /* Got a format specifier */
13459 int flags = 0;
13460 Py_ssize_t width = -1;
13461 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013462 Py_UCS4 c = '\0';
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013463 Py_UCS4 fill;
13464 int sign;
13465 Py_UCS4 signchar;
Benjamin Peterson29060642009-01-31 22:14:21 +000013466 int isnumok;
13467 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013468 void *pbuf = NULL;
13469 Py_ssize_t pindex, len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013470 Py_UCS4 bufmaxchar;
13471 Py_ssize_t buflen;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013472
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013473 fmtpos++;
Victor Stinner438106b2012-05-02 00:41:57 +020013474 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13475 if (c == '(') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013476 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013477 Py_ssize_t keylen;
13478 PyObject *key;
13479 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013480
Benjamin Peterson29060642009-01-31 22:14:21 +000013481 if (dict == NULL) {
13482 PyErr_SetString(PyExc_TypeError,
13483 "format requires a mapping");
13484 goto onError;
13485 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013486 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013487 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013488 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013489 /* Skip over balanced parentheses */
13490 while (pcount > 0 && --fmtcnt >= 0) {
Victor Stinnerbff7c962012-05-03 01:44:59 +020013491 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13492 if (c == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013493 --pcount;
Victor Stinnerbff7c962012-05-03 01:44:59 +020013494 else if (c == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013495 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013496 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013497 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013498 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013499 if (fmtcnt < 0 || pcount > 0) {
13500 PyErr_SetString(PyExc_ValueError,
13501 "incomplete format key");
13502 goto onError;
13503 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013504 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013505 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013506 if (key == NULL)
13507 goto onError;
13508 if (args_owned) {
13509 Py_DECREF(args);
13510 args_owned = 0;
13511 }
13512 args = PyObject_GetItem(dict, key);
13513 Py_DECREF(key);
13514 if (args == NULL) {
13515 goto onError;
13516 }
13517 args_owned = 1;
13518 arglen = -1;
13519 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013520 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013521 while (--fmtcnt >= 0) {
Victor Stinner438106b2012-05-02 00:41:57 +020013522 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
13523 switch (c) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013524 case '-': flags |= F_LJUST; continue;
13525 case '+': flags |= F_SIGN; continue;
13526 case ' ': flags |= F_BLANK; continue;
13527 case '#': flags |= F_ALT; continue;
13528 case '0': flags |= F_ZERO; continue;
13529 }
13530 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013531 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013532 if (c == '*') {
13533 v = getnextarg(args, arglen, &argidx);
13534 if (v == NULL)
13535 goto onError;
13536 if (!PyLong_Check(v)) {
13537 PyErr_SetString(PyExc_TypeError,
13538 "* wants int");
13539 goto onError;
13540 }
13541 width = PyLong_AsLong(v);
13542 if (width == -1 && PyErr_Occurred())
13543 goto onError;
13544 if (width < 0) {
13545 flags |= F_LJUST;
13546 width = -width;
13547 }
13548 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013549 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013550 }
13551 else if (c >= '0' && c <= '9') {
13552 width = c - '0';
13553 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013554 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013555 if (c < '0' || c > '9')
13556 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013557 /* Since c is unsigned, the RHS would end up as unsigned,
13558 mixing signed and unsigned comparison. Since c is between
13559 '0' and '9', casting to int is safe. */
13560 if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013561 PyErr_SetString(PyExc_ValueError,
13562 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013563 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013564 }
13565 width = width*10 + (c - '0');
13566 }
13567 }
13568 if (c == '.') {
13569 prec = 0;
13570 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013571 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013572 if (c == '*') {
13573 v = getnextarg(args, arglen, &argidx);
13574 if (v == NULL)
13575 goto onError;
13576 if (!PyLong_Check(v)) {
13577 PyErr_SetString(PyExc_TypeError,
13578 "* wants int");
13579 goto onError;
13580 }
13581 prec = PyLong_AsLong(v);
13582 if (prec == -1 && PyErr_Occurred())
13583 goto onError;
13584 if (prec < 0)
13585 prec = 0;
13586 if (--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 }
13589 else if (c >= '0' && c <= '9') {
13590 prec = c - '0';
13591 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013592 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013593 if (c < '0' || c > '9')
13594 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013595 if (prec > (INT_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013596 PyErr_SetString(PyExc_ValueError,
13597 "prec too big");
13598 goto onError;
13599 }
13600 prec = prec*10 + (c - '0');
13601 }
13602 }
13603 } /* prec */
13604 if (fmtcnt >= 0) {
13605 if (c == 'h' || c == 'l' || c == 'L') {
13606 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013607 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013608 }
13609 }
13610 if (fmtcnt < 0) {
13611 PyErr_SetString(PyExc_ValueError,
13612 "incomplete format");
13613 goto onError;
13614 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013615 if (fmtcnt == 0)
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013616 writer.overallocate = 0;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013617
13618 if (c == '%') {
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013619 if (_PyUnicodeWriter_Prepare(&writer, 1, '%') == -1)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013620 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013621 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '%');
13622 writer.pos += 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013623 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013624 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013625
Victor Stinneraff3cc62012-04-30 05:19:21 +020013626 v = getnextarg(args, arglen, &argidx);
13627 if (v == NULL)
13628 goto onError;
13629
Benjamin Peterson29060642009-01-31 22:14:21 +000013630 sign = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013631 signchar = '\0';
Benjamin Peterson29060642009-01-31 22:14:21 +000013632 fill = ' ';
13633 switch (c) {
13634
Benjamin Peterson29060642009-01-31 22:14:21 +000013635 case 's':
13636 case 'r':
13637 case 'a':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013638 if (PyLong_CheckExact(v) && width == -1 && prec == -1) {
13639 /* Fast path */
13640 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13641 goto onError;
13642 goto nextarg;
13643 }
13644
Victor Stinner808fc0a2010-03-22 12:50:40 +000013645 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013646 temp = v;
13647 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013648 }
13649 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013650 if (c == 's')
13651 temp = PyObject_Str(v);
13652 else if (c == 'r')
13653 temp = PyObject_Repr(v);
13654 else
13655 temp = PyObject_ASCII(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013656 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013657 break;
13658
13659 case 'i':
13660 case 'd':
13661 case 'u':
13662 case 'o':
13663 case 'x':
13664 case 'X':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013665 if (PyLong_CheckExact(v)
13666 && width == -1 && prec == -1
13667 && !(flags & (F_SIGN | F_BLANK)))
13668 {
13669 /* Fast path */
13670 switch(c)
13671 {
13672 case 'd':
13673 case 'i':
13674 case 'u':
13675 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13676 goto onError;
13677 goto nextarg;
13678 case 'x':
13679 if (_PyLong_FormatWriter(&writer, v, 16, flags & F_ALT) == -1)
13680 goto onError;
13681 goto nextarg;
13682 case 'o':
13683 if (_PyLong_FormatWriter(&writer, v, 8, flags & F_ALT) == -1)
13684 goto onError;
13685 goto nextarg;
13686 default:
13687 break;
13688 }
13689 }
13690
Benjamin Peterson29060642009-01-31 22:14:21 +000013691 isnumok = 0;
13692 if (PyNumber_Check(v)) {
13693 PyObject *iobj=NULL;
13694
13695 if (PyLong_Check(v)) {
13696 iobj = v;
13697 Py_INCREF(iobj);
13698 }
13699 else {
13700 iobj = PyNumber_Long(v);
13701 }
13702 if (iobj!=NULL) {
13703 if (PyLong_Check(iobj)) {
13704 isnumok = 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013705 sign = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013706 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013707 Py_DECREF(iobj);
Benjamin Peterson29060642009-01-31 22:14:21 +000013708 }
13709 else {
13710 Py_DECREF(iobj);
13711 }
13712 }
13713 }
13714 if (!isnumok) {
13715 PyErr_Format(PyExc_TypeError,
13716 "%%%c format: a number is required, "
13717 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13718 goto onError;
13719 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013720 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013721 fill = '0';
13722 break;
13723
13724 case 'e':
13725 case 'E':
13726 case 'f':
13727 case 'F':
13728 case 'g':
13729 case 'G':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013730 if (width == -1 && prec == -1
13731 && !(flags & (F_SIGN | F_BLANK)))
13732 {
13733 /* Fast path */
13734 if (formatfloat(v, flags, prec, c, NULL, &writer) == -1)
13735 goto onError;
13736 goto nextarg;
13737 }
13738
Benjamin Peterson29060642009-01-31 22:14:21 +000013739 sign = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013740 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013741 fill = '0';
Victor Stinnerd3f08822012-05-29 12:57:52 +020013742 if (formatfloat(v, flags, prec, c, &temp, NULL) == -1)
13743 temp = NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000013744 break;
13745
13746 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013747 {
13748 Py_UCS4 ch = formatchar(v);
13749 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013750 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013751 if (width == -1 && prec == -1) {
13752 /* Fast path */
13753 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1)
13754 goto onError;
13755 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch);
13756 writer.pos += 1;
13757 goto nextarg;
13758 }
Victor Stinnerb5c3ea32012-05-02 00:29:36 +020013759 temp = PyUnicode_FromOrdinal(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +000013760 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013761 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013762
13763 default:
13764 PyErr_Format(PyExc_ValueError,
13765 "unsupported format character '%c' (0x%x) "
13766 "at index %zd",
13767 (31<=c && c<=126) ? (char)c : '?',
13768 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013769 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013770 goto onError;
13771 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013772 if (temp == NULL)
13773 goto onError;
13774 assert (PyUnicode_Check(temp));
Victor Stinnerd3f08822012-05-29 12:57:52 +020013775
13776 if (width == -1 && prec == -1
13777 && !(flags & (F_SIGN | F_BLANK)))
13778 {
13779 /* Fast path */
13780 if (_PyUnicodeWriter_WriteStr(&writer, temp) == -1)
13781 goto onError;
13782 goto nextarg;
13783 }
13784
Victor Stinneraff3cc62012-04-30 05:19:21 +020013785 if (PyUnicode_READY(temp) == -1) {
13786 Py_CLEAR(temp);
13787 goto onError;
13788 }
13789 kind = PyUnicode_KIND(temp);
13790 pbuf = PyUnicode_DATA(temp);
13791 len = PyUnicode_GET_LENGTH(temp);
13792
13793 if (c == 's' || c == 'r' || c == 'a') {
13794 if (prec >= 0 && len > prec)
13795 len = prec;
13796 }
13797
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013798 /* pbuf is initialized here. */
13799 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013800 if (sign) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013801 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
13802 if (ch == '-' || ch == '+') {
13803 signchar = ch;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013804 len--;
13805 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013806 }
13807 else if (flags & F_SIGN)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013808 signchar = '+';
Benjamin Peterson29060642009-01-31 22:14:21 +000013809 else if (flags & F_BLANK)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013810 signchar = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +000013811 else
13812 sign = 0;
13813 }
13814 if (width < len)
13815 width = len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013816
13817 /* Compute the length and maximum character of the
13818 written characters */
13819 bufmaxchar = 127;
13820 if (!(flags & F_LJUST)) {
13821 if (sign) {
13822 if ((width-1) > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013823 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013824 }
13825 else {
13826 if (width > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013827 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013828 }
13829 }
13830 maxchar = _PyUnicode_FindMaxChar(temp, 0, pindex+len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013831 bufmaxchar = MAX_MAXCHAR(bufmaxchar, maxchar);
Victor Stinneree4544c2012-05-09 22:24:08 +020013832
13833 buflen = width;
13834 if (sign && len == width)
13835 buflen++;
13836
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013837 if (_PyUnicodeWriter_Prepare(&writer, buflen, bufmaxchar) == -1)
Victor Stinneree4544c2012-05-09 22:24:08 +020013838 goto onError;
13839
13840 /* Write characters */
Benjamin Peterson29060642009-01-31 22:14:21 +000013841 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013842 if (fill != ' ') {
Victor Stinneree4544c2012-05-09 22:24:08 +020013843 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13844 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013845 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013846 if (width > len)
13847 width--;
13848 }
13849 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013850 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013851 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013852 if (fill != ' ') {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013853 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13854 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13855 writer.pos += 2;
13856 pindex += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +000013857 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013858 width -= 2;
13859 if (width < 0)
13860 width = 0;
13861 len -= 2;
13862 }
13863 if (width > len && !(flags & F_LJUST)) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013864 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013865 FILL(writer.kind, writer.data, fill, writer.pos, sublen);
13866 writer.pos += sublen;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013867 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013868 }
13869 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013870 if (sign) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013871 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13872 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013873 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013874 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013875 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13876 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013877 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13878 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13879 writer.pos += 2;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013880 pindex += 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013881 }
13882 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013883
Victor Stinnerc9d369f2012-06-16 02:22:37 +020013884 if (len) {
13885 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13886 temp, pindex, len);
13887 writer.pos += len;
13888 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013889 if (width > len) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013890 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013891 FILL(writer.kind, writer.data, ' ', writer.pos, sublen);
13892 writer.pos += sublen;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013893 }
Victor Stinneree4544c2012-05-09 22:24:08 +020013894
Victor Stinnerd3f08822012-05-29 12:57:52 +020013895nextarg:
Benjamin Peterson29060642009-01-31 22:14:21 +000013896 if (dict && (argidx < arglen) && c != '%') {
13897 PyErr_SetString(PyExc_TypeError,
13898 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013899 goto onError;
13900 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013901 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013902 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013903 } /* until end */
13904 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013905 PyErr_SetString(PyExc_TypeError,
13906 "not all arguments converted during string formatting");
13907 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013908 }
13909
13910 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013911 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013912 }
13913 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013914 Py_XDECREF(temp);
13915 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013916 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013917
Benjamin Peterson29060642009-01-31 22:14:21 +000013918 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013919 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013920 Py_XDECREF(temp);
13921 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013922 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013923 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013924 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013925 }
13926 return NULL;
13927}
13928
Jeremy Hylton938ace62002-07-17 16:30:39 +000013929static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013930unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13931
Tim Peters6d6c1a32001-08-02 04:15:00 +000013932static PyObject *
13933unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13934{
Benjamin Peterson29060642009-01-31 22:14:21 +000013935 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013936 static char *kwlist[] = {"object", "encoding", "errors", 0};
13937 char *encoding = NULL;
13938 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013939
Benjamin Peterson14339b62009-01-31 16:36:08 +000013940 if (type != &PyUnicode_Type)
13941 return unicode_subtype_new(type, args, kwds);
13942 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013943 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013944 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013945 if (x == NULL) {
13946 Py_INCREF(unicode_empty);
13947 return unicode_empty;
13948 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013949 if (encoding == NULL && errors == NULL)
13950 return PyObject_Str(x);
13951 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013952 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013953}
13954
Guido van Rossume023fe02001-08-30 03:12:59 +000013955static PyObject *
13956unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13957{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013958 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013959 Py_ssize_t length, char_size;
13960 int share_wstr, share_utf8;
13961 unsigned int kind;
13962 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013963
Benjamin Peterson14339b62009-01-31 16:36:08 +000013964 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013965
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013966 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013967 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013968 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013969 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050013970 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013971 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013972 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013973 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013974
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013975 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013976 if (self == NULL) {
13977 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013978 return NULL;
13979 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013980 kind = PyUnicode_KIND(unicode);
13981 length = PyUnicode_GET_LENGTH(unicode);
13982
13983 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013984#ifdef Py_DEBUG
13985 _PyUnicode_HASH(self) = -1;
13986#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013987 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013988#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013989 _PyUnicode_STATE(self).interned = 0;
13990 _PyUnicode_STATE(self).kind = kind;
13991 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013992 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013993 _PyUnicode_STATE(self).ready = 1;
13994 _PyUnicode_WSTR(self) = NULL;
13995 _PyUnicode_UTF8_LENGTH(self) = 0;
13996 _PyUnicode_UTF8(self) = NULL;
13997 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013998 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013999
14000 share_utf8 = 0;
14001 share_wstr = 0;
14002 if (kind == PyUnicode_1BYTE_KIND) {
14003 char_size = 1;
14004 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14005 share_utf8 = 1;
14006 }
14007 else if (kind == PyUnicode_2BYTE_KIND) {
14008 char_size = 2;
14009 if (sizeof(wchar_t) == 2)
14010 share_wstr = 1;
14011 }
14012 else {
14013 assert(kind == PyUnicode_4BYTE_KIND);
14014 char_size = 4;
14015 if (sizeof(wchar_t) == 4)
14016 share_wstr = 1;
14017 }
14018
14019 /* Ensure we won't overflow the length. */
14020 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14021 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014022 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014023 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014024 data = PyObject_MALLOC((length + 1) * char_size);
14025 if (data == NULL) {
14026 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014027 goto onError;
14028 }
14029
Victor Stinnerc3c74152011-10-02 20:39:55 +020014030 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014031 if (share_utf8) {
14032 _PyUnicode_UTF8_LENGTH(self) = length;
14033 _PyUnicode_UTF8(self) = data;
14034 }
14035 if (share_wstr) {
14036 _PyUnicode_WSTR_LENGTH(self) = length;
14037 _PyUnicode_WSTR(self) = (wchar_t *)data;
14038 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014039
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014040 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014041 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014042 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014043#ifdef Py_DEBUG
14044 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14045#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014046 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014047 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014048
14049onError:
14050 Py_DECREF(unicode);
14051 Py_DECREF(self);
14052 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014053}
14054
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014055PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000014056 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014057\n\
Collin Winterd474ce82007-08-07 19:42:11 +000014058Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000014059encoding defaults to the current default string encoding.\n\
14060errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014061
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014062static PyObject *unicode_iter(PyObject *seq);
14063
Guido van Rossumd57fd912000-03-10 22:53:23 +000014064PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014065 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014066 "str", /* tp_name */
14067 sizeof(PyUnicodeObject), /* tp_size */
14068 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014069 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014070 (destructor)unicode_dealloc, /* tp_dealloc */
14071 0, /* tp_print */
14072 0, /* tp_getattr */
14073 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014074 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014075 unicode_repr, /* tp_repr */
14076 &unicode_as_number, /* tp_as_number */
14077 &unicode_as_sequence, /* tp_as_sequence */
14078 &unicode_as_mapping, /* tp_as_mapping */
14079 (hashfunc) unicode_hash, /* tp_hash*/
14080 0, /* tp_call*/
14081 (reprfunc) unicode_str, /* tp_str */
14082 PyObject_GenericGetAttr, /* tp_getattro */
14083 0, /* tp_setattro */
14084 0, /* tp_as_buffer */
14085 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014086 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014087 unicode_doc, /* tp_doc */
14088 0, /* tp_traverse */
14089 0, /* tp_clear */
14090 PyUnicode_RichCompare, /* tp_richcompare */
14091 0, /* tp_weaklistoffset */
14092 unicode_iter, /* tp_iter */
14093 0, /* tp_iternext */
14094 unicode_methods, /* tp_methods */
14095 0, /* tp_members */
14096 0, /* tp_getset */
14097 &PyBaseObject_Type, /* tp_base */
14098 0, /* tp_dict */
14099 0, /* tp_descr_get */
14100 0, /* tp_descr_set */
14101 0, /* tp_dictoffset */
14102 0, /* tp_init */
14103 0, /* tp_alloc */
14104 unicode_new, /* tp_new */
14105 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014106};
14107
14108/* Initialize the Unicode implementation */
14109
Victor Stinner3a50e702011-10-18 21:21:00 +020014110int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014111{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014112 int i;
14113
Thomas Wouters477c8d52006-05-27 19:21:47 +000014114 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014115 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014116 0x000A, /* LINE FEED */
14117 0x000D, /* CARRIAGE RETURN */
14118 0x001C, /* FILE SEPARATOR */
14119 0x001D, /* GROUP SEPARATOR */
14120 0x001E, /* RECORD SEPARATOR */
14121 0x0085, /* NEXT LINE */
14122 0x2028, /* LINE SEPARATOR */
14123 0x2029, /* PARAGRAPH SEPARATOR */
14124 };
14125
Fred Drakee4315f52000-05-09 19:53:39 +000014126 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014127 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014128 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014129 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014130 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014131
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014132 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014133 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014134 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014135 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014136
14137 /* initialize the linebreak bloom filter */
14138 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014139 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014140 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014141
14142 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014143
14144#ifdef HAVE_MBCS
14145 winver.dwOSVersionInfoSize = sizeof(winver);
14146 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14147 PyErr_SetFromWindowsErr(0);
14148 return -1;
14149 }
14150#endif
14151 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014152}
14153
14154/* Finalize the Unicode implementation */
14155
Christian Heimesa156e092008-02-16 07:38:31 +000014156int
14157PyUnicode_ClearFreeList(void)
14158{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014159 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014160}
14161
Guido van Rossumd57fd912000-03-10 22:53:23 +000014162void
Thomas Wouters78890102000-07-22 19:25:51 +000014163_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014164{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014165 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014166
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014167 Py_XDECREF(unicode_empty);
14168 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014169
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014170 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014171 if (unicode_latin1[i]) {
14172 Py_DECREF(unicode_latin1[i]);
14173 unicode_latin1[i] = NULL;
14174 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014175 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014176 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014177 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014178}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014179
Walter Dörwald16807132007-05-25 13:52:07 +000014180void
14181PyUnicode_InternInPlace(PyObject **p)
14182{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014183 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014184 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014185#ifdef Py_DEBUG
14186 assert(s != NULL);
14187 assert(_PyUnicode_CHECK(s));
14188#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014189 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014190 return;
14191#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014192 /* If it's a subclass, we don't really know what putting
14193 it in the interned dict might do. */
14194 if (!PyUnicode_CheckExact(s))
14195 return;
14196 if (PyUnicode_CHECK_INTERNED(s))
14197 return;
14198 if (interned == NULL) {
14199 interned = PyDict_New();
14200 if (interned == NULL) {
14201 PyErr_Clear(); /* Don't leave an exception */
14202 return;
14203 }
14204 }
14205 /* It might be that the GetItem call fails even
14206 though the key is present in the dictionary,
14207 namely when this happens during a stack overflow. */
14208 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014209 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014210 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014211
Benjamin Peterson29060642009-01-31 22:14:21 +000014212 if (t) {
14213 Py_INCREF(t);
14214 Py_DECREF(*p);
14215 *p = t;
14216 return;
14217 }
Walter Dörwald16807132007-05-25 13:52:07 +000014218
Benjamin Peterson14339b62009-01-31 16:36:08 +000014219 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014220 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014221 PyErr_Clear();
14222 PyThreadState_GET()->recursion_critical = 0;
14223 return;
14224 }
14225 PyThreadState_GET()->recursion_critical = 0;
14226 /* The two references in interned are not counted by refcnt.
14227 The deallocator will take care of this */
14228 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014229 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014230}
14231
14232void
14233PyUnicode_InternImmortal(PyObject **p)
14234{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014235 PyUnicode_InternInPlace(p);
14236 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014237 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014238 Py_INCREF(*p);
14239 }
Walter Dörwald16807132007-05-25 13:52:07 +000014240}
14241
14242PyObject *
14243PyUnicode_InternFromString(const char *cp)
14244{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014245 PyObject *s = PyUnicode_FromString(cp);
14246 if (s == NULL)
14247 return NULL;
14248 PyUnicode_InternInPlace(&s);
14249 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014250}
14251
Alexander Belopolsky40018472011-02-26 01:02:56 +000014252void
14253_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014254{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014255 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014256 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014257 Py_ssize_t i, n;
14258 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014259
Benjamin Peterson14339b62009-01-31 16:36:08 +000014260 if (interned == NULL || !PyDict_Check(interned))
14261 return;
14262 keys = PyDict_Keys(interned);
14263 if (keys == NULL || !PyList_Check(keys)) {
14264 PyErr_Clear();
14265 return;
14266 }
Walter Dörwald16807132007-05-25 13:52:07 +000014267
Benjamin Peterson14339b62009-01-31 16:36:08 +000014268 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14269 detector, interned unicode strings are not forcibly deallocated;
14270 rather, we give them their stolen references back, and then clear
14271 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014272
Benjamin Peterson14339b62009-01-31 16:36:08 +000014273 n = PyList_GET_SIZE(keys);
14274 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014275 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014276 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014277 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014278 if (PyUnicode_READY(s) == -1) {
14279 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014280 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014281 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014282 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014283 case SSTATE_NOT_INTERNED:
14284 /* XXX Shouldn't happen */
14285 break;
14286 case SSTATE_INTERNED_IMMORTAL:
14287 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014288 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014289 break;
14290 case SSTATE_INTERNED_MORTAL:
14291 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014292 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014293 break;
14294 default:
14295 Py_FatalError("Inconsistent interned string state.");
14296 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014297 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014298 }
14299 fprintf(stderr, "total size of all interned strings: "
14300 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14301 "mortal/immortal\n", mortal_size, immortal_size);
14302 Py_DECREF(keys);
14303 PyDict_Clear(interned);
14304 Py_DECREF(interned);
14305 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014306}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014307
14308
14309/********************* Unicode Iterator **************************/
14310
14311typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014312 PyObject_HEAD
14313 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014314 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014315} unicodeiterobject;
14316
14317static void
14318unicodeiter_dealloc(unicodeiterobject *it)
14319{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014320 _PyObject_GC_UNTRACK(it);
14321 Py_XDECREF(it->it_seq);
14322 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014323}
14324
14325static int
14326unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14327{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014328 Py_VISIT(it->it_seq);
14329 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014330}
14331
14332static PyObject *
14333unicodeiter_next(unicodeiterobject *it)
14334{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014335 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014336
Benjamin Peterson14339b62009-01-31 16:36:08 +000014337 assert(it != NULL);
14338 seq = it->it_seq;
14339 if (seq == NULL)
14340 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014341 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014342
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014343 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14344 int kind = PyUnicode_KIND(seq);
14345 void *data = PyUnicode_DATA(seq);
14346 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14347 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014348 if (item != NULL)
14349 ++it->it_index;
14350 return item;
14351 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014352
Benjamin Peterson14339b62009-01-31 16:36:08 +000014353 Py_DECREF(seq);
14354 it->it_seq = NULL;
14355 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014356}
14357
14358static PyObject *
14359unicodeiter_len(unicodeiterobject *it)
14360{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014361 Py_ssize_t len = 0;
14362 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014363 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014364 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014365}
14366
14367PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14368
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014369static PyObject *
14370unicodeiter_reduce(unicodeiterobject *it)
14371{
14372 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014373 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014374 it->it_seq, it->it_index);
14375 } else {
14376 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14377 if (u == NULL)
14378 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014379 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014380 }
14381}
14382
14383PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14384
14385static PyObject *
14386unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14387{
14388 Py_ssize_t index = PyLong_AsSsize_t(state);
14389 if (index == -1 && PyErr_Occurred())
14390 return NULL;
14391 if (index < 0)
14392 index = 0;
14393 it->it_index = index;
14394 Py_RETURN_NONE;
14395}
14396
14397PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14398
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014399static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014400 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014401 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014402 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14403 reduce_doc},
14404 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14405 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014406 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014407};
14408
14409PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014410 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14411 "str_iterator", /* tp_name */
14412 sizeof(unicodeiterobject), /* tp_basicsize */
14413 0, /* tp_itemsize */
14414 /* methods */
14415 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14416 0, /* tp_print */
14417 0, /* tp_getattr */
14418 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014419 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014420 0, /* tp_repr */
14421 0, /* tp_as_number */
14422 0, /* tp_as_sequence */
14423 0, /* tp_as_mapping */
14424 0, /* tp_hash */
14425 0, /* tp_call */
14426 0, /* tp_str */
14427 PyObject_GenericGetAttr, /* tp_getattro */
14428 0, /* tp_setattro */
14429 0, /* tp_as_buffer */
14430 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14431 0, /* tp_doc */
14432 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14433 0, /* tp_clear */
14434 0, /* tp_richcompare */
14435 0, /* tp_weaklistoffset */
14436 PyObject_SelfIter, /* tp_iter */
14437 (iternextfunc)unicodeiter_next, /* tp_iternext */
14438 unicodeiter_methods, /* tp_methods */
14439 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014440};
14441
14442static PyObject *
14443unicode_iter(PyObject *seq)
14444{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014445 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014446
Benjamin Peterson14339b62009-01-31 16:36:08 +000014447 if (!PyUnicode_Check(seq)) {
14448 PyErr_BadInternalCall();
14449 return NULL;
14450 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014451 if (PyUnicode_READY(seq) == -1)
14452 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014453 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14454 if (it == NULL)
14455 return NULL;
14456 it->it_index = 0;
14457 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014458 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014459 _PyObject_GC_TRACK(it);
14460 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014461}
14462
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014463
14464size_t
14465Py_UNICODE_strlen(const Py_UNICODE *u)
14466{
14467 int res = 0;
14468 while(*u++)
14469 res++;
14470 return res;
14471}
14472
14473Py_UNICODE*
14474Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14475{
14476 Py_UNICODE *u = s1;
14477 while ((*u++ = *s2++));
14478 return s1;
14479}
14480
14481Py_UNICODE*
14482Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14483{
14484 Py_UNICODE *u = s1;
14485 while ((*u++ = *s2++))
14486 if (n-- == 0)
14487 break;
14488 return s1;
14489}
14490
14491Py_UNICODE*
14492Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14493{
14494 Py_UNICODE *u1 = s1;
14495 u1 += Py_UNICODE_strlen(u1);
14496 Py_UNICODE_strcpy(u1, s2);
14497 return s1;
14498}
14499
14500int
14501Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14502{
14503 while (*s1 && *s2 && *s1 == *s2)
14504 s1++, s2++;
14505 if (*s1 && *s2)
14506 return (*s1 < *s2) ? -1 : +1;
14507 if (*s1)
14508 return 1;
14509 if (*s2)
14510 return -1;
14511 return 0;
14512}
14513
14514int
14515Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14516{
14517 register Py_UNICODE u1, u2;
14518 for (; n != 0; n--) {
14519 u1 = *s1;
14520 u2 = *s2;
14521 if (u1 != u2)
14522 return (u1 < u2) ? -1 : +1;
14523 if (u1 == '\0')
14524 return 0;
14525 s1++;
14526 s2++;
14527 }
14528 return 0;
14529}
14530
14531Py_UNICODE*
14532Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14533{
14534 const Py_UNICODE *p;
14535 for (p = s; *p; p++)
14536 if (*p == c)
14537 return (Py_UNICODE*)p;
14538 return NULL;
14539}
14540
14541Py_UNICODE*
14542Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14543{
14544 const Py_UNICODE *p;
14545 p = s + Py_UNICODE_strlen(s);
14546 while (p != s) {
14547 p--;
14548 if (*p == c)
14549 return (Py_UNICODE*)p;
14550 }
14551 return NULL;
14552}
Victor Stinner331ea922010-08-10 16:37:20 +000014553
Victor Stinner71133ff2010-09-01 23:43:53 +000014554Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014555PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014556{
Victor Stinner577db2c2011-10-11 22:12:48 +020014557 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014558 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014559
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014560 if (!PyUnicode_Check(unicode)) {
14561 PyErr_BadArgument();
14562 return NULL;
14563 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014564 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014565 if (u == NULL)
14566 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014567 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014568 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014569 PyErr_NoMemory();
14570 return NULL;
14571 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014572 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014573 size *= sizeof(Py_UNICODE);
14574 copy = PyMem_Malloc(size);
14575 if (copy == NULL) {
14576 PyErr_NoMemory();
14577 return NULL;
14578 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014579 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014580 return copy;
14581}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014582
Georg Brandl66c221e2010-10-14 07:04:07 +000014583/* A _string module, to export formatter_parser and formatter_field_name_split
14584 to the string.Formatter class implemented in Python. */
14585
14586static PyMethodDef _string_methods[] = {
14587 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14588 METH_O, PyDoc_STR("split the argument as a field name")},
14589 {"formatter_parser", (PyCFunction) formatter_parser,
14590 METH_O, PyDoc_STR("parse the argument as a format string")},
14591 {NULL, NULL}
14592};
14593
14594static struct PyModuleDef _string_module = {
14595 PyModuleDef_HEAD_INIT,
14596 "_string",
14597 PyDoc_STR("string helper module"),
14598 0,
14599 _string_methods,
14600 NULL,
14601 NULL,
14602 NULL,
14603 NULL
14604};
14605
14606PyMODINIT_FUNC
14607PyInit__string(void)
14608{
14609 return PyModule_Create(&_string_module);
14610}
14611
14612
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014613#ifdef __cplusplus
14614}
14615#endif