blob: cf9aec2b1f29314ae3d6d77b1f085b4412828f19 [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 Stinner5a706cf2011-10-02 00:36:53 +02003998 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003999 PyErr_BadArgument();
4000 return -1;
4001 }
4002
4003 return PyUnicode_GET_LENGTH(unicode);
4004}
4005
4006Py_UCS4
4007PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4008{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004009 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4010 PyErr_BadArgument();
4011 return (Py_UCS4)-1;
4012 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004013 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004014 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004015 return (Py_UCS4)-1;
4016 }
4017 return PyUnicode_READ_CHAR(unicode, index);
4018}
4019
4020int
4021PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4022{
4023 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004024 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004025 return -1;
4026 }
Victor Stinner488fa492011-12-12 00:01:39 +01004027 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004028 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004029 PyErr_SetString(PyExc_IndexError, "string index out of range");
4030 return -1;
4031 }
Victor Stinner488fa492011-12-12 00:01:39 +01004032 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004033 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004034 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4035 PyErr_SetString(PyExc_ValueError, "character out of range");
4036 return -1;
4037 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004038 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4039 index, ch);
4040 return 0;
4041}
4042
Alexander Belopolsky40018472011-02-26 01:02:56 +00004043const char *
4044PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004045{
Victor Stinner42cb4622010-09-01 19:39:01 +00004046 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004047}
4048
Victor Stinner554f3f02010-06-16 23:33:54 +00004049/* create or adjust a UnicodeDecodeError */
4050static void
4051make_decode_exception(PyObject **exceptionObject,
4052 const char *encoding,
4053 const char *input, Py_ssize_t length,
4054 Py_ssize_t startpos, Py_ssize_t endpos,
4055 const char *reason)
4056{
4057 if (*exceptionObject == NULL) {
4058 *exceptionObject = PyUnicodeDecodeError_Create(
4059 encoding, input, length, startpos, endpos, reason);
4060 }
4061 else {
4062 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4063 goto onError;
4064 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4065 goto onError;
4066 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4067 goto onError;
4068 }
4069 return;
4070
4071onError:
4072 Py_DECREF(*exceptionObject);
4073 *exceptionObject = NULL;
4074}
4075
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004076/* error handling callback helper:
4077 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004078 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004079 and adjust various state variables.
4080 return 0 on success, -1 on error
4081*/
4082
Alexander Belopolsky40018472011-02-26 01:02:56 +00004083static int
4084unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004085 const char *encoding, const char *reason,
4086 const char **input, const char **inend, Py_ssize_t *startinpos,
4087 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004088 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004089{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004090 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004091
4092 PyObject *restuple = NULL;
4093 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004094 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004095 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004096 Py_ssize_t requiredsize;
4097 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004098 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004099 int res = -1;
4100
Victor Stinner596a6c42011-11-09 00:02:18 +01004101 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4102 outsize = PyUnicode_GET_LENGTH(*output);
4103 else
4104 outsize = _PyUnicode_WSTR_LENGTH(*output);
4105
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004106 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004107 *errorHandler = PyCodec_LookupError(errors);
4108 if (*errorHandler == NULL)
4109 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004110 }
4111
Victor Stinner554f3f02010-06-16 23:33:54 +00004112 make_decode_exception(exceptionObject,
4113 encoding,
4114 *input, *inend - *input,
4115 *startinpos, *endinpos,
4116 reason);
4117 if (*exceptionObject == NULL)
4118 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004119
4120 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4121 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004122 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004123 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004124 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004125 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004126 }
4127 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004128 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004129 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004130 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004131
4132 /* Copy back the bytes variables, which might have been modified by the
4133 callback */
4134 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4135 if (!inputobj)
4136 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004137 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004138 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004139 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004140 *input = PyBytes_AS_STRING(inputobj);
4141 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004142 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004143 /* we can DECREF safely, as the exception has another reference,
4144 so the object won't go away. */
4145 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004146
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004147 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004148 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004149 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004150 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4151 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004152 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004153
Victor Stinner596a6c42011-11-09 00:02:18 +01004154 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4155 /* need more space? (at least enough for what we
4156 have+the replacement+the rest of the string (starting
4157 at the new input position), so we won't have to check space
4158 when there are no errors in the rest of the string) */
4159 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4160 requiredsize = *outpos + replen + insize-newpos;
4161 if (requiredsize > outsize) {
4162 if (requiredsize<2*outsize)
4163 requiredsize = 2*outsize;
4164 if (unicode_resize(output, requiredsize) < 0)
4165 goto onError;
4166 }
Victor Stinner1b487b42012-05-03 12:29:04 +02004167 if (unicode_widen(output, *outpos,
4168 PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004169 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004170 _PyUnicode_FastCopyCharacters(*output, *outpos, repunicode, 0, replen);
Victor Stinner596a6c42011-11-09 00:02:18 +01004171 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004172 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004173 else {
4174 wchar_t *repwstr;
4175 Py_ssize_t repwlen;
4176 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4177 if (repwstr == NULL)
4178 goto onError;
4179 /* need more space? (at least enough for what we
4180 have+the replacement+the rest of the string (starting
4181 at the new input position), so we won't have to check space
4182 when there are no errors in the rest of the string) */
4183 requiredsize = *outpos + repwlen + insize-newpos;
4184 if (requiredsize > outsize) {
4185 if (requiredsize < 2*outsize)
4186 requiredsize = 2*outsize;
4187 if (unicode_resize(output, requiredsize) < 0)
4188 goto onError;
4189 }
4190 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4191 *outpos += repwlen;
4192 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004193 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004194 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004195
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004196 /* we made it! */
4197 res = 0;
4198
Benjamin Peterson29060642009-01-31 22:14:21 +00004199 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004200 Py_XDECREF(restuple);
4201 return res;
4202}
4203
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004204/* --- UTF-7 Codec -------------------------------------------------------- */
4205
Antoine Pitrou244651a2009-05-04 18:56:13 +00004206/* See RFC2152 for details. We encode conservatively and decode liberally. */
4207
4208/* Three simple macros defining base-64. */
4209
4210/* Is c a base-64 character? */
4211
4212#define IS_BASE64(c) \
4213 (((c) >= 'A' && (c) <= 'Z') || \
4214 ((c) >= 'a' && (c) <= 'z') || \
4215 ((c) >= '0' && (c) <= '9') || \
4216 (c) == '+' || (c) == '/')
4217
4218/* given that c is a base-64 character, what is its base-64 value? */
4219
4220#define FROM_BASE64(c) \
4221 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4222 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4223 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4224 (c) == '+' ? 62 : 63)
4225
4226/* What is the base-64 character of the bottom 6 bits of n? */
4227
4228#define TO_BASE64(n) \
4229 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4230
4231/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4232 * decoded as itself. We are permissive on decoding; the only ASCII
4233 * byte not decoding to itself is the + which begins a base64
4234 * string. */
4235
4236#define DECODE_DIRECT(c) \
4237 ((c) <= 127 && (c) != '+')
4238
4239/* The UTF-7 encoder treats ASCII characters differently according to
4240 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4241 * the above). See RFC2152. This array identifies these different
4242 * sets:
4243 * 0 : "Set D"
4244 * alphanumeric and '(),-./:?
4245 * 1 : "Set O"
4246 * !"#$%&*;<=>@[]^_`{|}
4247 * 2 : "whitespace"
4248 * ht nl cr sp
4249 * 3 : special (must be base64 encoded)
4250 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4251 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004252
Tim Petersced69f82003-09-16 20:30:58 +00004253static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004254char utf7_category[128] = {
4255/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4256 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4257/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4258 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4259/* sp ! " # $ % & ' ( ) * + , - . / */
4260 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4261/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4262 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4263/* @ A B C D E F G H I J K L M N O */
4264 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4265/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4266 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4267/* ` a b c d e f g h i j k l m n o */
4268 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4269/* p q r s t u v w x y z { | } ~ del */
4270 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004271};
4272
Antoine Pitrou244651a2009-05-04 18:56:13 +00004273/* ENCODE_DIRECT: this character should be encoded as itself. The
4274 * answer depends on whether we are encoding set O as itself, and also
4275 * on whether we are encoding whitespace as itself. RFC2152 makes it
4276 * clear that the answers to these questions vary between
4277 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004278
Antoine Pitrou244651a2009-05-04 18:56:13 +00004279#define ENCODE_DIRECT(c, directO, directWS) \
4280 ((c) < 128 && (c) > 0 && \
4281 ((utf7_category[(c)] == 0) || \
4282 (directWS && (utf7_category[(c)] == 2)) || \
4283 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004284
Alexander Belopolsky40018472011-02-26 01:02:56 +00004285PyObject *
4286PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004287 Py_ssize_t size,
4288 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004289{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004290 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4291}
4292
Antoine Pitrou244651a2009-05-04 18:56:13 +00004293/* The decoder. The only state we preserve is our read position,
4294 * i.e. how many characters we have consumed. So if we end in the
4295 * middle of a shift sequence we have to back off the read position
4296 * and the output to the beginning of the sequence, otherwise we lose
4297 * all the shift state (seen bits, number of bits seen, high
4298 * surrogate). */
4299
Alexander Belopolsky40018472011-02-26 01:02:56 +00004300PyObject *
4301PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004302 Py_ssize_t size,
4303 const char *errors,
4304 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004305{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004306 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004307 Py_ssize_t startinpos;
4308 Py_ssize_t endinpos;
4309 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004310 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004311 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004312 const char *errmsg = "";
4313 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004314 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004315 unsigned int base64bits = 0;
4316 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004317 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004318 PyObject *errorHandler = NULL;
4319 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004320
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004321 /* Start off assuming it's all ASCII. Widen later as necessary. */
4322 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004323 if (!unicode)
4324 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004325 if (size == 0) {
4326 if (consumed)
4327 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004328 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004329 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004330
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004331 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004332 e = s + size;
4333
4334 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004335 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004336 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004337 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004338
Antoine Pitrou244651a2009-05-04 18:56:13 +00004339 if (inShift) { /* in a base-64 section */
4340 if (IS_BASE64(ch)) { /* consume a base-64 character */
4341 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4342 base64bits += 6;
4343 s++;
4344 if (base64bits >= 16) {
4345 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004346 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004347 base64bits -= 16;
4348 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4349 if (surrogate) {
4350 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004351 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4352 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004353 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4354 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004355 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004356 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004357 }
4358 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004359 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4360 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004361 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004362 }
4363 }
Victor Stinner551ac952011-11-29 22:58:13 +01004364 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004365 /* first surrogate */
4366 surrogate = outCh;
4367 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004368 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004369 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4370 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004371 }
4372 }
4373 }
4374 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004375 inShift = 0;
4376 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004377 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004378 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4379 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004380 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004381 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004382 if (base64bits > 0) { /* left-over bits */
4383 if (base64bits >= 6) {
4384 /* We've seen at least one base-64 character */
4385 errmsg = "partial character in shift sequence";
4386 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004387 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004388 else {
4389 /* Some bits remain; they should be zero */
4390 if (base64buffer != 0) {
4391 errmsg = "non-zero padding bits in shift sequence";
4392 goto utf7Error;
4393 }
4394 }
4395 }
4396 if (ch != '-') {
4397 /* '-' is absorbed; other terminating
4398 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004399 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4400 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004401 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004402 }
4403 }
4404 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004405 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004406 s++; /* consume '+' */
4407 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004408 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004409 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4410 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004411 }
4412 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004413 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004414 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004415 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004416 }
4417 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004418 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004419 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4420 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004421 s++;
4422 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004423 else {
4424 startinpos = s-starts;
4425 s++;
4426 errmsg = "unexpected special character";
4427 goto utf7Error;
4428 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004429 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004430utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004431 endinpos = s-starts;
4432 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004433 errors, &errorHandler,
4434 "utf7", errmsg,
4435 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004436 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004437 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004438 }
4439
Antoine Pitrou244651a2009-05-04 18:56:13 +00004440 /* end of string */
4441
4442 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4443 /* if we're in an inconsistent state, that's an error */
4444 if (surrogate ||
4445 (base64bits >= 6) ||
4446 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004447 endinpos = size;
4448 if (unicode_decode_call_errorhandler(
4449 errors, &errorHandler,
4450 "utf7", "unterminated shift sequence",
4451 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004452 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004453 goto onError;
4454 if (s < e)
4455 goto restart;
4456 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004457 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004458
4459 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004460 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004461 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004462 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004463 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004464 }
4465 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004466 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004467 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004468 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004469
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004470 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004471 goto onError;
4472
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004473 Py_XDECREF(errorHandler);
4474 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004475 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004476
Benjamin Peterson29060642009-01-31 22:14:21 +00004477 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004478 Py_XDECREF(errorHandler);
4479 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004480 Py_DECREF(unicode);
4481 return NULL;
4482}
4483
4484
Alexander Belopolsky40018472011-02-26 01:02:56 +00004485PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004486_PyUnicode_EncodeUTF7(PyObject *str,
4487 int base64SetO,
4488 int base64WhiteSpace,
4489 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004490{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004491 int kind;
4492 void *data;
4493 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004494 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004495 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004496 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004497 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004498 unsigned int base64bits = 0;
4499 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004500 char * out;
4501 char * start;
4502
Benjamin Petersonbac79492012-01-14 13:34:47 -05004503 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004504 return NULL;
4505 kind = PyUnicode_KIND(str);
4506 data = PyUnicode_DATA(str);
4507 len = PyUnicode_GET_LENGTH(str);
4508
4509 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004510 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004511
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004512 /* It might be possible to tighten this worst case */
4513 allocated = 8 * len;
4514 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004515 return PyErr_NoMemory();
4516
Antoine Pitrou244651a2009-05-04 18:56:13 +00004517 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004518 if (v == NULL)
4519 return NULL;
4520
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004521 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004522 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004523 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004524
Antoine Pitrou244651a2009-05-04 18:56:13 +00004525 if (inShift) {
4526 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4527 /* shifting out */
4528 if (base64bits) { /* output remaining bits */
4529 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4530 base64buffer = 0;
4531 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004532 }
4533 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004534 /* Characters not in the BASE64 set implicitly unshift the sequence
4535 so no '-' is required, except if the character is itself a '-' */
4536 if (IS_BASE64(ch) || ch == '-') {
4537 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004538 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004539 *out++ = (char) ch;
4540 }
4541 else {
4542 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004543 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004544 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004545 else { /* not in a shift sequence */
4546 if (ch == '+') {
4547 *out++ = '+';
4548 *out++ = '-';
4549 }
4550 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4551 *out++ = (char) ch;
4552 }
4553 else {
4554 *out++ = '+';
4555 inShift = 1;
4556 goto encode_char;
4557 }
4558 }
4559 continue;
4560encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004561 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004562 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004563
Antoine Pitrou244651a2009-05-04 18:56:13 +00004564 /* code first surrogate */
4565 base64bits += 16;
4566 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4567 while (base64bits >= 6) {
4568 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4569 base64bits -= 6;
4570 }
4571 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004572 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004573 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004574 base64bits += 16;
4575 base64buffer = (base64buffer << 16) | ch;
4576 while (base64bits >= 6) {
4577 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4578 base64bits -= 6;
4579 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004580 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004581 if (base64bits)
4582 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4583 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004584 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004585 if (_PyBytes_Resize(&v, out - start) < 0)
4586 return NULL;
4587 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004588}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004589PyObject *
4590PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4591 Py_ssize_t size,
4592 int base64SetO,
4593 int base64WhiteSpace,
4594 const char *errors)
4595{
4596 PyObject *result;
4597 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4598 if (tmp == NULL)
4599 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004600 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004601 base64WhiteSpace, errors);
4602 Py_DECREF(tmp);
4603 return result;
4604}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004605
Antoine Pitrou244651a2009-05-04 18:56:13 +00004606#undef IS_BASE64
4607#undef FROM_BASE64
4608#undef TO_BASE64
4609#undef DECODE_DIRECT
4610#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004611
Guido van Rossumd57fd912000-03-10 22:53:23 +00004612/* --- UTF-8 Codec -------------------------------------------------------- */
4613
Alexander Belopolsky40018472011-02-26 01:02:56 +00004614PyObject *
4615PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004616 Py_ssize_t size,
4617 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004618{
Walter Dörwald69652032004-09-07 20:24:22 +00004619 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4620}
4621
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004622#include "stringlib/asciilib.h"
4623#include "stringlib/codecs.h"
4624#include "stringlib/undef.h"
4625
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004626#include "stringlib/ucs1lib.h"
4627#include "stringlib/codecs.h"
4628#include "stringlib/undef.h"
4629
4630#include "stringlib/ucs2lib.h"
4631#include "stringlib/codecs.h"
4632#include "stringlib/undef.h"
4633
4634#include "stringlib/ucs4lib.h"
4635#include "stringlib/codecs.h"
4636#include "stringlib/undef.h"
4637
Antoine Pitrouab868312009-01-10 15:40:25 +00004638/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4639#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4640
4641/* Mask to quickly check whether a C 'long' contains a
4642 non-ASCII, UTF8-encoded char. */
4643#if (SIZEOF_LONG == 8)
4644# define ASCII_CHAR_MASK 0x8080808080808080L
4645#elif (SIZEOF_LONG == 4)
4646# define ASCII_CHAR_MASK 0x80808080L
4647#else
4648# error C 'long' size should be either 4 or 8!
4649#endif
4650
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004651static Py_ssize_t
4652ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004653{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004654 const char *p = start;
4655 const char *aligned_end = (const char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004656
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004657#if SIZEOF_LONG <= SIZEOF_VOID_P
4658 assert(!((size_t) dest & LONG_PTR_MASK));
4659 if (!((size_t) p & LONG_PTR_MASK)) {
4660 /* Fast path, see in STRINGLIB(utf8_decode) for
4661 an explanation. */
4662 /* Help register allocation */
4663 register const char *_p = p;
4664 register Py_UCS1 * q = dest;
4665 while (_p < aligned_end) {
4666 unsigned long value = *(const unsigned long *) _p;
4667 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004668 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004669 *((unsigned long *)q) = value;
4670 _p += SIZEOF_LONG;
4671 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004672 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004673 p = _p;
4674 while (p < end) {
4675 if ((unsigned char)*p & 0x80)
4676 break;
4677 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004678 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004679 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004680 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004681#endif
4682 while (p < end) {
4683 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4684 for an explanation. */
4685 if (!((size_t) p & LONG_PTR_MASK)) {
4686 /* Help register allocation */
4687 register const char *_p = p;
4688 while (_p < aligned_end) {
4689 unsigned long value = *(unsigned long *) _p;
4690 if (value & ASCII_CHAR_MASK)
4691 break;
4692 _p += SIZEOF_LONG;
4693 }
4694 p = _p;
4695 if (_p == end)
4696 break;
4697 }
4698 if ((unsigned char)*p & 0x80)
4699 break;
4700 ++p;
4701 }
4702 memcpy(dest, start, p - start);
4703 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004704}
Antoine Pitrouab868312009-01-10 15:40:25 +00004705
Victor Stinner785938e2011-12-11 20:09:03 +01004706PyObject *
4707PyUnicode_DecodeUTF8Stateful(const char *s,
4708 Py_ssize_t size,
4709 const char *errors,
4710 Py_ssize_t *consumed)
4711{
Victor Stinner785938e2011-12-11 20:09:03 +01004712 PyObject *unicode;
Victor Stinner785938e2011-12-11 20:09:03 +01004713 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004714 const char *end = s + size;
4715 Py_ssize_t outpos;
4716
4717 Py_ssize_t startinpos;
4718 Py_ssize_t endinpos;
4719 const char *errmsg = "";
4720 PyObject *errorHandler = NULL;
4721 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004722
4723 if (size == 0) {
4724 if (consumed)
4725 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004726 Py_INCREF(unicode_empty);
4727 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004728 }
4729
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004730 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4731 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004732 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004733 *consumed = 1;
4734 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004735 }
4736
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004737 unicode = PyUnicode_New(size, 127);
Victor Stinner785938e2011-12-11 20:09:03 +01004738 if (!unicode)
4739 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004740
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004741 outpos = ascii_decode(s, end, PyUnicode_1BYTE_DATA(unicode));
4742 s += outpos;
4743 while (s < end) {
4744 Py_UCS4 ch;
4745 int kind = PyUnicode_KIND(unicode);
4746 if (kind == PyUnicode_1BYTE_KIND) {
4747 if (PyUnicode_IS_ASCII(unicode))
4748 ch = asciilib_utf8_decode(&s, end,
4749 PyUnicode_1BYTE_DATA(unicode), &outpos);
4750 else
4751 ch = ucs1lib_utf8_decode(&s, end,
4752 PyUnicode_1BYTE_DATA(unicode), &outpos);
4753 } else if (kind == PyUnicode_2BYTE_KIND) {
4754 ch = ucs2lib_utf8_decode(&s, end,
4755 PyUnicode_2BYTE_DATA(unicode), &outpos);
4756 } else {
4757 assert(kind == PyUnicode_4BYTE_KIND);
4758 ch = ucs4lib_utf8_decode(&s, end,
4759 PyUnicode_4BYTE_DATA(unicode), &outpos);
4760 }
4761
4762 switch (ch) {
4763 case 0:
4764 if (s == end || consumed)
4765 goto End;
4766 errmsg = "unexpected end of data";
4767 startinpos = s - starts;
4768 endinpos = startinpos + 1;
4769 while (endinpos < size && (starts[endinpos] & 0xC0) == 0x80)
4770 endinpos++;
4771 break;
4772 case 1:
4773 errmsg = "invalid start byte";
4774 startinpos = s - starts;
4775 endinpos = startinpos + 1;
4776 break;
4777 case 2:
4778 errmsg = "invalid continuation byte";
4779 startinpos = s - starts;
4780 endinpos = startinpos + 1;
4781 while (endinpos < size && (starts[endinpos] & 0xC0) == 0x80)
4782 endinpos++;
4783 break;
4784 default:
4785 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4786 goto onError;
4787 continue;
4788 }
4789
4790 if (unicode_decode_call_errorhandler(
4791 errors, &errorHandler,
4792 "utf-8", errmsg,
4793 &starts, &end, &startinpos, &endinpos, &exc, &s,
4794 &unicode, &outpos))
4795 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004796 }
4797
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004798End:
4799 if (unicode_resize(&unicode, outpos) < 0)
4800 goto onError;
4801
4802 if (consumed)
4803 *consumed = s - starts;
4804
4805 Py_XDECREF(errorHandler);
4806 Py_XDECREF(exc);
4807 assert(_PyUnicode_CheckConsistency(unicode, 1));
4808 return unicode;
4809
4810onError:
4811 Py_XDECREF(errorHandler);
4812 Py_XDECREF(exc);
4813 Py_XDECREF(unicode);
4814 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004815}
4816
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004817#ifdef __APPLE__
4818
4819/* Simplified UTF-8 decoder using surrogateescape error handler,
4820 used to decode the command line arguments on Mac OS X. */
4821
4822wchar_t*
4823_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4824{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004825 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004826 wchar_t *unicode;
4827 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004828
4829 /* Note: size will always be longer than the resulting Unicode
4830 character count */
4831 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4832 PyErr_NoMemory();
4833 return NULL;
4834 }
4835 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4836 if (!unicode)
4837 return NULL;
4838
4839 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004840 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004841 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004842 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004843 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004844#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004845 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004846#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004847 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004848#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004849 if (ch > 0xFF) {
4850#if SIZEOF_WCHAR_T == 4
4851 assert(0);
4852#else
4853 assert(Py_UNICODE_IS_SURROGATE(ch));
4854 /* compute and append the two surrogates: */
4855 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4856 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4857#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004858 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004859 else {
4860 if (!ch && s == e)
4861 break;
4862 /* surrogateescape */
4863 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4864 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004865 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004866 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004867 return unicode;
4868}
4869
4870#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004871
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004872/* Primary internal function which creates utf8 encoded bytes objects.
4873
4874 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004875 and allocate exactly as much space needed at the end. Else allocate the
4876 maximum possible needed (4 result bytes per Unicode character), and return
4877 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004878*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004879PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004880_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004881{
Victor Stinner6099a032011-12-18 14:22:26 +01004882 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004883 void *data;
4884 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004885
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004886 if (!PyUnicode_Check(unicode)) {
4887 PyErr_BadArgument();
4888 return NULL;
4889 }
4890
4891 if (PyUnicode_READY(unicode) == -1)
4892 return NULL;
4893
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004894 if (PyUnicode_UTF8(unicode))
4895 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4896 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004897
4898 kind = PyUnicode_KIND(unicode);
4899 data = PyUnicode_DATA(unicode);
4900 size = PyUnicode_GET_LENGTH(unicode);
4901
Benjamin Petersonead6b532011-12-20 17:23:42 -06004902 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004903 default:
4904 assert(0);
4905 case PyUnicode_1BYTE_KIND:
4906 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4907 assert(!PyUnicode_IS_ASCII(unicode));
4908 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4909 case PyUnicode_2BYTE_KIND:
4910 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4911 case PyUnicode_4BYTE_KIND:
4912 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004913 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004914}
4915
Alexander Belopolsky40018472011-02-26 01:02:56 +00004916PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004917PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4918 Py_ssize_t size,
4919 const char *errors)
4920{
4921 PyObject *v, *unicode;
4922
4923 unicode = PyUnicode_FromUnicode(s, size);
4924 if (unicode == NULL)
4925 return NULL;
4926 v = _PyUnicode_AsUTF8String(unicode, errors);
4927 Py_DECREF(unicode);
4928 return v;
4929}
4930
4931PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004932PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004933{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004934 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004935}
4936
Walter Dörwald41980ca2007-08-16 21:55:45 +00004937/* --- UTF-32 Codec ------------------------------------------------------- */
4938
4939PyObject *
4940PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004941 Py_ssize_t size,
4942 const char *errors,
4943 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004944{
4945 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4946}
4947
4948PyObject *
4949PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004950 Py_ssize_t size,
4951 const char *errors,
4952 int *byteorder,
4953 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004954{
4955 const char *starts = s;
4956 Py_ssize_t startinpos;
4957 Py_ssize_t endinpos;
4958 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004959 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004960 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004961 int bo = 0; /* assume native ordering by default */
4962 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004963 /* Offsets from q for retrieving bytes in the right order. */
4964#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4965 int iorder[] = {0, 1, 2, 3};
4966#else
4967 int iorder[] = {3, 2, 1, 0};
4968#endif
4969 PyObject *errorHandler = NULL;
4970 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004971
Walter Dörwald41980ca2007-08-16 21:55:45 +00004972 q = (unsigned char *)s;
4973 e = q + size;
4974
4975 if (byteorder)
4976 bo = *byteorder;
4977
4978 /* Check for BOM marks (U+FEFF) in the input and adjust current
4979 byte order setting accordingly. In native mode, the leading BOM
4980 mark is skipped, in all other modes, it is copied to the output
4981 stream as-is (giving a ZWNBSP character). */
4982 if (bo == 0) {
4983 if (size >= 4) {
4984 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004985 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004986#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004987 if (bom == 0x0000FEFF) {
4988 q += 4;
4989 bo = -1;
4990 }
4991 else if (bom == 0xFFFE0000) {
4992 q += 4;
4993 bo = 1;
4994 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004995#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004996 if (bom == 0x0000FEFF) {
4997 q += 4;
4998 bo = 1;
4999 }
5000 else if (bom == 0xFFFE0000) {
5001 q += 4;
5002 bo = -1;
5003 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005004#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005005 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005006 }
5007
5008 if (bo == -1) {
5009 /* force LE */
5010 iorder[0] = 0;
5011 iorder[1] = 1;
5012 iorder[2] = 2;
5013 iorder[3] = 3;
5014 }
5015 else if (bo == 1) {
5016 /* force BE */
5017 iorder[0] = 3;
5018 iorder[1] = 2;
5019 iorder[2] = 1;
5020 iorder[3] = 0;
5021 }
5022
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005023 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005024 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005025 if (!unicode)
5026 return NULL;
5027 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005028 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005029 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005030
Walter Dörwald41980ca2007-08-16 21:55:45 +00005031 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005032 Py_UCS4 ch;
5033 /* remaining bytes at the end? (size should be divisible by 4) */
5034 if (e-q<4) {
5035 if (consumed)
5036 break;
5037 errmsg = "truncated data";
5038 startinpos = ((const char *)q)-starts;
5039 endinpos = ((const char *)e)-starts;
5040 goto utf32Error;
5041 /* The remaining input chars are ignored if the callback
5042 chooses to skip the input */
5043 }
5044 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5045 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005046
Benjamin Peterson29060642009-01-31 22:14:21 +00005047 if (ch >= 0x110000)
5048 {
5049 errmsg = "codepoint not in range(0x110000)";
5050 startinpos = ((const char *)q)-starts;
5051 endinpos = startinpos+4;
5052 goto utf32Error;
5053 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005054 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5055 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005056 q += 4;
5057 continue;
5058 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005059 if (unicode_decode_call_errorhandler(
5060 errors, &errorHandler,
5061 "utf32", errmsg,
5062 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005063 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005064 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005065 }
5066
5067 if (byteorder)
5068 *byteorder = bo;
5069
5070 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005071 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005072
5073 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005074 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005075 goto onError;
5076
5077 Py_XDECREF(errorHandler);
5078 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005079 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005080
Benjamin Peterson29060642009-01-31 22:14:21 +00005081 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005082 Py_DECREF(unicode);
5083 Py_XDECREF(errorHandler);
5084 Py_XDECREF(exc);
5085 return NULL;
5086}
5087
5088PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005089_PyUnicode_EncodeUTF32(PyObject *str,
5090 const char *errors,
5091 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005092{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005093 int kind;
5094 void *data;
5095 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005096 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005097 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005098 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005099 /* Offsets from p for storing byte pairs in the right order. */
5100#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5101 int iorder[] = {0, 1, 2, 3};
5102#else
5103 int iorder[] = {3, 2, 1, 0};
5104#endif
5105
Benjamin Peterson29060642009-01-31 22:14:21 +00005106#define STORECHAR(CH) \
5107 do { \
5108 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5109 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5110 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5111 p[iorder[0]] = (CH) & 0xff; \
5112 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005113 } while(0)
5114
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005115 if (!PyUnicode_Check(str)) {
5116 PyErr_BadArgument();
5117 return NULL;
5118 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005119 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005120 return NULL;
5121 kind = PyUnicode_KIND(str);
5122 data = PyUnicode_DATA(str);
5123 len = PyUnicode_GET_LENGTH(str);
5124
5125 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005126 bytesize = nsize * 4;
5127 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005128 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005129 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005130 if (v == NULL)
5131 return NULL;
5132
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005133 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005134 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005135 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005136 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005137 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005138
5139 if (byteorder == -1) {
5140 /* force LE */
5141 iorder[0] = 0;
5142 iorder[1] = 1;
5143 iorder[2] = 2;
5144 iorder[3] = 3;
5145 }
5146 else if (byteorder == 1) {
5147 /* force BE */
5148 iorder[0] = 3;
5149 iorder[1] = 2;
5150 iorder[2] = 1;
5151 iorder[3] = 0;
5152 }
5153
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005154 for (i = 0; i < len; i++)
5155 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005156
5157 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005158 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005159#undef STORECHAR
5160}
5161
Alexander Belopolsky40018472011-02-26 01:02:56 +00005162PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005163PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5164 Py_ssize_t size,
5165 const char *errors,
5166 int byteorder)
5167{
5168 PyObject *result;
5169 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5170 if (tmp == NULL)
5171 return NULL;
5172 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5173 Py_DECREF(tmp);
5174 return result;
5175}
5176
5177PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005178PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005179{
Victor Stinnerb960b342011-11-20 19:12:52 +01005180 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005181}
5182
Guido van Rossumd57fd912000-03-10 22:53:23 +00005183/* --- UTF-16 Codec ------------------------------------------------------- */
5184
Tim Peters772747b2001-08-09 22:21:55 +00005185PyObject *
5186PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005187 Py_ssize_t size,
5188 const char *errors,
5189 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005190{
Walter Dörwald69652032004-09-07 20:24:22 +00005191 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5192}
5193
5194PyObject *
5195PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005196 Py_ssize_t size,
5197 const char *errors,
5198 int *byteorder,
5199 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005200{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005201 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005202 Py_ssize_t startinpos;
5203 Py_ssize_t endinpos;
5204 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005205 PyObject *unicode;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005206 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005207 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005208 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005209 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005210 PyObject *errorHandler = NULL;
5211 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005212
Tim Peters772747b2001-08-09 22:21:55 +00005213 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005214 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005215
5216 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005217 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005218
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005219 /* Check for BOM marks (U+FEFF) in the input and adjust current
5220 byte order setting accordingly. In native mode, the leading BOM
5221 mark is skipped, in all other modes, it is copied to the output
5222 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005223 if (bo == 0 && size >= 2) {
5224 const Py_UCS4 bom = (q[1] << 8) | q[0];
5225 if (bom == 0xFEFF) {
5226 q += 2;
5227 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005228 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005229 else if (bom == 0xFFFE) {
5230 q += 2;
5231 bo = 1;
5232 }
5233 if (byteorder)
5234 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005235 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005236
Antoine Pitrou63065d72012-05-15 23:48:04 +02005237 if (q == e) {
5238 if (consumed)
5239 *consumed = size;
5240 Py_INCREF(unicode_empty);
5241 return unicode_empty;
Tim Peters772747b2001-08-09 22:21:55 +00005242 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005243
Antoine Pitrouab868312009-01-10 15:40:25 +00005244#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005245 native_ordering = bo <= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005246#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005247 native_ordering = bo >= 0;
Antoine Pitrouab868312009-01-10 15:40:25 +00005248#endif
Tim Peters772747b2001-08-09 22:21:55 +00005249
Antoine Pitrou63065d72012-05-15 23:48:04 +02005250 /* Note: size will always be longer than the resulting Unicode
5251 character count */
5252 unicode = PyUnicode_New((e - q + 1) / 2, 127);
5253 if (!unicode)
5254 return NULL;
5255
5256 outpos = 0;
5257 while (1) {
5258 Py_UCS4 ch = 0;
5259 if (e - q >= 2) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005260 int kind = PyUnicode_KIND(unicode);
Antoine Pitrou63065d72012-05-15 23:48:04 +02005261 if (kind == PyUnicode_1BYTE_KIND) {
5262 if (PyUnicode_IS_ASCII(unicode))
5263 ch = asciilib_utf16_decode(&q, e,
5264 PyUnicode_1BYTE_DATA(unicode), &outpos,
5265 native_ordering);
5266 else
5267 ch = ucs1lib_utf16_decode(&q, e,
5268 PyUnicode_1BYTE_DATA(unicode), &outpos,
5269 native_ordering);
5270 } else if (kind == PyUnicode_2BYTE_KIND) {
5271 ch = ucs2lib_utf16_decode(&q, e,
5272 PyUnicode_2BYTE_DATA(unicode), &outpos,
5273 native_ordering);
5274 } else {
5275 assert(kind == PyUnicode_4BYTE_KIND);
5276 ch = ucs4lib_utf16_decode(&q, e,
5277 PyUnicode_4BYTE_DATA(unicode), &outpos,
5278 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005279 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005280 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005281
Antoine Pitrou63065d72012-05-15 23:48:04 +02005282 switch (ch)
5283 {
5284 case 0:
5285 /* remaining byte at the end? (size should be even) */
5286 if (q == e || consumed)
5287 goto End;
5288 errmsg = "truncated data";
5289 startinpos = ((const char *)q) - starts;
5290 endinpos = ((const char *)e) - starts;
5291 break;
5292 /* The remaining input chars are ignored if the callback
5293 chooses to skip the input */
5294 case 1:
5295 errmsg = "unexpected end of data";
5296 startinpos = ((const char *)q) - 2 - starts;
5297 endinpos = ((const char *)e) - starts;
5298 break;
5299 case 2:
5300 errmsg = "illegal encoding";
5301 startinpos = ((const char *)q) - 2 - starts;
5302 endinpos = startinpos + 2;
5303 break;
5304 case 3:
5305 errmsg = "illegal UTF-16 surrogate";
5306 startinpos = ((const char *)q) - 4 - starts;
5307 endinpos = startinpos + 2;
5308 break;
5309 default:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005310 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5311 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005312 continue;
5313 }
5314
Benjamin Peterson29060642009-01-31 22:14:21 +00005315 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005316 errors,
5317 &errorHandler,
5318 "utf16", errmsg,
5319 &starts,
5320 (const char **)&e,
5321 &startinpos,
5322 &endinpos,
5323 &exc,
5324 (const char **)&q,
5325 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005326 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005327 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005328 }
5329
Antoine Pitrou63065d72012-05-15 23:48:04 +02005330End:
Walter Dörwald69652032004-09-07 20:24:22 +00005331 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005332 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005333
Guido van Rossumd57fd912000-03-10 22:53:23 +00005334 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005335 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005336 goto onError;
5337
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005338 Py_XDECREF(errorHandler);
5339 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005340 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005341
Benjamin Peterson29060642009-01-31 22:14:21 +00005342 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005343 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005344 Py_XDECREF(errorHandler);
5345 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005346 return NULL;
5347}
5348
Tim Peters772747b2001-08-09 22:21:55 +00005349PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005350_PyUnicode_EncodeUTF16(PyObject *str,
5351 const char *errors,
5352 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005353{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005354 enum PyUnicode_Kind kind;
5355 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005356 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005357 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005358 unsigned short *out;
5359 Py_ssize_t bytesize;
5360 Py_ssize_t pairs;
5361#ifdef WORDS_BIGENDIAN
5362 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005363#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005364 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005365#endif
5366
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005367 if (!PyUnicode_Check(str)) {
5368 PyErr_BadArgument();
5369 return NULL;
5370 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005371 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005372 return NULL;
5373 kind = PyUnicode_KIND(str);
5374 data = PyUnicode_DATA(str);
5375 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005376
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005377 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005378 if (kind == PyUnicode_4BYTE_KIND) {
5379 const Py_UCS4 *in = (const Py_UCS4 *)data;
5380 const Py_UCS4 *end = in + len;
5381 while (in < end)
5382 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005383 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005384 }
5385 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005386 return PyErr_NoMemory();
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005387 bytesize = (len + pairs + (byteorder == 0)) * 2;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005388 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005389 if (v == NULL)
5390 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005391
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005392 /* output buffer is 2-bytes aligned */
5393 assert(((Py_uintptr_t)PyBytes_AS_STRING(v) & 1) == 0);
5394 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005395 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005396 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005397 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005398 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005399
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005400 switch (kind) {
5401 case PyUnicode_1BYTE_KIND: {
5402 ucs1lib_utf16_encode(out, (const Py_UCS1 *)data, len, native_ordering);
5403 break;
Tim Peters772747b2001-08-09 22:21:55 +00005404 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005405 case PyUnicode_2BYTE_KIND: {
5406 ucs2lib_utf16_encode(out, (const Py_UCS2 *)data, len, native_ordering);
5407 break;
Tim Peters772747b2001-08-09 22:21:55 +00005408 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005409 case PyUnicode_4BYTE_KIND: {
5410 ucs4lib_utf16_encode(out, (const Py_UCS4 *)data, len, native_ordering);
5411 break;
5412 }
5413 default:
5414 assert(0);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005415 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005416
5417 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005418 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005419}
5420
Alexander Belopolsky40018472011-02-26 01:02:56 +00005421PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005422PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5423 Py_ssize_t size,
5424 const char *errors,
5425 int byteorder)
5426{
5427 PyObject *result;
5428 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5429 if (tmp == NULL)
5430 return NULL;
5431 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5432 Py_DECREF(tmp);
5433 return result;
5434}
5435
5436PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005437PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005438{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005439 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005440}
5441
5442/* --- Unicode Escape Codec ----------------------------------------------- */
5443
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005444/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5445 if all the escapes in the string make it still a valid ASCII string.
5446 Returns -1 if any escapes were found which cause the string to
5447 pop out of ASCII range. Otherwise returns the length of the
5448 required buffer to hold the string.
5449 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005450static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005451length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5452{
5453 const unsigned char *p = (const unsigned char *)s;
5454 const unsigned char *end = p + size;
5455 Py_ssize_t length = 0;
5456
5457 if (size < 0)
5458 return -1;
5459
5460 for (; p < end; ++p) {
5461 if (*p > 127) {
5462 /* Non-ASCII */
5463 return -1;
5464 }
5465 else if (*p != '\\') {
5466 /* Normal character */
5467 ++length;
5468 }
5469 else {
5470 /* Backslash-escape, check next char */
5471 ++p;
5472 /* Escape sequence reaches till end of string or
5473 non-ASCII follow-up. */
5474 if (p >= end || *p > 127)
5475 return -1;
5476 switch (*p) {
5477 case '\n':
5478 /* backslash + \n result in zero characters */
5479 break;
5480 case '\\': case '\'': case '\"':
5481 case 'b': case 'f': case 't':
5482 case 'n': case 'r': case 'v': case 'a':
5483 ++length;
5484 break;
5485 case '0': case '1': case '2': case '3':
5486 case '4': case '5': case '6': case '7':
5487 case 'x': case 'u': case 'U': case 'N':
5488 /* these do not guarantee ASCII characters */
5489 return -1;
5490 default:
5491 /* count the backslash + the other character */
5492 length += 2;
5493 }
5494 }
5495 }
5496 return length;
5497}
5498
Fredrik Lundh06d12682001-01-24 07:59:11 +00005499static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005500
Alexander Belopolsky40018472011-02-26 01:02:56 +00005501PyObject *
5502PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005503 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005504 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005505{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005506 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005507 Py_ssize_t startinpos;
5508 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005509 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005510 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005511 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005512 char* message;
5513 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005514 PyObject *errorHandler = NULL;
5515 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005516 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005517 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005518
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005519 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005520
5521 /* After length_of_escaped_ascii_string() there are two alternatives,
5522 either the string is pure ASCII with named escapes like \n, etc.
5523 and we determined it's exact size (common case)
5524 or it contains \x, \u, ... escape sequences. then we create a
5525 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005526 if (len >= 0) {
5527 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005528 if (!v)
5529 goto onError;
5530 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005531 }
5532 else {
5533 /* Escaped strings will always be longer than the resulting
5534 Unicode string, so we start with size here and then reduce the
5535 length after conversion to the true value.
5536 (but if the error callback returns a long replacement string
5537 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005538 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005539 if (!v)
5540 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005541 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005542 }
5543
Guido van Rossumd57fd912000-03-10 22:53:23 +00005544 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005545 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005546 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005547 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005548
Guido van Rossumd57fd912000-03-10 22:53:23 +00005549 while (s < end) {
5550 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005551 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005552 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005553
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005554 /* The only case in which i == ascii_length is a backslash
5555 followed by a newline. */
5556 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005557
Guido van Rossumd57fd912000-03-10 22:53:23 +00005558 /* Non-escape characters are interpreted as Unicode ordinals */
5559 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005560 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5561 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005562 continue;
5563 }
5564
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005565 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005566 /* \ - Escapes */
5567 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005568 c = *s++;
5569 if (s > end)
5570 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005571
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005572 /* The only case in which i == ascii_length is a backslash
5573 followed by a newline. */
5574 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005575
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005576 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005577
Benjamin Peterson29060642009-01-31 22:14:21 +00005578 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005579#define WRITECHAR(ch) \
5580 do { \
5581 if (unicode_putchar(&v, &i, ch) < 0) \
5582 goto onError; \
5583 }while(0)
5584
Guido van Rossumd57fd912000-03-10 22:53:23 +00005585 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005586 case '\\': WRITECHAR('\\'); break;
5587 case '\'': WRITECHAR('\''); break;
5588 case '\"': WRITECHAR('\"'); break;
5589 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005590 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005591 case 'f': WRITECHAR('\014'); break;
5592 case 't': WRITECHAR('\t'); break;
5593 case 'n': WRITECHAR('\n'); break;
5594 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005595 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005596 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005597 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005598 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005599
Benjamin Peterson29060642009-01-31 22:14:21 +00005600 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005601 case '0': case '1': case '2': case '3':
5602 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005603 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005604 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005605 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005606 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005607 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005608 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005609 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005610 break;
5611
Benjamin Peterson29060642009-01-31 22:14:21 +00005612 /* hex escapes */
5613 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005614 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005615 digits = 2;
5616 message = "truncated \\xXX escape";
5617 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005618
Benjamin Peterson29060642009-01-31 22:14:21 +00005619 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005620 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005621 digits = 4;
5622 message = "truncated \\uXXXX escape";
5623 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005624
Benjamin Peterson29060642009-01-31 22:14:21 +00005625 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005626 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005627 digits = 8;
5628 message = "truncated \\UXXXXXXXX escape";
5629 hexescape:
5630 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005631 if (s+digits>end) {
5632 endinpos = size;
5633 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005634 errors, &errorHandler,
5635 "unicodeescape", "end of string in escape sequence",
5636 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005637 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005638 goto onError;
5639 goto nextByte;
5640 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005641 for (j = 0; j < digits; ++j) {
5642 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005643 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005644 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005645 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005646 errors, &errorHandler,
5647 "unicodeescape", message,
5648 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005649 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005650 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005651 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005652 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005653 }
5654 chr = (chr<<4) & ~0xF;
5655 if (c >= '0' && c <= '9')
5656 chr += c - '0';
5657 else if (c >= 'a' && c <= 'f')
5658 chr += 10 + c - 'a';
5659 else
5660 chr += 10 + c - 'A';
5661 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005662 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005663 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005664 /* _decoding_error will have already written into the
5665 target buffer. */
5666 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005667 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005668 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005669 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005670 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005671 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005672 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005673 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005674 errors, &errorHandler,
5675 "unicodeescape", "illegal Unicode character",
5676 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005677 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005678 goto onError;
5679 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005680 break;
5681
Benjamin Peterson29060642009-01-31 22:14:21 +00005682 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005683 case 'N':
5684 message = "malformed \\N character escape";
5685 if (ucnhash_CAPI == NULL) {
5686 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005687 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5688 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005689 if (ucnhash_CAPI == NULL)
5690 goto ucnhashError;
5691 }
5692 if (*s == '{') {
5693 const char *start = s+1;
5694 /* look for the closing brace */
5695 while (*s != '}' && s < end)
5696 s++;
5697 if (s > start && s < end && *s == '}') {
5698 /* found a name. look it up in the unicode database */
5699 message = "unknown Unicode character name";
5700 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005701 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005702 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005703 goto store;
5704 }
5705 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005706 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005707 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005708 errors, &errorHandler,
5709 "unicodeescape", message,
5710 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005711 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005712 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005713 break;
5714
5715 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005716 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005717 message = "\\ at end of string";
5718 s--;
5719 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005720 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005721 errors, &errorHandler,
5722 "unicodeescape", message,
5723 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005724 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005725 goto onError;
5726 }
5727 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005728 WRITECHAR('\\');
5729 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005730 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005731 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005733 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005734 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005735 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005736#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005737
Victor Stinner16e6a802011-12-12 13:24:15 +01005738 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005739 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005740 Py_XDECREF(errorHandler);
5741 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005742 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005743
Benjamin Peterson29060642009-01-31 22:14:21 +00005744 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005745 PyErr_SetString(
5746 PyExc_UnicodeError,
5747 "\\N escapes not supported (can't load unicodedata module)"
5748 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005749 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005750 Py_XDECREF(errorHandler);
5751 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005752 return NULL;
5753
Benjamin Peterson29060642009-01-31 22:14:21 +00005754 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005755 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005756 Py_XDECREF(errorHandler);
5757 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005758 return NULL;
5759}
5760
5761/* Return a Unicode-Escape string version of the Unicode object.
5762
5763 If quotes is true, the string is enclosed in u"" or u'' quotes as
5764 appropriate.
5765
5766*/
5767
Alexander Belopolsky40018472011-02-26 01:02:56 +00005768PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005769PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005770{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005771 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005772 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005773 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005774 int kind;
5775 void *data;
5776 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005777
Thomas Wouters89f507f2006-12-13 04:49:30 +00005778 /* Initial allocation is based on the longest-possible unichr
5779 escape.
5780
5781 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5782 unichr, so in this case it's the longest unichr escape. In
5783 narrow (UTF-16) builds this is five chars per source unichr
5784 since there are two unichrs in the surrogate pair, so in narrow
5785 (UTF-16) builds it's not the longest unichr escape.
5786
5787 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5788 so in the narrow (UTF-16) build case it's the longest unichr
5789 escape.
5790 */
5791
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005792 if (!PyUnicode_Check(unicode)) {
5793 PyErr_BadArgument();
5794 return NULL;
5795 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005796 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005797 return NULL;
5798 len = PyUnicode_GET_LENGTH(unicode);
5799 kind = PyUnicode_KIND(unicode);
5800 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005801 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005802 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5803 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5804 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5805 }
5806
5807 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005808 return PyBytes_FromStringAndSize(NULL, 0);
5809
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005810 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005811 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005812
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005813 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005814 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005815 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005816 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005817 if (repr == NULL)
5818 return NULL;
5819
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005820 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005821
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005822 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005823 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005824
Walter Dörwald79e913e2007-05-12 11:08:06 +00005825 /* Escape backslashes */
5826 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005827 *p++ = '\\';
5828 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005829 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005830 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005831
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005832 /* Map 21-bit characters to '\U00xxxxxx' */
5833 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005834 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005835 *p++ = '\\';
5836 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005837 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5838 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5839 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5840 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5841 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5842 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5843 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5844 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005845 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005846 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005847
Guido van Rossumd57fd912000-03-10 22:53:23 +00005848 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005849 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005850 *p++ = '\\';
5851 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005852 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5853 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5854 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5855 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005856 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005857
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005858 /* Map special whitespace to '\t', \n', '\r' */
5859 else if (ch == '\t') {
5860 *p++ = '\\';
5861 *p++ = 't';
5862 }
5863 else if (ch == '\n') {
5864 *p++ = '\\';
5865 *p++ = 'n';
5866 }
5867 else if (ch == '\r') {
5868 *p++ = '\\';
5869 *p++ = 'r';
5870 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005871
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005872 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005873 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005874 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005875 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005876 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5877 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005878 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005879
Guido van Rossumd57fd912000-03-10 22:53:23 +00005880 /* Copy everything else as-is */
5881 else
5882 *p++ = (char) ch;
5883 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005884
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005885 assert(p - PyBytes_AS_STRING(repr) > 0);
5886 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5887 return NULL;
5888 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005889}
5890
Alexander Belopolsky40018472011-02-26 01:02:56 +00005891PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005892PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5893 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005894{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005895 PyObject *result;
5896 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5897 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005898 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005899 result = PyUnicode_AsUnicodeEscapeString(tmp);
5900 Py_DECREF(tmp);
5901 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005902}
5903
5904/* --- Raw Unicode Escape Codec ------------------------------------------- */
5905
Alexander Belopolsky40018472011-02-26 01:02:56 +00005906PyObject *
5907PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005908 Py_ssize_t size,
5909 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005910{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005911 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005912 Py_ssize_t startinpos;
5913 Py_ssize_t endinpos;
5914 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005915 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005916 const char *end;
5917 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005918 PyObject *errorHandler = NULL;
5919 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005920
Guido van Rossumd57fd912000-03-10 22:53:23 +00005921 /* Escaped strings will always be longer than the resulting
5922 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005923 length after conversion to the true value. (But decoding error
5924 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005925 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005926 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005927 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005928 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005929 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005930 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005931 end = s + size;
5932 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005933 unsigned char c;
5934 Py_UCS4 x;
5935 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005936 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005937
Benjamin Peterson29060642009-01-31 22:14:21 +00005938 /* Non-escape characters are interpreted as Unicode ordinals */
5939 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005940 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5941 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005942 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005943 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005944 startinpos = s-starts;
5945
5946 /* \u-escapes are only interpreted iff the number of leading
5947 backslashes if odd */
5948 bs = s;
5949 for (;s < end;) {
5950 if (*s != '\\')
5951 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005952 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
5953 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005954 }
5955 if (((s - bs) & 1) == 0 ||
5956 s >= end ||
5957 (*s != 'u' && *s != 'U')) {
5958 continue;
5959 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005960 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00005961 count = *s=='u' ? 4 : 8;
5962 s++;
5963
5964 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00005965 for (x = 0, i = 0; i < count; ++i, ++s) {
5966 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005967 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005968 endinpos = s-starts;
5969 if (unicode_decode_call_errorhandler(
5970 errors, &errorHandler,
5971 "rawunicodeescape", "truncated \\uXXXX",
5972 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005973 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005974 goto onError;
5975 goto nextByte;
5976 }
5977 x = (x<<4) & ~0xF;
5978 if (c >= '0' && c <= '9')
5979 x += c - '0';
5980 else if (c >= 'a' && c <= 'f')
5981 x += 10 + c - 'a';
5982 else
5983 x += 10 + c - 'A';
5984 }
Victor Stinner8faf8212011-12-08 22:14:11 +01005985 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005986 if (unicode_putchar(&v, &outpos, x) < 0)
5987 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005988 } else {
5989 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005990 if (unicode_decode_call_errorhandler(
5991 errors, &errorHandler,
5992 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005993 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005994 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005995 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005996 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005997 nextByte:
5998 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005999 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006000 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006001 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006002 Py_XDECREF(errorHandler);
6003 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006004 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006005
Benjamin Peterson29060642009-01-31 22:14:21 +00006006 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006007 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006008 Py_XDECREF(errorHandler);
6009 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006010 return NULL;
6011}
6012
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006013
Alexander Belopolsky40018472011-02-26 01:02:56 +00006014PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006015PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006016{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006017 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006018 char *p;
6019 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006020 Py_ssize_t expandsize, pos;
6021 int kind;
6022 void *data;
6023 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006024
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006025 if (!PyUnicode_Check(unicode)) {
6026 PyErr_BadArgument();
6027 return NULL;
6028 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006029 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006030 return NULL;
6031 kind = PyUnicode_KIND(unicode);
6032 data = PyUnicode_DATA(unicode);
6033 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006034 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6035 bytes, and 1 byte characters 4. */
6036 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006037
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006038 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006039 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006040
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006041 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006042 if (repr == NULL)
6043 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006044 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006045 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006046
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006047 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006048 for (pos = 0; pos < len; pos++) {
6049 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006050 /* Map 32-bit characters to '\Uxxxxxxxx' */
6051 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006052 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006053 *p++ = '\\';
6054 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006055 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6056 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6057 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6058 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6059 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6060 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6061 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6062 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006063 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006064 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006065 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006066 *p++ = '\\';
6067 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006068 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6069 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6070 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6071 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006072 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006073 /* Copy everything else as-is */
6074 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006075 *p++ = (char) ch;
6076 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006077
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006078 assert(p > q);
6079 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006080 return NULL;
6081 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006082}
6083
Alexander Belopolsky40018472011-02-26 01:02:56 +00006084PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006085PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6086 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006087{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006088 PyObject *result;
6089 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6090 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006091 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006092 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6093 Py_DECREF(tmp);
6094 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006095}
6096
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006097/* --- Unicode Internal Codec ------------------------------------------- */
6098
Alexander Belopolsky40018472011-02-26 01:02:56 +00006099PyObject *
6100_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006101 Py_ssize_t size,
6102 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006103{
6104 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006105 Py_ssize_t startinpos;
6106 Py_ssize_t endinpos;
6107 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006108 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006109 const char *end;
6110 const char *reason;
6111 PyObject *errorHandler = NULL;
6112 PyObject *exc = NULL;
6113
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006114 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006115 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006116 1))
6117 return NULL;
6118
Thomas Wouters89f507f2006-12-13 04:49:30 +00006119 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006120 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006121 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006122 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006123 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006124 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006125 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006126 end = s + size;
6127
6128 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006129 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006130 Py_UCS4 ch;
6131 /* We copy the raw representation one byte at a time because the
6132 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006133 ((char *) &uch)[0] = s[0];
6134 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006135#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006136 ((char *) &uch)[2] = s[2];
6137 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006138#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006139 ch = uch;
6140
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006141 /* We have to sanity check the raw data, otherwise doom looms for
6142 some malformed UCS-4 data. */
6143 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006144#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006145 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006146#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006147 end-s < Py_UNICODE_SIZE
6148 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006149 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006150 startinpos = s - starts;
6151 if (end-s < Py_UNICODE_SIZE) {
6152 endinpos = end-starts;
6153 reason = "truncated input";
6154 }
6155 else {
6156 endinpos = s - starts + Py_UNICODE_SIZE;
6157 reason = "illegal code point (> 0x10FFFF)";
6158 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006159 if (unicode_decode_call_errorhandler(
6160 errors, &errorHandler,
6161 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006162 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006163 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006164 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006165 continue;
6166 }
6167
6168 s += Py_UNICODE_SIZE;
6169#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006170 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006171 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006172 Py_UNICODE uch2;
6173 ((char *) &uch2)[0] = s[0];
6174 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006175 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006176 {
Victor Stinner551ac952011-11-29 22:58:13 +01006177 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006178 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006179 }
6180 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006181#endif
6182
6183 if (unicode_putchar(&v, &outpos, ch) < 0)
6184 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006185 }
6186
Victor Stinner16e6a802011-12-12 13:24:15 +01006187 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006188 goto onError;
6189 Py_XDECREF(errorHandler);
6190 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006191 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006192
Benjamin Peterson29060642009-01-31 22:14:21 +00006193 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006194 Py_XDECREF(v);
6195 Py_XDECREF(errorHandler);
6196 Py_XDECREF(exc);
6197 return NULL;
6198}
6199
Guido van Rossumd57fd912000-03-10 22:53:23 +00006200/* --- Latin-1 Codec ------------------------------------------------------ */
6201
Alexander Belopolsky40018472011-02-26 01:02:56 +00006202PyObject *
6203PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006204 Py_ssize_t size,
6205 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006206{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006207 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006208 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006209}
6210
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006211/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006212static void
6213make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006214 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006215 PyObject *unicode,
6216 Py_ssize_t startpos, Py_ssize_t endpos,
6217 const char *reason)
6218{
6219 if (*exceptionObject == NULL) {
6220 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006221 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006222 encoding, unicode, startpos, endpos, reason);
6223 }
6224 else {
6225 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6226 goto onError;
6227 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6228 goto onError;
6229 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6230 goto onError;
6231 return;
6232 onError:
6233 Py_DECREF(*exceptionObject);
6234 *exceptionObject = NULL;
6235 }
6236}
6237
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006238/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006239static void
6240raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006241 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006242 PyObject *unicode,
6243 Py_ssize_t startpos, Py_ssize_t endpos,
6244 const char *reason)
6245{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006246 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006247 encoding, unicode, startpos, endpos, reason);
6248 if (*exceptionObject != NULL)
6249 PyCodec_StrictErrors(*exceptionObject);
6250}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006251
6252/* error handling callback helper:
6253 build arguments, call the callback and check the arguments,
6254 put the result into newpos and return the replacement string, which
6255 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006256static PyObject *
6257unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006258 PyObject **errorHandler,
6259 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006260 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006261 Py_ssize_t startpos, Py_ssize_t endpos,
6262 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006263{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006264 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006265 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006266 PyObject *restuple;
6267 PyObject *resunicode;
6268
6269 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006270 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006271 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006272 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006273 }
6274
Benjamin Petersonbac79492012-01-14 13:34:47 -05006275 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006276 return NULL;
6277 len = PyUnicode_GET_LENGTH(unicode);
6278
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006279 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006280 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006281 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006282 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006283
6284 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006285 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006286 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006287 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006288 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006289 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006290 Py_DECREF(restuple);
6291 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006292 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006293 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006294 &resunicode, newpos)) {
6295 Py_DECREF(restuple);
6296 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006297 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006298 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6299 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6300 Py_DECREF(restuple);
6301 return NULL;
6302 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006303 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006304 *newpos = len + *newpos;
6305 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006306 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6307 Py_DECREF(restuple);
6308 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006309 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006310 Py_INCREF(resunicode);
6311 Py_DECREF(restuple);
6312 return resunicode;
6313}
6314
Alexander Belopolsky40018472011-02-26 01:02:56 +00006315static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006316unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006317 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006318 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006319{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006320 /* input state */
6321 Py_ssize_t pos=0, size;
6322 int kind;
6323 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006324 /* output object */
6325 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006326 /* pointer into the output */
6327 char *str;
6328 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006329 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006330 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6331 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006332 PyObject *errorHandler = NULL;
6333 PyObject *exc = NULL;
6334 /* the following variable is used for caching string comparisons
6335 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6336 int known_errorHandler = -1;
6337
Benjamin Petersonbac79492012-01-14 13:34:47 -05006338 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006339 return NULL;
6340 size = PyUnicode_GET_LENGTH(unicode);
6341 kind = PyUnicode_KIND(unicode);
6342 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006343 /* allocate enough for a simple encoding without
6344 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006345 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006346 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006347 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006348 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006349 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006350 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006351 ressize = size;
6352
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006353 while (pos < size) {
6354 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006355
Benjamin Peterson29060642009-01-31 22:14:21 +00006356 /* can we encode this? */
6357 if (c<limit) {
6358 /* no overflow check, because we know that the space is enough */
6359 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006360 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006361 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006362 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006363 Py_ssize_t requiredsize;
6364 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006365 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006366 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006367 Py_ssize_t collstart = pos;
6368 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006369 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006370 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006371 ++collend;
6372 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6373 if (known_errorHandler==-1) {
6374 if ((errors==NULL) || (!strcmp(errors, "strict")))
6375 known_errorHandler = 1;
6376 else if (!strcmp(errors, "replace"))
6377 known_errorHandler = 2;
6378 else if (!strcmp(errors, "ignore"))
6379 known_errorHandler = 3;
6380 else if (!strcmp(errors, "xmlcharrefreplace"))
6381 known_errorHandler = 4;
6382 else
6383 known_errorHandler = 0;
6384 }
6385 switch (known_errorHandler) {
6386 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006387 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006388 goto onError;
6389 case 2: /* replace */
6390 while (collstart++<collend)
6391 *str++ = '?'; /* fall through */
6392 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006393 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006394 break;
6395 case 4: /* xmlcharrefreplace */
6396 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006397 /* determine replacement size */
6398 for (i = collstart, repsize = 0; i < collend; ++i) {
6399 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6400 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006401 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006402 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006403 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006404 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006405 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006406 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006407 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006408 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006409 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006410 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006411 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006412 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006413 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006414 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006415 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006416 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006417 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006418 if (requiredsize > ressize) {
6419 if (requiredsize<2*ressize)
6420 requiredsize = 2*ressize;
6421 if (_PyBytes_Resize(&res, requiredsize))
6422 goto onError;
6423 str = PyBytes_AS_STRING(res) + respos;
6424 ressize = requiredsize;
6425 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006426 /* generate replacement */
6427 for (i = collstart; i < collend; ++i) {
6428 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006429 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006430 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006431 break;
6432 default:
6433 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006434 encoding, reason, unicode, &exc,
6435 collstart, collend, &newpos);
6436 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006437 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006438 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006439 if (PyBytes_Check(repunicode)) {
6440 /* Directly copy bytes result to output. */
6441 repsize = PyBytes_Size(repunicode);
6442 if (repsize > 1) {
6443 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006444 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006445 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6446 Py_DECREF(repunicode);
6447 goto onError;
6448 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006449 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006450 ressize += repsize-1;
6451 }
6452 memcpy(str, PyBytes_AsString(repunicode), repsize);
6453 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006454 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006455 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006456 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006457 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006458 /* need more space? (at least enough for what we
6459 have+the replacement+the rest of the string, so
6460 we won't have to check space for encodable characters) */
6461 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006462 repsize = PyUnicode_GET_LENGTH(repunicode);
6463 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006464 if (requiredsize > ressize) {
6465 if (requiredsize<2*ressize)
6466 requiredsize = 2*ressize;
6467 if (_PyBytes_Resize(&res, requiredsize)) {
6468 Py_DECREF(repunicode);
6469 goto onError;
6470 }
6471 str = PyBytes_AS_STRING(res) + respos;
6472 ressize = requiredsize;
6473 }
6474 /* check if there is anything unencodable in the replacement
6475 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006476 for (i = 0; repsize-->0; ++i, ++str) {
6477 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006478 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006479 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006480 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006481 Py_DECREF(repunicode);
6482 goto onError;
6483 }
6484 *str = (char)c;
6485 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006486 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006487 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006488 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006489 }
6490 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006491 /* Resize if we allocated to much */
6492 size = str - PyBytes_AS_STRING(res);
6493 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006494 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006495 if (_PyBytes_Resize(&res, size) < 0)
6496 goto onError;
6497 }
6498
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006499 Py_XDECREF(errorHandler);
6500 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006501 return res;
6502
6503 onError:
6504 Py_XDECREF(res);
6505 Py_XDECREF(errorHandler);
6506 Py_XDECREF(exc);
6507 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006508}
6509
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006510/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006511PyObject *
6512PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006513 Py_ssize_t size,
6514 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006515{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006516 PyObject *result;
6517 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6518 if (unicode == NULL)
6519 return NULL;
6520 result = unicode_encode_ucs1(unicode, errors, 256);
6521 Py_DECREF(unicode);
6522 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006523}
6524
Alexander Belopolsky40018472011-02-26 01:02:56 +00006525PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006526_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006527{
6528 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006529 PyErr_BadArgument();
6530 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006531 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006532 if (PyUnicode_READY(unicode) == -1)
6533 return NULL;
6534 /* Fast path: if it is a one-byte string, construct
6535 bytes object directly. */
6536 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6537 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6538 PyUnicode_GET_LENGTH(unicode));
6539 /* Non-Latin-1 characters present. Defer to above function to
6540 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006541 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006542}
6543
6544PyObject*
6545PyUnicode_AsLatin1String(PyObject *unicode)
6546{
6547 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006548}
6549
6550/* --- 7-bit ASCII Codec -------------------------------------------------- */
6551
Alexander Belopolsky40018472011-02-26 01:02:56 +00006552PyObject *
6553PyUnicode_DecodeASCII(const char *s,
6554 Py_ssize_t size,
6555 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006556{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006557 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006558 PyObject *unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006559 int kind;
6560 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006561 Py_ssize_t startinpos;
6562 Py_ssize_t endinpos;
6563 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006564 const char *e;
6565 PyObject *errorHandler = NULL;
6566 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006567
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006568 if (size == 0) {
6569 Py_INCREF(unicode_empty);
6570 return unicode_empty;
6571 }
6572
Guido van Rossumd57fd912000-03-10 22:53:23 +00006573 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006574 if (size == 1 && (unsigned char)s[0] < 128)
6575 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006576
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006577 unicode = PyUnicode_New(size, 127);
6578 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006579 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006580
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006581 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006582 data = PyUnicode_1BYTE_DATA(unicode);
6583 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
6584 if (outpos == size)
6585 return unicode;
6586
6587 s += outpos;
6588 kind = PyUnicode_1BYTE_KIND;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006589 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006590 register unsigned char c = (unsigned char)*s;
6591 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006592 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006593 ++s;
6594 }
6595 else {
6596 startinpos = s-starts;
6597 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006598 if (unicode_decode_call_errorhandler(
6599 errors, &errorHandler,
6600 "ascii", "ordinal not in range(128)",
6601 &starts, &e, &startinpos, &endinpos, &exc, &s,
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006602 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006603 goto onError;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006604 kind = PyUnicode_KIND(unicode);
6605 data = PyUnicode_DATA(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00006606 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006607 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006608 if (unicode_resize(&unicode, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006609 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006610 Py_XDECREF(errorHandler);
6611 Py_XDECREF(exc);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006612 assert(_PyUnicode_CheckConsistency(unicode, 1));
6613 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00006614
Benjamin Peterson29060642009-01-31 22:14:21 +00006615 onError:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006616 Py_XDECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006617 Py_XDECREF(errorHandler);
6618 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006619 return NULL;
6620}
6621
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006622/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006623PyObject *
6624PyUnicode_EncodeASCII(const Py_UNICODE *p,
6625 Py_ssize_t size,
6626 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006627{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006628 PyObject *result;
6629 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6630 if (unicode == NULL)
6631 return NULL;
6632 result = unicode_encode_ucs1(unicode, errors, 128);
6633 Py_DECREF(unicode);
6634 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006635}
6636
Alexander Belopolsky40018472011-02-26 01:02:56 +00006637PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006638_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006639{
6640 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006641 PyErr_BadArgument();
6642 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006643 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006644 if (PyUnicode_READY(unicode) == -1)
6645 return NULL;
6646 /* Fast path: if it is an ASCII-only string, construct bytes object
6647 directly. Else defer to above function to raise the exception. */
6648 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6649 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6650 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006651 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006652}
6653
6654PyObject *
6655PyUnicode_AsASCIIString(PyObject *unicode)
6656{
6657 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006658}
6659
Victor Stinner99b95382011-07-04 14:23:54 +02006660#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006661
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006662/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006663
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006664#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006665#define NEED_RETRY
6666#endif
6667
Victor Stinner3a50e702011-10-18 21:21:00 +02006668#ifndef WC_ERR_INVALID_CHARS
6669# define WC_ERR_INVALID_CHARS 0x0080
6670#endif
6671
6672static char*
6673code_page_name(UINT code_page, PyObject **obj)
6674{
6675 *obj = NULL;
6676 if (code_page == CP_ACP)
6677 return "mbcs";
6678 if (code_page == CP_UTF7)
6679 return "CP_UTF7";
6680 if (code_page == CP_UTF8)
6681 return "CP_UTF8";
6682
6683 *obj = PyBytes_FromFormat("cp%u", code_page);
6684 if (*obj == NULL)
6685 return NULL;
6686 return PyBytes_AS_STRING(*obj);
6687}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006688
Alexander Belopolsky40018472011-02-26 01:02:56 +00006689static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006690is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006691{
6692 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006693 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006694
Victor Stinner3a50e702011-10-18 21:21:00 +02006695 if (!IsDBCSLeadByteEx(code_page, *curr))
6696 return 0;
6697
6698 prev = CharPrevExA(code_page, s, curr, 0);
6699 if (prev == curr)
6700 return 1;
6701 /* FIXME: This code is limited to "true" double-byte encodings,
6702 as it assumes an incomplete character consists of a single
6703 byte. */
6704 if (curr - prev == 2)
6705 return 1;
6706 if (!IsDBCSLeadByteEx(code_page, *prev))
6707 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006708 return 0;
6709}
6710
Victor Stinner3a50e702011-10-18 21:21:00 +02006711static DWORD
6712decode_code_page_flags(UINT code_page)
6713{
6714 if (code_page == CP_UTF7) {
6715 /* The CP_UTF7 decoder only supports flags=0 */
6716 return 0;
6717 }
6718 else
6719 return MB_ERR_INVALID_CHARS;
6720}
6721
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006722/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006723 * Decode a byte string from a Windows code page into unicode object in strict
6724 * mode.
6725 *
6726 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6727 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006728 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006729static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006730decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006731 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006732 const char *in,
6733 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006734{
Victor Stinner3a50e702011-10-18 21:21:00 +02006735 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006736 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006737 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006738
6739 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006740 assert(insize > 0);
6741 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6742 if (outsize <= 0)
6743 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006744
6745 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006746 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006747 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006748 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006749 if (*v == NULL)
6750 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006751 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006752 }
6753 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006754 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006755 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006756 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006757 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006758 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006759 }
6760
6761 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006762 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6763 if (outsize <= 0)
6764 goto error;
6765 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006766
Victor Stinner3a50e702011-10-18 21:21:00 +02006767error:
6768 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6769 return -2;
6770 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006771 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006772}
6773
Victor Stinner3a50e702011-10-18 21:21:00 +02006774/*
6775 * Decode a byte string from a code page into unicode object with an error
6776 * handler.
6777 *
6778 * Returns consumed size if succeed, or raise a WindowsError or
6779 * UnicodeDecodeError exception and returns -1 on error.
6780 */
6781static int
6782decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006783 PyObject **v,
6784 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006785 const char *errors)
6786{
6787 const char *startin = in;
6788 const char *endin = in + size;
6789 const DWORD flags = decode_code_page_flags(code_page);
6790 /* Ideally, we should get reason from FormatMessage. This is the Windows
6791 2000 English version of the message. */
6792 const char *reason = "No mapping for the Unicode character exists "
6793 "in the target code page.";
6794 /* each step cannot decode more than 1 character, but a character can be
6795 represented as a surrogate pair */
6796 wchar_t buffer[2], *startout, *out;
6797 int insize, outsize;
6798 PyObject *errorHandler = NULL;
6799 PyObject *exc = NULL;
6800 PyObject *encoding_obj = NULL;
6801 char *encoding;
6802 DWORD err;
6803 int ret = -1;
6804
6805 assert(size > 0);
6806
6807 encoding = code_page_name(code_page, &encoding_obj);
6808 if (encoding == NULL)
6809 return -1;
6810
6811 if (errors == NULL || strcmp(errors, "strict") == 0) {
6812 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6813 UnicodeDecodeError. */
6814 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6815 if (exc != NULL) {
6816 PyCodec_StrictErrors(exc);
6817 Py_CLEAR(exc);
6818 }
6819 goto error;
6820 }
6821
6822 if (*v == NULL) {
6823 /* Create unicode object */
6824 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6825 PyErr_NoMemory();
6826 goto error;
6827 }
Victor Stinnerab595942011-12-17 04:59:06 +01006828 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006829 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006830 if (*v == NULL)
6831 goto error;
6832 startout = PyUnicode_AS_UNICODE(*v);
6833 }
6834 else {
6835 /* Extend unicode object */
6836 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6837 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6838 PyErr_NoMemory();
6839 goto error;
6840 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006841 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006842 goto error;
6843 startout = PyUnicode_AS_UNICODE(*v) + n;
6844 }
6845
6846 /* Decode the byte string character per character */
6847 out = startout;
6848 while (in < endin)
6849 {
6850 /* Decode a character */
6851 insize = 1;
6852 do
6853 {
6854 outsize = MultiByteToWideChar(code_page, flags,
6855 in, insize,
6856 buffer, Py_ARRAY_LENGTH(buffer));
6857 if (outsize > 0)
6858 break;
6859 err = GetLastError();
6860 if (err != ERROR_NO_UNICODE_TRANSLATION
6861 && err != ERROR_INSUFFICIENT_BUFFER)
6862 {
6863 PyErr_SetFromWindowsErr(0);
6864 goto error;
6865 }
6866 insize++;
6867 }
6868 /* 4=maximum length of a UTF-8 sequence */
6869 while (insize <= 4 && (in + insize) <= endin);
6870
6871 if (outsize <= 0) {
6872 Py_ssize_t startinpos, endinpos, outpos;
6873
6874 startinpos = in - startin;
6875 endinpos = startinpos + 1;
6876 outpos = out - PyUnicode_AS_UNICODE(*v);
6877 if (unicode_decode_call_errorhandler(
6878 errors, &errorHandler,
6879 encoding, reason,
6880 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006881 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006882 {
6883 goto error;
6884 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006885 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006886 }
6887 else {
6888 in += insize;
6889 memcpy(out, buffer, outsize * sizeof(wchar_t));
6890 out += outsize;
6891 }
6892 }
6893
6894 /* write a NUL character at the end */
6895 *out = 0;
6896
6897 /* Extend unicode object */
6898 outsize = out - startout;
6899 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006900 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006901 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01006902 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02006903
6904error:
6905 Py_XDECREF(encoding_obj);
6906 Py_XDECREF(errorHandler);
6907 Py_XDECREF(exc);
6908 return ret;
6909}
6910
Victor Stinner3a50e702011-10-18 21:21:00 +02006911static PyObject *
6912decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006913 const char *s, Py_ssize_t size,
6914 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006915{
Victor Stinner76a31a62011-11-04 00:05:13 +01006916 PyObject *v = NULL;
6917 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006918
Victor Stinner3a50e702011-10-18 21:21:00 +02006919 if (code_page < 0) {
6920 PyErr_SetString(PyExc_ValueError, "invalid code page number");
6921 return NULL;
6922 }
6923
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006924 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006925 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006926
Victor Stinner76a31a62011-11-04 00:05:13 +01006927 do
6928 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006929#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01006930 if (size > INT_MAX) {
6931 chunk_size = INT_MAX;
6932 final = 0;
6933 done = 0;
6934 }
6935 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006936#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01006937 {
6938 chunk_size = (int)size;
6939 final = (consumed == NULL);
6940 done = 1;
6941 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006942
Victor Stinner76a31a62011-11-04 00:05:13 +01006943 /* Skip trailing lead-byte unless 'final' is set */
6944 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
6945 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006946
Victor Stinner76a31a62011-11-04 00:05:13 +01006947 if (chunk_size == 0 && done) {
6948 if (v != NULL)
6949 break;
6950 Py_INCREF(unicode_empty);
6951 return unicode_empty;
6952 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006953
Victor Stinner76a31a62011-11-04 00:05:13 +01006954
6955 converted = decode_code_page_strict(code_page, &v,
6956 s, chunk_size);
6957 if (converted == -2)
6958 converted = decode_code_page_errors(code_page, &v,
6959 s, chunk_size,
6960 errors);
6961 assert(converted != 0);
6962
6963 if (converted < 0) {
6964 Py_XDECREF(v);
6965 return NULL;
6966 }
6967
6968 if (consumed)
6969 *consumed += converted;
6970
6971 s += converted;
6972 size -= converted;
6973 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02006974
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006975 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006976}
6977
Alexander Belopolsky40018472011-02-26 01:02:56 +00006978PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02006979PyUnicode_DecodeCodePageStateful(int code_page,
6980 const char *s,
6981 Py_ssize_t size,
6982 const char *errors,
6983 Py_ssize_t *consumed)
6984{
6985 return decode_code_page_stateful(code_page, s, size, errors, consumed);
6986}
6987
6988PyObject *
6989PyUnicode_DecodeMBCSStateful(const char *s,
6990 Py_ssize_t size,
6991 const char *errors,
6992 Py_ssize_t *consumed)
6993{
6994 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
6995}
6996
6997PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006998PyUnicode_DecodeMBCS(const char *s,
6999 Py_ssize_t size,
7000 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007001{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007002 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7003}
7004
Victor Stinner3a50e702011-10-18 21:21:00 +02007005static DWORD
7006encode_code_page_flags(UINT code_page, const char *errors)
7007{
7008 if (code_page == CP_UTF8) {
7009 if (winver.dwMajorVersion >= 6)
7010 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7011 and later */
7012 return WC_ERR_INVALID_CHARS;
7013 else
7014 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7015 return 0;
7016 }
7017 else if (code_page == CP_UTF7) {
7018 /* CP_UTF7 only supports flags=0 */
7019 return 0;
7020 }
7021 else {
7022 if (errors != NULL && strcmp(errors, "replace") == 0)
7023 return 0;
7024 else
7025 return WC_NO_BEST_FIT_CHARS;
7026 }
7027}
7028
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007029/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007030 * Encode a Unicode string to a Windows code page into a byte string in strict
7031 * mode.
7032 *
7033 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7034 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007035 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007036static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007037encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007038 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007039 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007040{
Victor Stinner554f3f02010-06-16 23:33:54 +00007041 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007042 BOOL *pusedDefaultChar = &usedDefaultChar;
7043 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007044 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007045 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007046 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007047 const DWORD flags = encode_code_page_flags(code_page, NULL);
7048 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007049 /* Create a substring so that we can get the UTF-16 representation
7050 of just the slice under consideration. */
7051 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007052
Martin v. Löwis3d325192011-11-04 18:23:06 +01007053 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007054
Victor Stinner3a50e702011-10-18 21:21:00 +02007055 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007056 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007057 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007058 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007059
Victor Stinner2fc507f2011-11-04 20:06:39 +01007060 substring = PyUnicode_Substring(unicode, offset, offset+len);
7061 if (substring == NULL)
7062 return -1;
7063 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7064 if (p == NULL) {
7065 Py_DECREF(substring);
7066 return -1;
7067 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007068
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007069 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007070 outsize = WideCharToMultiByte(code_page, flags,
7071 p, size,
7072 NULL, 0,
7073 NULL, pusedDefaultChar);
7074 if (outsize <= 0)
7075 goto error;
7076 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007077 if (pusedDefaultChar && *pusedDefaultChar) {
7078 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007079 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007080 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007081
Victor Stinner3a50e702011-10-18 21:21:00 +02007082 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007083 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007084 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007085 if (*outbytes == NULL) {
7086 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007087 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007088 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007089 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007090 }
7091 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007092 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007093 const Py_ssize_t n = PyBytes_Size(*outbytes);
7094 if (outsize > PY_SSIZE_T_MAX - n) {
7095 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007096 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007097 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007098 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007099 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7100 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007101 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007102 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007103 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007104 }
7105
7106 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007107 outsize = WideCharToMultiByte(code_page, flags,
7108 p, size,
7109 out, outsize,
7110 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007111 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007112 if (outsize <= 0)
7113 goto error;
7114 if (pusedDefaultChar && *pusedDefaultChar)
7115 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007116 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007117
Victor Stinner3a50e702011-10-18 21:21:00 +02007118error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007119 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007120 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7121 return -2;
7122 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007123 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007124}
7125
Victor Stinner3a50e702011-10-18 21:21:00 +02007126/*
7127 * Encode a Unicode string to a Windows code page into a byte string using a
7128 * error handler.
7129 *
7130 * Returns consumed characters if succeed, or raise a WindowsError and returns
7131 * -1 on other error.
7132 */
7133static int
7134encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007135 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007136 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007137{
Victor Stinner3a50e702011-10-18 21:21:00 +02007138 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007139 Py_ssize_t pos = unicode_offset;
7140 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007141 /* Ideally, we should get reason from FormatMessage. This is the Windows
7142 2000 English version of the message. */
7143 const char *reason = "invalid character";
7144 /* 4=maximum length of a UTF-8 sequence */
7145 char buffer[4];
7146 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7147 Py_ssize_t outsize;
7148 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007149 PyObject *errorHandler = NULL;
7150 PyObject *exc = NULL;
7151 PyObject *encoding_obj = NULL;
7152 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007153 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007154 PyObject *rep;
7155 int ret = -1;
7156
7157 assert(insize > 0);
7158
7159 encoding = code_page_name(code_page, &encoding_obj);
7160 if (encoding == NULL)
7161 return -1;
7162
7163 if (errors == NULL || strcmp(errors, "strict") == 0) {
7164 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7165 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007166 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007167 if (exc != NULL) {
7168 PyCodec_StrictErrors(exc);
7169 Py_DECREF(exc);
7170 }
7171 Py_XDECREF(encoding_obj);
7172 return -1;
7173 }
7174
7175 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7176 pusedDefaultChar = &usedDefaultChar;
7177 else
7178 pusedDefaultChar = NULL;
7179
7180 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7181 PyErr_NoMemory();
7182 goto error;
7183 }
7184 outsize = insize * Py_ARRAY_LENGTH(buffer);
7185
7186 if (*outbytes == NULL) {
7187 /* Create string object */
7188 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7189 if (*outbytes == NULL)
7190 goto error;
7191 out = PyBytes_AS_STRING(*outbytes);
7192 }
7193 else {
7194 /* Extend string object */
7195 Py_ssize_t n = PyBytes_Size(*outbytes);
7196 if (n > PY_SSIZE_T_MAX - outsize) {
7197 PyErr_NoMemory();
7198 goto error;
7199 }
7200 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7201 goto error;
7202 out = PyBytes_AS_STRING(*outbytes) + n;
7203 }
7204
7205 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007206 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007208 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7209 wchar_t chars[2];
7210 int charsize;
7211 if (ch < 0x10000) {
7212 chars[0] = (wchar_t)ch;
7213 charsize = 1;
7214 }
7215 else {
7216 ch -= 0x10000;
7217 chars[0] = 0xd800 + (ch >> 10);
7218 chars[1] = 0xdc00 + (ch & 0x3ff);
7219 charsize = 2;
7220 }
7221
Victor Stinner3a50e702011-10-18 21:21:00 +02007222 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007223 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007224 buffer, Py_ARRAY_LENGTH(buffer),
7225 NULL, pusedDefaultChar);
7226 if (outsize > 0) {
7227 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7228 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007229 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007230 memcpy(out, buffer, outsize);
7231 out += outsize;
7232 continue;
7233 }
7234 }
7235 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7236 PyErr_SetFromWindowsErr(0);
7237 goto error;
7238 }
7239
Victor Stinner3a50e702011-10-18 21:21:00 +02007240 rep = unicode_encode_call_errorhandler(
7241 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007242 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007243 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007244 if (rep == NULL)
7245 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007246 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007247
7248 if (PyBytes_Check(rep)) {
7249 outsize = PyBytes_GET_SIZE(rep);
7250 if (outsize != 1) {
7251 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7252 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7253 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7254 Py_DECREF(rep);
7255 goto error;
7256 }
7257 out = PyBytes_AS_STRING(*outbytes) + offset;
7258 }
7259 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7260 out += outsize;
7261 }
7262 else {
7263 Py_ssize_t i;
7264 enum PyUnicode_Kind kind;
7265 void *data;
7266
Benjamin Petersonbac79492012-01-14 13:34:47 -05007267 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007268 Py_DECREF(rep);
7269 goto error;
7270 }
7271
7272 outsize = PyUnicode_GET_LENGTH(rep);
7273 if (outsize != 1) {
7274 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7275 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7276 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7277 Py_DECREF(rep);
7278 goto error;
7279 }
7280 out = PyBytes_AS_STRING(*outbytes) + offset;
7281 }
7282 kind = PyUnicode_KIND(rep);
7283 data = PyUnicode_DATA(rep);
7284 for (i=0; i < outsize; i++) {
7285 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7286 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007287 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007288 encoding, unicode,
7289 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007290 "unable to encode error handler result to ASCII");
7291 Py_DECREF(rep);
7292 goto error;
7293 }
7294 *out = (unsigned char)ch;
7295 out++;
7296 }
7297 }
7298 Py_DECREF(rep);
7299 }
7300 /* write a NUL byte */
7301 *out = 0;
7302 outsize = out - PyBytes_AS_STRING(*outbytes);
7303 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7304 if (_PyBytes_Resize(outbytes, outsize) < 0)
7305 goto error;
7306 ret = 0;
7307
7308error:
7309 Py_XDECREF(encoding_obj);
7310 Py_XDECREF(errorHandler);
7311 Py_XDECREF(exc);
7312 return ret;
7313}
7314
Victor Stinner3a50e702011-10-18 21:21:00 +02007315static PyObject *
7316encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007317 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007318 const char *errors)
7319{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007320 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007321 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007322 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007323 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007324
Benjamin Petersonbac79492012-01-14 13:34:47 -05007325 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007326 return NULL;
7327 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007328
Victor Stinner3a50e702011-10-18 21:21:00 +02007329 if (code_page < 0) {
7330 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7331 return NULL;
7332 }
7333
Martin v. Löwis3d325192011-11-04 18:23:06 +01007334 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007335 return PyBytes_FromStringAndSize(NULL, 0);
7336
Victor Stinner7581cef2011-11-03 22:32:33 +01007337 offset = 0;
7338 do
7339 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007340#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007341 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007342 chunks. */
7343 if (len > INT_MAX/2) {
7344 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007345 done = 0;
7346 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007347 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007348#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007349 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007350 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007351 done = 1;
7352 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007353
Victor Stinner76a31a62011-11-04 00:05:13 +01007354 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007355 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007356 errors);
7357 if (ret == -2)
7358 ret = encode_code_page_errors(code_page, &outbytes,
7359 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007360 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007361 if (ret < 0) {
7362 Py_XDECREF(outbytes);
7363 return NULL;
7364 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007365
Victor Stinner7581cef2011-11-03 22:32:33 +01007366 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007367 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007368 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007369
Victor Stinner3a50e702011-10-18 21:21:00 +02007370 return outbytes;
7371}
7372
7373PyObject *
7374PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7375 Py_ssize_t size,
7376 const char *errors)
7377{
Victor Stinner7581cef2011-11-03 22:32:33 +01007378 PyObject *unicode, *res;
7379 unicode = PyUnicode_FromUnicode(p, size);
7380 if (unicode == NULL)
7381 return NULL;
7382 res = encode_code_page(CP_ACP, unicode, errors);
7383 Py_DECREF(unicode);
7384 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007385}
7386
7387PyObject *
7388PyUnicode_EncodeCodePage(int code_page,
7389 PyObject *unicode,
7390 const char *errors)
7391{
Victor Stinner7581cef2011-11-03 22:32:33 +01007392 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007393}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007394
Alexander Belopolsky40018472011-02-26 01:02:56 +00007395PyObject *
7396PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007397{
7398 if (!PyUnicode_Check(unicode)) {
7399 PyErr_BadArgument();
7400 return NULL;
7401 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007402 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007403}
7404
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007405#undef NEED_RETRY
7406
Victor Stinner99b95382011-07-04 14:23:54 +02007407#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007408
Guido van Rossumd57fd912000-03-10 22:53:23 +00007409/* --- Character Mapping Codec -------------------------------------------- */
7410
Alexander Belopolsky40018472011-02-26 01:02:56 +00007411PyObject *
7412PyUnicode_DecodeCharmap(const char *s,
7413 Py_ssize_t size,
7414 PyObject *mapping,
7415 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007416{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007417 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007418 Py_ssize_t startinpos;
7419 Py_ssize_t endinpos;
7420 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007421 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007422 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007423 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007424 PyObject *errorHandler = NULL;
7425 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007426
Guido van Rossumd57fd912000-03-10 22:53:23 +00007427 /* Default to Latin-1 */
7428 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007429 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007430
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007431 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007432 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007433 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007434 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007435 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007436 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007437 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007438 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007439 Py_ssize_t maplen;
7440 enum PyUnicode_Kind kind;
7441 void *data;
7442 Py_UCS4 x;
7443
Benjamin Petersonbac79492012-01-14 13:34:47 -05007444 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007445 return NULL;
7446
7447 maplen = PyUnicode_GET_LENGTH(mapping);
7448 data = PyUnicode_DATA(mapping);
7449 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007450 while (s < e) {
7451 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007452
Benjamin Peterson29060642009-01-31 22:14:21 +00007453 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007454 x = PyUnicode_READ(kind, data, ch);
7455 else
7456 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007457
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007458 if (x == 0xfffe)
7459 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007460 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007461 startinpos = s-starts;
7462 endinpos = startinpos+1;
7463 if (unicode_decode_call_errorhandler(
7464 errors, &errorHandler,
7465 "charmap", "character maps to <undefined>",
7466 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007467 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007468 goto onError;
7469 }
7470 continue;
7471 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007472
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007473 if (unicode_putchar(&v, &outpos, x) < 0)
7474 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007475 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007476 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007477 }
7478 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007479 while (s < e) {
7480 unsigned char ch = *s;
7481 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007482
Benjamin Peterson29060642009-01-31 22:14:21 +00007483 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7484 w = PyLong_FromLong((long)ch);
7485 if (w == NULL)
7486 goto onError;
7487 x = PyObject_GetItem(mapping, w);
7488 Py_DECREF(w);
7489 if (x == NULL) {
7490 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7491 /* No mapping found means: mapping is undefined. */
7492 PyErr_Clear();
7493 x = Py_None;
7494 Py_INCREF(x);
7495 } else
7496 goto onError;
7497 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007498
Benjamin Peterson29060642009-01-31 22:14:21 +00007499 /* Apply mapping */
7500 if (PyLong_Check(x)) {
7501 long value = PyLong_AS_LONG(x);
7502 if (value < 0 || value > 65535) {
7503 PyErr_SetString(PyExc_TypeError,
7504 "character mapping must be in range(65536)");
7505 Py_DECREF(x);
7506 goto onError;
7507 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007508 if (unicode_putchar(&v, &outpos, value) < 0)
7509 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007510 }
7511 else if (x == Py_None) {
7512 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007513 startinpos = s-starts;
7514 endinpos = startinpos+1;
7515 if (unicode_decode_call_errorhandler(
7516 errors, &errorHandler,
7517 "charmap", "character maps to <undefined>",
7518 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007519 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007520 Py_DECREF(x);
7521 goto onError;
7522 }
7523 Py_DECREF(x);
7524 continue;
7525 }
7526 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007527 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007528
Benjamin Petersonbac79492012-01-14 13:34:47 -05007529 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007530 goto onError;
7531 targetsize = PyUnicode_GET_LENGTH(x);
7532
7533 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007534 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007535 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007536 PyUnicode_READ_CHAR(x, 0)) < 0)
7537 goto onError;
7538 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007539 else if (targetsize > 1) {
7540 /* 1-n mapping */
7541 if (targetsize > extrachars) {
7542 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007543 Py_ssize_t needed = (targetsize - extrachars) + \
7544 (targetsize << 2);
7545 extrachars += needed;
7546 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007547 if (unicode_resize(&v,
7548 PyUnicode_GET_LENGTH(v) + needed) < 0)
7549 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007550 Py_DECREF(x);
7551 goto onError;
7552 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007553 }
Victor Stinner1b487b42012-05-03 12:29:04 +02007554 if (unicode_widen(&v, outpos, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007555 goto onError;
7556 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7557 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007558 extrachars -= targetsize;
7559 }
7560 /* 1-0 mapping: skip the character */
7561 }
7562 else {
7563 /* wrong return value */
7564 PyErr_SetString(PyExc_TypeError,
7565 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007566 Py_DECREF(x);
7567 goto onError;
7568 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007569 Py_DECREF(x);
7570 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007571 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007572 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007573 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007574 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007575 Py_XDECREF(errorHandler);
7576 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007577 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007578
Benjamin Peterson29060642009-01-31 22:14:21 +00007579 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007580 Py_XDECREF(errorHandler);
7581 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007582 Py_XDECREF(v);
7583 return NULL;
7584}
7585
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007586/* Charmap encoding: the lookup table */
7587
Alexander Belopolsky40018472011-02-26 01:02:56 +00007588struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007589 PyObject_HEAD
7590 unsigned char level1[32];
7591 int count2, count3;
7592 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007593};
7594
7595static PyObject*
7596encoding_map_size(PyObject *obj, PyObject* args)
7597{
7598 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007599 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007600 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007601}
7602
7603static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007604 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007605 PyDoc_STR("Return the size (in bytes) of this object") },
7606 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007607};
7608
7609static void
7610encoding_map_dealloc(PyObject* o)
7611{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007612 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007613}
7614
7615static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007616 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007617 "EncodingMap", /*tp_name*/
7618 sizeof(struct encoding_map), /*tp_basicsize*/
7619 0, /*tp_itemsize*/
7620 /* methods */
7621 encoding_map_dealloc, /*tp_dealloc*/
7622 0, /*tp_print*/
7623 0, /*tp_getattr*/
7624 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007625 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007626 0, /*tp_repr*/
7627 0, /*tp_as_number*/
7628 0, /*tp_as_sequence*/
7629 0, /*tp_as_mapping*/
7630 0, /*tp_hash*/
7631 0, /*tp_call*/
7632 0, /*tp_str*/
7633 0, /*tp_getattro*/
7634 0, /*tp_setattro*/
7635 0, /*tp_as_buffer*/
7636 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7637 0, /*tp_doc*/
7638 0, /*tp_traverse*/
7639 0, /*tp_clear*/
7640 0, /*tp_richcompare*/
7641 0, /*tp_weaklistoffset*/
7642 0, /*tp_iter*/
7643 0, /*tp_iternext*/
7644 encoding_map_methods, /*tp_methods*/
7645 0, /*tp_members*/
7646 0, /*tp_getset*/
7647 0, /*tp_base*/
7648 0, /*tp_dict*/
7649 0, /*tp_descr_get*/
7650 0, /*tp_descr_set*/
7651 0, /*tp_dictoffset*/
7652 0, /*tp_init*/
7653 0, /*tp_alloc*/
7654 0, /*tp_new*/
7655 0, /*tp_free*/
7656 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007657};
7658
7659PyObject*
7660PyUnicode_BuildEncodingMap(PyObject* string)
7661{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007662 PyObject *result;
7663 struct encoding_map *mresult;
7664 int i;
7665 int need_dict = 0;
7666 unsigned char level1[32];
7667 unsigned char level2[512];
7668 unsigned char *mlevel1, *mlevel2, *mlevel3;
7669 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007670 int kind;
7671 void *data;
7672 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007673
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007674 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007675 PyErr_BadArgument();
7676 return NULL;
7677 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007678 kind = PyUnicode_KIND(string);
7679 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007680 memset(level1, 0xFF, sizeof level1);
7681 memset(level2, 0xFF, sizeof level2);
7682
7683 /* If there isn't a one-to-one mapping of NULL to \0,
7684 or if there are non-BMP characters, we need to use
7685 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007686 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007687 need_dict = 1;
7688 for (i = 1; i < 256; i++) {
7689 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007690 ch = PyUnicode_READ(kind, data, i);
7691 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007692 need_dict = 1;
7693 break;
7694 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007695 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007696 /* unmapped character */
7697 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007698 l1 = ch >> 11;
7699 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007700 if (level1[l1] == 0xFF)
7701 level1[l1] = count2++;
7702 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007703 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007704 }
7705
7706 if (count2 >= 0xFF || count3 >= 0xFF)
7707 need_dict = 1;
7708
7709 if (need_dict) {
7710 PyObject *result = PyDict_New();
7711 PyObject *key, *value;
7712 if (!result)
7713 return NULL;
7714 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007715 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007716 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007717 if (!key || !value)
7718 goto failed1;
7719 if (PyDict_SetItem(result, key, value) == -1)
7720 goto failed1;
7721 Py_DECREF(key);
7722 Py_DECREF(value);
7723 }
7724 return result;
7725 failed1:
7726 Py_XDECREF(key);
7727 Py_XDECREF(value);
7728 Py_DECREF(result);
7729 return NULL;
7730 }
7731
7732 /* Create a three-level trie */
7733 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7734 16*count2 + 128*count3 - 1);
7735 if (!result)
7736 return PyErr_NoMemory();
7737 PyObject_Init(result, &EncodingMapType);
7738 mresult = (struct encoding_map*)result;
7739 mresult->count2 = count2;
7740 mresult->count3 = count3;
7741 mlevel1 = mresult->level1;
7742 mlevel2 = mresult->level23;
7743 mlevel3 = mresult->level23 + 16*count2;
7744 memcpy(mlevel1, level1, 32);
7745 memset(mlevel2, 0xFF, 16*count2);
7746 memset(mlevel3, 0, 128*count3);
7747 count3 = 0;
7748 for (i = 1; i < 256; i++) {
7749 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007750 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007751 /* unmapped character */
7752 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007753 o1 = PyUnicode_READ(kind, data, i)>>11;
7754 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007755 i2 = 16*mlevel1[o1] + o2;
7756 if (mlevel2[i2] == 0xFF)
7757 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007758 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007759 i3 = 128*mlevel2[i2] + o3;
7760 mlevel3[i3] = i;
7761 }
7762 return result;
7763}
7764
7765static int
Victor Stinner22168992011-11-20 17:09:18 +01007766encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007767{
7768 struct encoding_map *map = (struct encoding_map*)mapping;
7769 int l1 = c>>11;
7770 int l2 = (c>>7) & 0xF;
7771 int l3 = c & 0x7F;
7772 int i;
7773
Victor Stinner22168992011-11-20 17:09:18 +01007774 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007775 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007776 if (c == 0)
7777 return 0;
7778 /* level 1*/
7779 i = map->level1[l1];
7780 if (i == 0xFF) {
7781 return -1;
7782 }
7783 /* level 2*/
7784 i = map->level23[16*i+l2];
7785 if (i == 0xFF) {
7786 return -1;
7787 }
7788 /* level 3 */
7789 i = map->level23[16*map->count2 + 128*i + l3];
7790 if (i == 0) {
7791 return -1;
7792 }
7793 return i;
7794}
7795
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007796/* Lookup the character ch in the mapping. If the character
7797 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007798 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007799static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007800charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007801{
Christian Heimes217cfd12007-12-02 14:31:20 +00007802 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007803 PyObject *x;
7804
7805 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007806 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007807 x = PyObject_GetItem(mapping, w);
7808 Py_DECREF(w);
7809 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007810 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7811 /* No mapping found means: mapping is undefined. */
7812 PyErr_Clear();
7813 x = Py_None;
7814 Py_INCREF(x);
7815 return x;
7816 } else
7817 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007818 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007819 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007820 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007821 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007822 long value = PyLong_AS_LONG(x);
7823 if (value < 0 || value > 255) {
7824 PyErr_SetString(PyExc_TypeError,
7825 "character mapping must be in range(256)");
7826 Py_DECREF(x);
7827 return NULL;
7828 }
7829 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007830 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007831 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007832 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007833 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007834 /* wrong return value */
7835 PyErr_Format(PyExc_TypeError,
7836 "character mapping must return integer, bytes or None, not %.400s",
7837 x->ob_type->tp_name);
7838 Py_DECREF(x);
7839 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007840 }
7841}
7842
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007843static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007844charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007845{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007846 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7847 /* exponentially overallocate to minimize reallocations */
7848 if (requiredsize < 2*outsize)
7849 requiredsize = 2*outsize;
7850 if (_PyBytes_Resize(outobj, requiredsize))
7851 return -1;
7852 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007853}
7854
Benjamin Peterson14339b62009-01-31 16:36:08 +00007855typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007856 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007857} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007858/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007859 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007860 space is available. Return a new reference to the object that
7861 was put in the output buffer, or Py_None, if the mapping was undefined
7862 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007863 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007864static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01007865charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007866 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007867{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007868 PyObject *rep;
7869 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007870 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007871
Christian Heimes90aa7642007-12-19 02:45:37 +00007872 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007873 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007874 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007875 if (res == -1)
7876 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007877 if (outsize<requiredsize)
7878 if (charmapencode_resize(outobj, outpos, requiredsize))
7879 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007880 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007881 outstart[(*outpos)++] = (char)res;
7882 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007883 }
7884
7885 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007886 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007887 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007888 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007889 Py_DECREF(rep);
7890 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007891 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007892 if (PyLong_Check(rep)) {
7893 Py_ssize_t requiredsize = *outpos+1;
7894 if (outsize<requiredsize)
7895 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7896 Py_DECREF(rep);
7897 return enc_EXCEPTION;
7898 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007899 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007900 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007901 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007902 else {
7903 const char *repchars = PyBytes_AS_STRING(rep);
7904 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7905 Py_ssize_t requiredsize = *outpos+repsize;
7906 if (outsize<requiredsize)
7907 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7908 Py_DECREF(rep);
7909 return enc_EXCEPTION;
7910 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007911 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007912 memcpy(outstart + *outpos, repchars, repsize);
7913 *outpos += repsize;
7914 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007915 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007916 Py_DECREF(rep);
7917 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007918}
7919
7920/* handle an error in PyUnicode_EncodeCharmap
7921 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007922static int
7923charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007924 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007925 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007926 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007927 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007928{
7929 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007930 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007931 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01007932 enum PyUnicode_Kind kind;
7933 void *data;
7934 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007935 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007936 Py_ssize_t collstartpos = *inpos;
7937 Py_ssize_t collendpos = *inpos+1;
7938 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007939 char *encoding = "charmap";
7940 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007941 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007942 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05007943 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007944
Benjamin Petersonbac79492012-01-14 13:34:47 -05007945 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007946 return -1;
7947 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007948 /* find all unencodable characters */
7949 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007950 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007951 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007952 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05007953 val = encoding_map_lookup(ch, mapping);
7954 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007955 break;
7956 ++collendpos;
7957 continue;
7958 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007959
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007960 ch = PyUnicode_READ_CHAR(unicode, collendpos);
7961 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007962 if (rep==NULL)
7963 return -1;
7964 else if (rep!=Py_None) {
7965 Py_DECREF(rep);
7966 break;
7967 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007968 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007969 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007970 }
7971 /* cache callback name lookup
7972 * (if not done yet, i.e. it's the first error) */
7973 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007974 if ((errors==NULL) || (!strcmp(errors, "strict")))
7975 *known_errorHandler = 1;
7976 else if (!strcmp(errors, "replace"))
7977 *known_errorHandler = 2;
7978 else if (!strcmp(errors, "ignore"))
7979 *known_errorHandler = 3;
7980 else if (!strcmp(errors, "xmlcharrefreplace"))
7981 *known_errorHandler = 4;
7982 else
7983 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007984 }
7985 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007986 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007987 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007988 return -1;
7989 case 2: /* replace */
7990 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007991 x = charmapencode_output('?', mapping, res, respos);
7992 if (x==enc_EXCEPTION) {
7993 return -1;
7994 }
7995 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007996 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00007997 return -1;
7998 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007999 }
8000 /* fall through */
8001 case 3: /* ignore */
8002 *inpos = collendpos;
8003 break;
8004 case 4: /* xmlcharrefreplace */
8005 /* generate replacement (temporarily (mis)uses p) */
8006 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008007 char buffer[2+29+1+1];
8008 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008009 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008010 for (cp = buffer; *cp; ++cp) {
8011 x = charmapencode_output(*cp, mapping, res, respos);
8012 if (x==enc_EXCEPTION)
8013 return -1;
8014 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008015 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008016 return -1;
8017 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008018 }
8019 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008020 *inpos = collendpos;
8021 break;
8022 default:
8023 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008024 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008025 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008026 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008027 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008028 if (PyBytes_Check(repunicode)) {
8029 /* Directly copy bytes result to output. */
8030 Py_ssize_t outsize = PyBytes_Size(*res);
8031 Py_ssize_t requiredsize;
8032 repsize = PyBytes_Size(repunicode);
8033 requiredsize = *respos + repsize;
8034 if (requiredsize > outsize)
8035 /* Make room for all additional bytes. */
8036 if (charmapencode_resize(res, respos, requiredsize)) {
8037 Py_DECREF(repunicode);
8038 return -1;
8039 }
8040 memcpy(PyBytes_AsString(*res) + *respos,
8041 PyBytes_AsString(repunicode), repsize);
8042 *respos += repsize;
8043 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008044 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008045 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008046 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008047 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008048 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008049 Py_DECREF(repunicode);
8050 return -1;
8051 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008052 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008053 data = PyUnicode_DATA(repunicode);
8054 kind = PyUnicode_KIND(repunicode);
8055 for (index = 0; index < repsize; index++) {
8056 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8057 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008058 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008059 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008060 return -1;
8061 }
8062 else if (x==enc_FAILED) {
8063 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008064 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008065 return -1;
8066 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008067 }
8068 *inpos = newpos;
8069 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008070 }
8071 return 0;
8072}
8073
Alexander Belopolsky40018472011-02-26 01:02:56 +00008074PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008075_PyUnicode_EncodeCharmap(PyObject *unicode,
8076 PyObject *mapping,
8077 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008078{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008079 /* output object */
8080 PyObject *res = NULL;
8081 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008082 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008083 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008084 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008085 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008086 PyObject *errorHandler = NULL;
8087 PyObject *exc = NULL;
8088 /* the following variable is used for caching string comparisons
8089 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8090 * 3=ignore, 4=xmlcharrefreplace */
8091 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008092
Benjamin Petersonbac79492012-01-14 13:34:47 -05008093 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008094 return NULL;
8095 size = PyUnicode_GET_LENGTH(unicode);
8096
Guido van Rossumd57fd912000-03-10 22:53:23 +00008097 /* Default to Latin-1 */
8098 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008099 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008100
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008101 /* allocate enough for a simple encoding without
8102 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008103 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008104 if (res == NULL)
8105 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008106 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008107 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008108
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008109 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008110 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008111 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008112 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008113 if (x==enc_EXCEPTION) /* error */
8114 goto onError;
8115 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008116 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008117 &exc,
8118 &known_errorHandler, &errorHandler, errors,
8119 &res, &respos)) {
8120 goto onError;
8121 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008122 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008123 else
8124 /* done with this character => adjust input position */
8125 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008126 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008127
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008128 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008129 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008130 if (_PyBytes_Resize(&res, respos) < 0)
8131 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008132
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008133 Py_XDECREF(exc);
8134 Py_XDECREF(errorHandler);
8135 return res;
8136
Benjamin Peterson29060642009-01-31 22:14:21 +00008137 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008138 Py_XDECREF(res);
8139 Py_XDECREF(exc);
8140 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008141 return NULL;
8142}
8143
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008144/* Deprecated */
8145PyObject *
8146PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8147 Py_ssize_t size,
8148 PyObject *mapping,
8149 const char *errors)
8150{
8151 PyObject *result;
8152 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8153 if (unicode == NULL)
8154 return NULL;
8155 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8156 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008157 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008158}
8159
Alexander Belopolsky40018472011-02-26 01:02:56 +00008160PyObject *
8161PyUnicode_AsCharmapString(PyObject *unicode,
8162 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008163{
8164 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008165 PyErr_BadArgument();
8166 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008167 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008168 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008169}
8170
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008171/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008172static void
8173make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008174 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008175 Py_ssize_t startpos, Py_ssize_t endpos,
8176 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008177{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008178 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008179 *exceptionObject = _PyUnicodeTranslateError_Create(
8180 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008181 }
8182 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008183 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8184 goto onError;
8185 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8186 goto onError;
8187 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8188 goto onError;
8189 return;
8190 onError:
8191 Py_DECREF(*exceptionObject);
8192 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008193 }
8194}
8195
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008196/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008197static void
8198raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008199 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008200 Py_ssize_t startpos, Py_ssize_t endpos,
8201 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008202{
8203 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008204 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008205 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008206 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008207}
8208
8209/* error handling callback helper:
8210 build arguments, call the callback and check the arguments,
8211 put the result into newpos and return the replacement string, which
8212 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008213static PyObject *
8214unicode_translate_call_errorhandler(const char *errors,
8215 PyObject **errorHandler,
8216 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008217 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008218 Py_ssize_t startpos, Py_ssize_t endpos,
8219 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008220{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008221 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008222
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008223 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008224 PyObject *restuple;
8225 PyObject *resunicode;
8226
8227 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008228 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008229 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008230 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008231 }
8232
8233 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008234 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008235 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008236 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008237
8238 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008239 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008240 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008241 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008242 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008243 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008244 Py_DECREF(restuple);
8245 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008246 }
8247 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008248 &resunicode, &i_newpos)) {
8249 Py_DECREF(restuple);
8250 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008251 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008252 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008253 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008254 else
8255 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008256 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008257 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8258 Py_DECREF(restuple);
8259 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008260 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008261 Py_INCREF(resunicode);
8262 Py_DECREF(restuple);
8263 return resunicode;
8264}
8265
8266/* Lookup the character ch in the mapping and put the result in result,
8267 which must be decrefed by the caller.
8268 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008269static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008270charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008271{
Christian Heimes217cfd12007-12-02 14:31:20 +00008272 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008273 PyObject *x;
8274
8275 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008277 x = PyObject_GetItem(mapping, w);
8278 Py_DECREF(w);
8279 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008280 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8281 /* No mapping found means: use 1:1 mapping. */
8282 PyErr_Clear();
8283 *result = NULL;
8284 return 0;
8285 } else
8286 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008287 }
8288 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008289 *result = x;
8290 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008291 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008292 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008293 long value = PyLong_AS_LONG(x);
8294 long max = PyUnicode_GetMax();
8295 if (value < 0 || value > max) {
8296 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008297 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008298 Py_DECREF(x);
8299 return -1;
8300 }
8301 *result = x;
8302 return 0;
8303 }
8304 else if (PyUnicode_Check(x)) {
8305 *result = x;
8306 return 0;
8307 }
8308 else {
8309 /* wrong return value */
8310 PyErr_SetString(PyExc_TypeError,
8311 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008312 Py_DECREF(x);
8313 return -1;
8314 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008315}
8316/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008317 if not reallocate and adjust various state variables.
8318 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008319static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008320charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008321 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008322{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008323 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008324 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008325 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008326 /* exponentially overallocate to minimize reallocations */
8327 if (requiredsize < 2 * oldsize)
8328 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008329 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8330 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008331 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008332 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008333 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008334 }
8335 return 0;
8336}
8337/* lookup the character, put the result in the output string and adjust
8338 various state variables. Return a new reference to the object that
8339 was put in the output buffer in *result, or Py_None, if the mapping was
8340 undefined (in which case no character was written).
8341 The called must decref result.
8342 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008343static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008344charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8345 PyObject *mapping, Py_UCS4 **output,
8346 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008347 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008348{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008349 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8350 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008351 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008352 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008353 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008354 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008355 }
8356 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008357 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008358 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008359 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008360 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008361 }
8362 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008363 Py_ssize_t repsize;
8364 if (PyUnicode_READY(*res) == -1)
8365 return -1;
8366 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008367 if (repsize==1) {
8368 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008369 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008370 }
8371 else if (repsize!=0) {
8372 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008373 Py_ssize_t requiredsize = *opos +
8374 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008375 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008376 Py_ssize_t i;
8377 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008378 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008379 for(i = 0; i < repsize; i++)
8380 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008381 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008382 }
8383 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008384 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008385 return 0;
8386}
8387
Alexander Belopolsky40018472011-02-26 01:02:56 +00008388PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008389_PyUnicode_TranslateCharmap(PyObject *input,
8390 PyObject *mapping,
8391 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008392{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008393 /* input object */
8394 char *idata;
8395 Py_ssize_t size, i;
8396 int kind;
8397 /* output buffer */
8398 Py_UCS4 *output = NULL;
8399 Py_ssize_t osize;
8400 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008401 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008402 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008403 char *reason = "character maps to <undefined>";
8404 PyObject *errorHandler = NULL;
8405 PyObject *exc = NULL;
8406 /* the following variable is used for caching string comparisons
8407 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8408 * 3=ignore, 4=xmlcharrefreplace */
8409 int known_errorHandler = -1;
8410
Guido van Rossumd57fd912000-03-10 22:53:23 +00008411 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008412 PyErr_BadArgument();
8413 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008414 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008415
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008416 if (PyUnicode_READY(input) == -1)
8417 return NULL;
8418 idata = (char*)PyUnicode_DATA(input);
8419 kind = PyUnicode_KIND(input);
8420 size = PyUnicode_GET_LENGTH(input);
8421 i = 0;
8422
8423 if (size == 0) {
8424 Py_INCREF(input);
8425 return input;
8426 }
8427
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008428 /* allocate enough for a simple 1:1 translation without
8429 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008430 osize = size;
8431 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8432 opos = 0;
8433 if (output == NULL) {
8434 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008435 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008436 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008437
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008438 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008439 /* try to encode it */
8440 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008441 if (charmaptranslate_output(input, i, mapping,
8442 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008443 Py_XDECREF(x);
8444 goto onError;
8445 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008446 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008447 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008448 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008449 else { /* untranslatable character */
8450 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8451 Py_ssize_t repsize;
8452 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008453 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008454 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008455 Py_ssize_t collstart = i;
8456 Py_ssize_t collend = i+1;
8457 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008458
Benjamin Peterson29060642009-01-31 22:14:21 +00008459 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008460 while (collend < size) {
8461 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008462 goto onError;
8463 Py_XDECREF(x);
8464 if (x!=Py_None)
8465 break;
8466 ++collend;
8467 }
8468 /* cache callback name lookup
8469 * (if not done yet, i.e. it's the first error) */
8470 if (known_errorHandler==-1) {
8471 if ((errors==NULL) || (!strcmp(errors, "strict")))
8472 known_errorHandler = 1;
8473 else if (!strcmp(errors, "replace"))
8474 known_errorHandler = 2;
8475 else if (!strcmp(errors, "ignore"))
8476 known_errorHandler = 3;
8477 else if (!strcmp(errors, "xmlcharrefreplace"))
8478 known_errorHandler = 4;
8479 else
8480 known_errorHandler = 0;
8481 }
8482 switch (known_errorHandler) {
8483 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008484 raise_translate_exception(&exc, input, collstart,
8485 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008486 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 case 2: /* replace */
8488 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008489 for (coll = collstart; coll<collend; coll++)
8490 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008491 /* fall through */
8492 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008493 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008494 break;
8495 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008496 /* generate replacement (temporarily (mis)uses i) */
8497 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008498 char buffer[2+29+1+1];
8499 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008500 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8501 if (charmaptranslate_makespace(&output, &osize,
8502 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008503 goto onError;
8504 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008505 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008506 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008507 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008508 break;
8509 default:
8510 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008511 reason, input, &exc,
8512 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008513 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008514 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008515 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008516 Py_DECREF(repunicode);
8517 goto onError;
8518 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008519 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008520 repsize = PyUnicode_GET_LENGTH(repunicode);
8521 if (charmaptranslate_makespace(&output, &osize,
8522 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008523 Py_DECREF(repunicode);
8524 goto onError;
8525 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008526 for (uni2 = 0; repsize-->0; ++uni2)
8527 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8528 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008529 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008530 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008531 }
8532 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008533 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8534 if (!res)
8535 goto onError;
8536 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008537 Py_XDECREF(exc);
8538 Py_XDECREF(errorHandler);
8539 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008540
Benjamin Peterson29060642009-01-31 22:14:21 +00008541 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008542 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008543 Py_XDECREF(exc);
8544 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008545 return NULL;
8546}
8547
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008548/* Deprecated. Use PyUnicode_Translate instead. */
8549PyObject *
8550PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8551 Py_ssize_t size,
8552 PyObject *mapping,
8553 const char *errors)
8554{
8555 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8556 if (!unicode)
8557 return NULL;
8558 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8559}
8560
Alexander Belopolsky40018472011-02-26 01:02:56 +00008561PyObject *
8562PyUnicode_Translate(PyObject *str,
8563 PyObject *mapping,
8564 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008565{
8566 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008567
Guido van Rossumd57fd912000-03-10 22:53:23 +00008568 str = PyUnicode_FromObject(str);
8569 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008570 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008571 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008572 Py_DECREF(str);
8573 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008574
Benjamin Peterson29060642009-01-31 22:14:21 +00008575 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008576 Py_XDECREF(str);
8577 return NULL;
8578}
Tim Petersced69f82003-09-16 20:30:58 +00008579
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008580static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008581fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008582{
8583 /* No need to call PyUnicode_READY(self) because this function is only
8584 called as a callback from fixup() which does it already. */
8585 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8586 const int kind = PyUnicode_KIND(self);
8587 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008588 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008589 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008590 Py_ssize_t i;
8591
8592 for (i = 0; i < len; ++i) {
8593 ch = PyUnicode_READ(kind, data, i);
8594 fixed = 0;
8595 if (ch > 127) {
8596 if (Py_UNICODE_ISSPACE(ch))
8597 fixed = ' ';
8598 else {
8599 const int decimal = Py_UNICODE_TODECIMAL(ch);
8600 if (decimal >= 0)
8601 fixed = '0' + decimal;
8602 }
8603 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008604 modified = 1;
Victor Stinnere6abb482012-05-02 01:15:40 +02008605 maxchar = MAX_MAXCHAR(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008606 PyUnicode_WRITE(kind, data, i, fixed);
8607 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008608 else
8609 maxchar = MAX_MAXCHAR(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008610 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008611 }
8612
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008613 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008614}
8615
8616PyObject *
8617_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8618{
8619 if (!PyUnicode_Check(unicode)) {
8620 PyErr_BadInternalCall();
8621 return NULL;
8622 }
8623 if (PyUnicode_READY(unicode) == -1)
8624 return NULL;
8625 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8626 /* If the string is already ASCII, just return the same string */
8627 Py_INCREF(unicode);
8628 return unicode;
8629 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008630 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008631}
8632
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008633PyObject *
8634PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8635 Py_ssize_t length)
8636{
Victor Stinnerf0124502011-11-21 23:12:56 +01008637 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008638 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008639 Py_UCS4 maxchar;
8640 enum PyUnicode_Kind kind;
8641 void *data;
8642
Victor Stinner99d7ad02012-02-22 13:37:39 +01008643 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008644 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008645 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008646 if (ch > 127) {
8647 int decimal = Py_UNICODE_TODECIMAL(ch);
8648 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008649 ch = '0' + decimal;
Victor Stinnere6abb482012-05-02 01:15:40 +02008650 maxchar = MAX_MAXCHAR(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008651 }
8652 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008653
8654 /* Copy to a new string */
8655 decimal = PyUnicode_New(length, maxchar);
8656 if (decimal == NULL)
8657 return decimal;
8658 kind = PyUnicode_KIND(decimal);
8659 data = PyUnicode_DATA(decimal);
8660 /* Iterate over code points */
8661 for (i = 0; i < length; i++) {
8662 Py_UNICODE ch = s[i];
8663 if (ch > 127) {
8664 int decimal = Py_UNICODE_TODECIMAL(ch);
8665 if (decimal >= 0)
8666 ch = '0' + decimal;
8667 }
8668 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008669 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008670 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008671}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008672/* --- Decimal Encoder ---------------------------------------------------- */
8673
Alexander Belopolsky40018472011-02-26 01:02:56 +00008674int
8675PyUnicode_EncodeDecimal(Py_UNICODE *s,
8676 Py_ssize_t length,
8677 char *output,
8678 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008679{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008680 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008681 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008682 enum PyUnicode_Kind kind;
8683 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008684
8685 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008686 PyErr_BadArgument();
8687 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008688 }
8689
Victor Stinner42bf7752011-11-21 22:52:58 +01008690 unicode = PyUnicode_FromUnicode(s, length);
8691 if (unicode == NULL)
8692 return -1;
8693
Benjamin Petersonbac79492012-01-14 13:34:47 -05008694 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008695 Py_DECREF(unicode);
8696 return -1;
8697 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008698 kind = PyUnicode_KIND(unicode);
8699 data = PyUnicode_DATA(unicode);
8700
Victor Stinnerb84d7232011-11-22 01:50:07 +01008701 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008702 PyObject *exc;
8703 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008704 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008705 Py_ssize_t startpos;
8706
8707 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008708
Benjamin Peterson29060642009-01-31 22:14:21 +00008709 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008710 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008711 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008712 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008713 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008714 decimal = Py_UNICODE_TODECIMAL(ch);
8715 if (decimal >= 0) {
8716 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008717 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008718 continue;
8719 }
8720 if (0 < ch && ch < 256) {
8721 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008722 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008723 continue;
8724 }
Victor Stinner6345be92011-11-25 20:09:01 +01008725
Victor Stinner42bf7752011-11-21 22:52:58 +01008726 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008727 exc = NULL;
8728 raise_encode_exception(&exc, "decimal", unicode,
8729 startpos, startpos+1,
8730 "invalid decimal Unicode string");
8731 Py_XDECREF(exc);
8732 Py_DECREF(unicode);
8733 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008734 }
8735 /* 0-terminate the output string */
8736 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008737 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008738 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008739}
8740
Guido van Rossumd57fd912000-03-10 22:53:23 +00008741/* --- Helpers ------------------------------------------------------------ */
8742
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008743static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008744any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008745 Py_ssize_t start,
8746 Py_ssize_t end)
8747{
8748 int kind1, kind2, kind;
8749 void *buf1, *buf2;
8750 Py_ssize_t len1, len2, result;
8751
8752 kind1 = PyUnicode_KIND(s1);
8753 kind2 = PyUnicode_KIND(s2);
8754 kind = kind1 > kind2 ? kind1 : kind2;
8755 buf1 = PyUnicode_DATA(s1);
8756 buf2 = PyUnicode_DATA(s2);
8757 if (kind1 != kind)
8758 buf1 = _PyUnicode_AsKind(s1, kind);
8759 if (!buf1)
8760 return -2;
8761 if (kind2 != kind)
8762 buf2 = _PyUnicode_AsKind(s2, kind);
8763 if (!buf2) {
8764 if (kind1 != kind) PyMem_Free(buf1);
8765 return -2;
8766 }
8767 len1 = PyUnicode_GET_LENGTH(s1);
8768 len2 = PyUnicode_GET_LENGTH(s2);
8769
Victor Stinner794d5672011-10-10 03:21:36 +02008770 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008771 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008772 case PyUnicode_1BYTE_KIND:
8773 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8774 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8775 else
8776 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8777 break;
8778 case PyUnicode_2BYTE_KIND:
8779 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8780 break;
8781 case PyUnicode_4BYTE_KIND:
8782 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8783 break;
8784 default:
8785 assert(0); result = -2;
8786 }
8787 }
8788 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008789 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008790 case PyUnicode_1BYTE_KIND:
8791 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8792 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8793 else
8794 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8795 break;
8796 case PyUnicode_2BYTE_KIND:
8797 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8798 break;
8799 case PyUnicode_4BYTE_KIND:
8800 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8801 break;
8802 default:
8803 assert(0); result = -2;
8804 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008805 }
8806
8807 if (kind1 != kind)
8808 PyMem_Free(buf1);
8809 if (kind2 != kind)
8810 PyMem_Free(buf2);
8811
8812 return result;
8813}
8814
8815Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01008816_PyUnicode_InsertThousandsGrouping(
8817 PyObject *unicode, Py_ssize_t index,
8818 Py_ssize_t n_buffer,
8819 void *digits, Py_ssize_t n_digits,
8820 Py_ssize_t min_width,
8821 const char *grouping, PyObject *thousands_sep,
8822 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008823{
Victor Stinner41a863c2012-02-24 00:37:51 +01008824 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008825 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01008826 Py_ssize_t thousands_sep_len;
8827 Py_ssize_t len;
8828
8829 if (unicode != NULL) {
8830 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008831 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01008832 }
8833 else {
8834 kind = PyUnicode_1BYTE_KIND;
8835 data = NULL;
8836 }
8837 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
8838 thousands_sep_data = PyUnicode_DATA(thousands_sep);
8839 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
8840 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01008841 if (thousands_sep_kind < kind) {
8842 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
8843 if (!thousands_sep_data)
8844 return -1;
8845 }
8846 else {
8847 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
8848 if (!data)
8849 return -1;
8850 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008851 }
8852
Benjamin Petersonead6b532011-12-20 17:23:42 -06008853 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008854 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008855 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01008856 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008857 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008858 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008859 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02008860 else
Victor Stinner41a863c2012-02-24 00:37:51 +01008861 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02008862 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008863 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008864 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008865 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008866 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008867 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008868 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008869 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008870 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008871 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008872 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01008873 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008874 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01008875 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01008876 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01008877 break;
8878 default:
8879 assert(0);
8880 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008881 }
Victor Stinner90f50d42012-02-24 01:44:47 +01008882 if (unicode != NULL && thousands_sep_kind != kind) {
8883 if (thousands_sep_kind < kind)
8884 PyMem_Free(thousands_sep_data);
8885 else
8886 PyMem_Free(data);
8887 }
Victor Stinner41a863c2012-02-24 00:37:51 +01008888 if (unicode == NULL) {
8889 *maxchar = 127;
8890 if (len != n_digits) {
Victor Stinnere6abb482012-05-02 01:15:40 +02008891 *maxchar = MAX_MAXCHAR(*maxchar,
8892 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01008893 }
8894 }
8895 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008896}
8897
8898
Thomas Wouters477c8d52006-05-27 19:21:47 +00008899/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008900#define ADJUST_INDICES(start, end, len) \
8901 if (end > len) \
8902 end = len; \
8903 else if (end < 0) { \
8904 end += len; \
8905 if (end < 0) \
8906 end = 0; \
8907 } \
8908 if (start < 0) { \
8909 start += len; \
8910 if (start < 0) \
8911 start = 0; \
8912 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008913
Alexander Belopolsky40018472011-02-26 01:02:56 +00008914Py_ssize_t
8915PyUnicode_Count(PyObject *str,
8916 PyObject *substr,
8917 Py_ssize_t start,
8918 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008919{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008920 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008921 PyObject* str_obj;
8922 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008923 int kind1, kind2, kind;
8924 void *buf1 = NULL, *buf2 = NULL;
8925 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008926
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008927 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008928 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008929 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02008930 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06008931 if (!sub_obj) {
8932 Py_DECREF(str_obj);
8933 return -1;
8934 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06008935 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06008936 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008937 Py_DECREF(str_obj);
8938 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008939 }
Tim Petersced69f82003-09-16 20:30:58 +00008940
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008941 kind1 = PyUnicode_KIND(str_obj);
8942 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008943 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008944 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008945 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008946 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02008947 if (kind2 > kind) {
8948 Py_DECREF(sub_obj);
8949 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02008950 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02008951 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01008952 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05008953 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008954 if (!buf2)
8955 goto onError;
8956 len1 = PyUnicode_GET_LENGTH(str_obj);
8957 len2 = PyUnicode_GET_LENGTH(sub_obj);
8958
8959 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06008960 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008961 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008962 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8963 result = asciilib_count(
8964 ((Py_UCS1*)buf1) + start, end - start,
8965 buf2, len2, PY_SSIZE_T_MAX
8966 );
8967 else
8968 result = ucs1lib_count(
8969 ((Py_UCS1*)buf1) + start, end - start,
8970 buf2, len2, PY_SSIZE_T_MAX
8971 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008972 break;
8973 case PyUnicode_2BYTE_KIND:
8974 result = ucs2lib_count(
8975 ((Py_UCS2*)buf1) + start, end - start,
8976 buf2, len2, PY_SSIZE_T_MAX
8977 );
8978 break;
8979 case PyUnicode_4BYTE_KIND:
8980 result = ucs4lib_count(
8981 ((Py_UCS4*)buf1) + start, end - start,
8982 buf2, len2, PY_SSIZE_T_MAX
8983 );
8984 break;
8985 default:
8986 assert(0); result = 0;
8987 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008988
8989 Py_DECREF(sub_obj);
8990 Py_DECREF(str_obj);
8991
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008992 if (kind2 != kind)
8993 PyMem_Free(buf2);
8994
Guido van Rossumd57fd912000-03-10 22:53:23 +00008995 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008996 onError:
8997 Py_DECREF(sub_obj);
8998 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008999 if (kind2 != kind && buf2)
9000 PyMem_Free(buf2);
9001 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009002}
9003
Alexander Belopolsky40018472011-02-26 01:02:56 +00009004Py_ssize_t
9005PyUnicode_Find(PyObject *str,
9006 PyObject *sub,
9007 Py_ssize_t start,
9008 Py_ssize_t end,
9009 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009010{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009011 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009012
Guido van Rossumd57fd912000-03-10 22:53:23 +00009013 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009014 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009015 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009016 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009017 if (!sub) {
9018 Py_DECREF(str);
9019 return -2;
9020 }
9021 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9022 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009023 Py_DECREF(str);
9024 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009025 }
Tim Petersced69f82003-09-16 20:30:58 +00009026
Victor Stinner794d5672011-10-10 03:21:36 +02009027 result = any_find_slice(direction,
9028 str, sub, start, end
9029 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009030
Guido van Rossumd57fd912000-03-10 22:53:23 +00009031 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009032 Py_DECREF(sub);
9033
Guido van Rossumd57fd912000-03-10 22:53:23 +00009034 return result;
9035}
9036
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009037Py_ssize_t
9038PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9039 Py_ssize_t start, Py_ssize_t end,
9040 int direction)
9041{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009042 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009043 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009044 if (PyUnicode_READY(str) == -1)
9045 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009046 if (start < 0 || end < 0) {
9047 PyErr_SetString(PyExc_IndexError, "string index out of range");
9048 return -2;
9049 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009050 if (end > PyUnicode_GET_LENGTH(str))
9051 end = PyUnicode_GET_LENGTH(str);
9052 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009053 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9054 kind, end-start, ch, direction);
9055 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009056 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009057 else
9058 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009059}
9060
Alexander Belopolsky40018472011-02-26 01:02:56 +00009061static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009062tailmatch(PyObject *self,
9063 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009064 Py_ssize_t start,
9065 Py_ssize_t end,
9066 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009067{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009068 int kind_self;
9069 int kind_sub;
9070 void *data_self;
9071 void *data_sub;
9072 Py_ssize_t offset;
9073 Py_ssize_t i;
9074 Py_ssize_t end_sub;
9075
9076 if (PyUnicode_READY(self) == -1 ||
9077 PyUnicode_READY(substring) == -1)
9078 return 0;
9079
9080 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009081 return 1;
9082
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009083 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9084 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009085 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009086 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009088 kind_self = PyUnicode_KIND(self);
9089 data_self = PyUnicode_DATA(self);
9090 kind_sub = PyUnicode_KIND(substring);
9091 data_sub = PyUnicode_DATA(substring);
9092 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9093
9094 if (direction > 0)
9095 offset = end;
9096 else
9097 offset = start;
9098
9099 if (PyUnicode_READ(kind_self, data_self, offset) ==
9100 PyUnicode_READ(kind_sub, data_sub, 0) &&
9101 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9102 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9103 /* If both are of the same kind, memcmp is sufficient */
9104 if (kind_self == kind_sub) {
9105 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009106 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009107 data_sub,
9108 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009109 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009110 }
9111 /* otherwise we have to compare each character by first accesing it */
9112 else {
9113 /* We do not need to compare 0 and len(substring)-1 because
9114 the if statement above ensured already that they are equal
9115 when we end up here. */
9116 // TODO: honor direction and do a forward or backwards search
9117 for (i = 1; i < end_sub; ++i) {
9118 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9119 PyUnicode_READ(kind_sub, data_sub, i))
9120 return 0;
9121 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009122 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009123 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009124 }
9125
9126 return 0;
9127}
9128
Alexander Belopolsky40018472011-02-26 01:02:56 +00009129Py_ssize_t
9130PyUnicode_Tailmatch(PyObject *str,
9131 PyObject *substr,
9132 Py_ssize_t start,
9133 Py_ssize_t end,
9134 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009135{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009136 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009137
Guido van Rossumd57fd912000-03-10 22:53:23 +00009138 str = PyUnicode_FromObject(str);
9139 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009140 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009141 substr = PyUnicode_FromObject(substr);
9142 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009143 Py_DECREF(str);
9144 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009145 }
Tim Petersced69f82003-09-16 20:30:58 +00009146
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009147 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009148 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009149 Py_DECREF(str);
9150 Py_DECREF(substr);
9151 return result;
9152}
9153
Guido van Rossumd57fd912000-03-10 22:53:23 +00009154/* Apply fixfct filter to the Unicode object self and return a
9155 reference to the modified object */
9156
Alexander Belopolsky40018472011-02-26 01:02:56 +00009157static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009158fixup(PyObject *self,
9159 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009160{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009161 PyObject *u;
9162 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009163 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009164
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009165 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009166 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009167 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009168 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009169
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009170 /* fix functions return the new maximum character in a string,
9171 if the kind of the resulting unicode object does not change,
9172 everything is fine. Otherwise we need to change the string kind
9173 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009174 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009175
9176 if (maxchar_new == 0) {
9177 /* no changes */;
9178 if (PyUnicode_CheckExact(self)) {
9179 Py_DECREF(u);
9180 Py_INCREF(self);
9181 return self;
9182 }
9183 else
9184 return u;
9185 }
9186
Victor Stinnere6abb482012-05-02 01:15:40 +02009187 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009188
Victor Stinnereaab6042011-12-11 22:22:39 +01009189 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009190 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009191
9192 /* In case the maximum character changed, we need to
9193 convert the string to the new category. */
9194 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9195 if (v == NULL) {
9196 Py_DECREF(u);
9197 return NULL;
9198 }
9199 if (maxchar_new > maxchar_old) {
9200 /* If the maxchar increased so that the kind changed, not all
9201 characters are representable anymore and we need to fix the
9202 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009203 _PyUnicode_FastCopyCharacters(v, 0,
9204 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009205 maxchar_old = fixfct(v);
9206 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009207 }
9208 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009209 _PyUnicode_FastCopyCharacters(v, 0,
9210 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009211 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009212 Py_DECREF(u);
9213 assert(_PyUnicode_CheckConsistency(v, 1));
9214 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009215}
9216
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009217static PyObject *
9218ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009219{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009220 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9221 char *resdata, *data = PyUnicode_DATA(self);
9222 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009223
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009224 res = PyUnicode_New(len, 127);
9225 if (res == NULL)
9226 return NULL;
9227 resdata = PyUnicode_DATA(res);
9228 if (lower)
9229 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009230 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009231 _Py_bytes_upper(resdata, data, len);
9232 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009233}
9234
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009235static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009236handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009237{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009238 Py_ssize_t j;
9239 int final_sigma;
9240 Py_UCS4 c;
9241 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009242
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009243 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9244
9245 where ! is a negation and \p{xxx} is a character with property xxx.
9246 */
9247 for (j = i - 1; j >= 0; j--) {
9248 c = PyUnicode_READ(kind, data, j);
9249 if (!_PyUnicode_IsCaseIgnorable(c))
9250 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009251 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009252 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9253 if (final_sigma) {
9254 for (j = i + 1; j < length; j++) {
9255 c = PyUnicode_READ(kind, data, j);
9256 if (!_PyUnicode_IsCaseIgnorable(c))
9257 break;
9258 }
9259 final_sigma = j == length || !_PyUnicode_IsCased(c);
9260 }
9261 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009262}
9263
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009264static int
9265lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9266 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009267{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009268 /* Obscure special case. */
9269 if (c == 0x3A3) {
9270 mapped[0] = handle_capital_sigma(kind, data, length, i);
9271 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009272 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009273 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009274}
9275
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009276static Py_ssize_t
9277do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009278{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009279 Py_ssize_t i, k = 0;
9280 int n_res, j;
9281 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009282
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009283 c = PyUnicode_READ(kind, data, 0);
9284 n_res = _PyUnicode_ToUpperFull(c, mapped);
9285 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009286 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009287 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009288 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009289 for (i = 1; i < length; i++) {
9290 c = PyUnicode_READ(kind, data, i);
9291 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9292 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009293 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009294 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009295 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009296 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009297 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009298}
9299
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009300static Py_ssize_t
9301do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9302 Py_ssize_t i, k = 0;
9303
9304 for (i = 0; i < length; i++) {
9305 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9306 int n_res, j;
9307 if (Py_UNICODE_ISUPPER(c)) {
9308 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9309 }
9310 else if (Py_UNICODE_ISLOWER(c)) {
9311 n_res = _PyUnicode_ToUpperFull(c, mapped);
9312 }
9313 else {
9314 n_res = 1;
9315 mapped[0] = c;
9316 }
9317 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009318 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009319 res[k++] = mapped[j];
9320 }
9321 }
9322 return k;
9323}
9324
9325static Py_ssize_t
9326do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9327 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009328{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009329 Py_ssize_t i, k = 0;
9330
9331 for (i = 0; i < length; i++) {
9332 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9333 int n_res, j;
9334 if (lower)
9335 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9336 else
9337 n_res = _PyUnicode_ToUpperFull(c, mapped);
9338 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009339 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009340 res[k++] = mapped[j];
9341 }
9342 }
9343 return k;
9344}
9345
9346static Py_ssize_t
9347do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9348{
9349 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9350}
9351
9352static Py_ssize_t
9353do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9354{
9355 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9356}
9357
Benjamin Petersone51757f2012-01-12 21:10:29 -05009358static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009359do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9360{
9361 Py_ssize_t i, k = 0;
9362
9363 for (i = 0; i < length; i++) {
9364 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9365 Py_UCS4 mapped[3];
9366 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9367 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009368 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009369 res[k++] = mapped[j];
9370 }
9371 }
9372 return k;
9373}
9374
9375static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009376do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9377{
9378 Py_ssize_t i, k = 0;
9379 int previous_is_cased;
9380
9381 previous_is_cased = 0;
9382 for (i = 0; i < length; i++) {
9383 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9384 Py_UCS4 mapped[3];
9385 int n_res, j;
9386
9387 if (previous_is_cased)
9388 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9389 else
9390 n_res = _PyUnicode_ToTitleFull(c, mapped);
9391
9392 for (j = 0; j < n_res; j++) {
Victor Stinnere6abb482012-05-02 01:15:40 +02009393 *maxchar = MAX_MAXCHAR(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009394 res[k++] = mapped[j];
9395 }
9396
9397 previous_is_cased = _PyUnicode_IsCased(c);
9398 }
9399 return k;
9400}
9401
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009402static PyObject *
9403case_operation(PyObject *self,
9404 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9405{
9406 PyObject *res = NULL;
9407 Py_ssize_t length, newlength = 0;
9408 int kind, outkind;
9409 void *data, *outdata;
9410 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9411
Benjamin Petersoneea48462012-01-16 14:28:50 -05009412 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009413
9414 kind = PyUnicode_KIND(self);
9415 data = PyUnicode_DATA(self);
9416 length = PyUnicode_GET_LENGTH(self);
9417 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9418 if (tmp == NULL)
9419 return PyErr_NoMemory();
9420 newlength = perform(kind, data, length, tmp, &maxchar);
9421 res = PyUnicode_New(newlength, maxchar);
9422 if (res == NULL)
9423 goto leave;
9424 tmpend = tmp + newlength;
9425 outdata = PyUnicode_DATA(res);
9426 outkind = PyUnicode_KIND(res);
9427 switch (outkind) {
9428 case PyUnicode_1BYTE_KIND:
9429 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9430 break;
9431 case PyUnicode_2BYTE_KIND:
9432 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9433 break;
9434 case PyUnicode_4BYTE_KIND:
9435 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9436 break;
9437 default:
9438 assert(0);
9439 break;
9440 }
9441 leave:
9442 PyMem_FREE(tmp);
9443 return res;
9444}
9445
Tim Peters8ce9f162004-08-27 01:49:32 +00009446PyObject *
9447PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009448{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009449 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009450 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009451 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009452 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009453 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9454 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009455 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009456 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009457 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009458 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009459 int use_memcpy;
9460 unsigned char *res_data = NULL, *sep_data = NULL;
9461 PyObject *last_obj;
9462 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009463
Tim Peters05eba1f2004-08-27 21:32:02 +00009464 fseq = PySequence_Fast(seq, "");
9465 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009466 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009467 }
9468
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009469 /* NOTE: the following code can't call back into Python code,
9470 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009471 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009472
Tim Peters05eba1f2004-08-27 21:32:02 +00009473 seqlen = PySequence_Fast_GET_SIZE(fseq);
9474 /* If empty sequence, return u"". */
9475 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009476 Py_DECREF(fseq);
9477 Py_INCREF(unicode_empty);
9478 res = unicode_empty;
9479 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009480 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009481
Tim Peters05eba1f2004-08-27 21:32:02 +00009482 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009483 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009484 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009485 if (seqlen == 1) {
9486 if (PyUnicode_CheckExact(items[0])) {
9487 res = items[0];
9488 Py_INCREF(res);
9489 Py_DECREF(fseq);
9490 return res;
9491 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009492 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009493 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009494 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009495 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009496 /* Set up sep and seplen */
9497 if (separator == NULL) {
9498 /* fall back to a blank space separator */
9499 sep = PyUnicode_FromOrdinal(' ');
9500 if (!sep)
9501 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009502 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009503 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009504 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009505 else {
9506 if (!PyUnicode_Check(separator)) {
9507 PyErr_Format(PyExc_TypeError,
9508 "separator: expected str instance,"
9509 " %.80s found",
9510 Py_TYPE(separator)->tp_name);
9511 goto onError;
9512 }
9513 if (PyUnicode_READY(separator))
9514 goto onError;
9515 sep = separator;
9516 seplen = PyUnicode_GET_LENGTH(separator);
9517 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9518 /* inc refcount to keep this code path symmetric with the
9519 above case of a blank separator */
9520 Py_INCREF(sep);
9521 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009522 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009523 }
9524
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009525 /* There are at least two things to join, or else we have a subclass
9526 * of str in the sequence.
9527 * Do a pre-pass to figure out the total amount of space we'll
9528 * need (sz), and see whether all argument are strings.
9529 */
9530 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009531#ifdef Py_DEBUG
9532 use_memcpy = 0;
9533#else
9534 use_memcpy = 1;
9535#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009536 for (i = 0; i < seqlen; i++) {
9537 const Py_ssize_t old_sz = sz;
9538 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009539 if (!PyUnicode_Check(item)) {
9540 PyErr_Format(PyExc_TypeError,
9541 "sequence item %zd: expected str instance,"
9542 " %.80s found",
9543 i, Py_TYPE(item)->tp_name);
9544 goto onError;
9545 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009546 if (PyUnicode_READY(item) == -1)
9547 goto onError;
9548 sz += PyUnicode_GET_LENGTH(item);
9549 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnere6abb482012-05-02 01:15:40 +02009550 maxchar = MAX_MAXCHAR(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009551 if (i != 0)
9552 sz += seplen;
9553 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9554 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009555 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009556 goto onError;
9557 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009558 if (use_memcpy && last_obj != NULL) {
9559 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9560 use_memcpy = 0;
9561 }
9562 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009563 }
Tim Petersced69f82003-09-16 20:30:58 +00009564
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009565 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009566 if (res == NULL)
9567 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009568
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009569 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009570#ifdef Py_DEBUG
9571 use_memcpy = 0;
9572#else
9573 if (use_memcpy) {
9574 res_data = PyUnicode_1BYTE_DATA(res);
9575 kind = PyUnicode_KIND(res);
9576 if (seplen != 0)
9577 sep_data = PyUnicode_1BYTE_DATA(sep);
9578 }
9579#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009580 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009581 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009582 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009583 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009584 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009585 if (use_memcpy) {
9586 Py_MEMCPY(res_data,
9587 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009588 kind * seplen);
9589 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009590 }
9591 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009592 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009593 res_offset += seplen;
9594 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009595 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009596 itemlen = PyUnicode_GET_LENGTH(item);
9597 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009598 if (use_memcpy) {
9599 Py_MEMCPY(res_data,
9600 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009601 kind * itemlen);
9602 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009603 }
9604 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009605 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009606 res_offset += itemlen;
9607 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009608 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009609 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009610 if (use_memcpy)
9611 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009612 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009613 else
9614 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009615
Tim Peters05eba1f2004-08-27 21:32:02 +00009616 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009617 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009618 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009619 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009620
Benjamin Peterson29060642009-01-31 22:14:21 +00009621 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009622 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009623 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009624 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009625 return NULL;
9626}
9627
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009628#define FILL(kind, data, value, start, length) \
9629 do { \
9630 Py_ssize_t i_ = 0; \
9631 assert(kind != PyUnicode_WCHAR_KIND); \
9632 switch ((kind)) { \
9633 case PyUnicode_1BYTE_KIND: { \
9634 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009635 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009636 break; \
9637 } \
9638 case PyUnicode_2BYTE_KIND: { \
9639 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9640 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9641 break; \
9642 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009643 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009644 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9645 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9646 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009647 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009648 } \
9649 } \
9650 } while (0)
9651
Victor Stinnerd3f08822012-05-29 12:57:52 +02009652void
9653_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9654 Py_UCS4 fill_char)
9655{
9656 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9657 const void *data = PyUnicode_DATA(unicode);
9658 assert(PyUnicode_IS_READY(unicode));
9659 assert(unicode_modifiable(unicode));
9660 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9661 assert(start >= 0);
9662 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9663 FILL(kind, data, fill_char, start, length);
9664}
9665
Victor Stinner3fe55312012-01-04 00:33:50 +01009666Py_ssize_t
9667PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9668 Py_UCS4 fill_char)
9669{
9670 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009671
9672 if (!PyUnicode_Check(unicode)) {
9673 PyErr_BadInternalCall();
9674 return -1;
9675 }
9676 if (PyUnicode_READY(unicode) == -1)
9677 return -1;
9678 if (unicode_check_modifiable(unicode))
9679 return -1;
9680
Victor Stinnerd3f08822012-05-29 12:57:52 +02009681 if (start < 0) {
9682 PyErr_SetString(PyExc_IndexError, "string index out of range");
9683 return -1;
9684 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009685 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9686 PyErr_SetString(PyExc_ValueError,
9687 "fill character is bigger than "
9688 "the string maximum character");
9689 return -1;
9690 }
9691
9692 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9693 length = Py_MIN(maxlen, length);
9694 if (length <= 0)
9695 return 0;
9696
Victor Stinnerd3f08822012-05-29 12:57:52 +02009697 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009698 return length;
9699}
9700
Victor Stinner9310abb2011-10-05 00:59:23 +02009701static PyObject *
9702pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009703 Py_ssize_t left,
9704 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009705 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009706{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009707 PyObject *u;
9708 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009709 int kind;
9710 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009711
9712 if (left < 0)
9713 left = 0;
9714 if (right < 0)
9715 right = 0;
9716
Victor Stinnerc4b49542011-12-11 22:44:26 +01009717 if (left == 0 && right == 0)
9718 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009720 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9721 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009722 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9723 return NULL;
9724 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009725 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009726 maxchar = MAX_MAXCHAR(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009727 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009728 if (!u)
9729 return NULL;
9730
9731 kind = PyUnicode_KIND(u);
9732 data = PyUnicode_DATA(u);
9733 if (left)
9734 FILL(kind, data, fill, 0, left);
9735 if (right)
9736 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009737 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009738 assert(_PyUnicode_CheckConsistency(u, 1));
9739 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009740}
9741
Alexander Belopolsky40018472011-02-26 01:02:56 +00009742PyObject *
9743PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009744{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009745 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009746
9747 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009748 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009749 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009750 if (PyUnicode_READY(string) == -1) {
9751 Py_DECREF(string);
9752 return NULL;
9753 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009754
Benjamin Petersonead6b532011-12-20 17:23:42 -06009755 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009756 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009757 if (PyUnicode_IS_ASCII(string))
9758 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009759 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009760 PyUnicode_GET_LENGTH(string), keepends);
9761 else
9762 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009763 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009764 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009765 break;
9766 case PyUnicode_2BYTE_KIND:
9767 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009768 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009769 PyUnicode_GET_LENGTH(string), keepends);
9770 break;
9771 case PyUnicode_4BYTE_KIND:
9772 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009773 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009774 PyUnicode_GET_LENGTH(string), keepends);
9775 break;
9776 default:
9777 assert(0);
9778 list = 0;
9779 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009780 Py_DECREF(string);
9781 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009782}
9783
Alexander Belopolsky40018472011-02-26 01:02:56 +00009784static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009785split(PyObject *self,
9786 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009787 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009788{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009789 int kind1, kind2, kind;
9790 void *buf1, *buf2;
9791 Py_ssize_t len1, len2;
9792 PyObject* out;
9793
Guido van Rossumd57fd912000-03-10 22:53:23 +00009794 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009795 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009796
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009797 if (PyUnicode_READY(self) == -1)
9798 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009799
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009800 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009801 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009802 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009803 if (PyUnicode_IS_ASCII(self))
9804 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009805 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009806 PyUnicode_GET_LENGTH(self), maxcount
9807 );
9808 else
9809 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009810 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009811 PyUnicode_GET_LENGTH(self), maxcount
9812 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009813 case PyUnicode_2BYTE_KIND:
9814 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009815 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009816 PyUnicode_GET_LENGTH(self), maxcount
9817 );
9818 case PyUnicode_4BYTE_KIND:
9819 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009820 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009821 PyUnicode_GET_LENGTH(self), maxcount
9822 );
9823 default:
9824 assert(0);
9825 return NULL;
9826 }
9827
9828 if (PyUnicode_READY(substring) == -1)
9829 return NULL;
9830
9831 kind1 = PyUnicode_KIND(self);
9832 kind2 = PyUnicode_KIND(substring);
9833 kind = kind1 > kind2 ? kind1 : kind2;
9834 buf1 = PyUnicode_DATA(self);
9835 buf2 = PyUnicode_DATA(substring);
9836 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009837 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009838 if (!buf1)
9839 return NULL;
9840 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009841 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009842 if (!buf2) {
9843 if (kind1 != kind) PyMem_Free(buf1);
9844 return NULL;
9845 }
9846 len1 = PyUnicode_GET_LENGTH(self);
9847 len2 = PyUnicode_GET_LENGTH(substring);
9848
Benjamin Petersonead6b532011-12-20 17:23:42 -06009849 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009850 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009851 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9852 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009853 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009854 else
9855 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009856 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009857 break;
9858 case PyUnicode_2BYTE_KIND:
9859 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009860 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009861 break;
9862 case PyUnicode_4BYTE_KIND:
9863 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009864 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009865 break;
9866 default:
9867 out = NULL;
9868 }
9869 if (kind1 != kind)
9870 PyMem_Free(buf1);
9871 if (kind2 != kind)
9872 PyMem_Free(buf2);
9873 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009874}
9875
Alexander Belopolsky40018472011-02-26 01:02:56 +00009876static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009877rsplit(PyObject *self,
9878 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009879 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009880{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009881 int kind1, kind2, kind;
9882 void *buf1, *buf2;
9883 Py_ssize_t len1, len2;
9884 PyObject* out;
9885
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009886 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009887 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009888
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009889 if (PyUnicode_READY(self) == -1)
9890 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009891
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009892 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -06009893 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009894 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009895 if (PyUnicode_IS_ASCII(self))
9896 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009897 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009898 PyUnicode_GET_LENGTH(self), maxcount
9899 );
9900 else
9901 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009902 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009903 PyUnicode_GET_LENGTH(self), maxcount
9904 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009905 case PyUnicode_2BYTE_KIND:
9906 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009907 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009908 PyUnicode_GET_LENGTH(self), maxcount
9909 );
9910 case PyUnicode_4BYTE_KIND:
9911 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009912 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009913 PyUnicode_GET_LENGTH(self), maxcount
9914 );
9915 default:
9916 assert(0);
9917 return NULL;
9918 }
9919
9920 if (PyUnicode_READY(substring) == -1)
9921 return NULL;
9922
9923 kind1 = PyUnicode_KIND(self);
9924 kind2 = PyUnicode_KIND(substring);
9925 kind = kind1 > kind2 ? kind1 : kind2;
9926 buf1 = PyUnicode_DATA(self);
9927 buf2 = PyUnicode_DATA(substring);
9928 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009929 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009930 if (!buf1)
9931 return NULL;
9932 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009933 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009934 if (!buf2) {
9935 if (kind1 != kind) PyMem_Free(buf1);
9936 return NULL;
9937 }
9938 len1 = PyUnicode_GET_LENGTH(self);
9939 len2 = PyUnicode_GET_LENGTH(substring);
9940
Benjamin Petersonead6b532011-12-20 17:23:42 -06009941 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009942 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009943 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9944 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009945 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009946 else
9947 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009948 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009949 break;
9950 case PyUnicode_2BYTE_KIND:
9951 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009952 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009953 break;
9954 case PyUnicode_4BYTE_KIND:
9955 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009956 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009957 break;
9958 default:
9959 out = NULL;
9960 }
9961 if (kind1 != kind)
9962 PyMem_Free(buf1);
9963 if (kind2 != kind)
9964 PyMem_Free(buf2);
9965 return out;
9966}
9967
9968static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009969anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9970 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009971{
Benjamin Petersonead6b532011-12-20 17:23:42 -06009972 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009973 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009974 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9975 return asciilib_find(buf1, len1, buf2, len2, offset);
9976 else
9977 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009978 case PyUnicode_2BYTE_KIND:
9979 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9980 case PyUnicode_4BYTE_KIND:
9981 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9982 }
9983 assert(0);
9984 return -1;
9985}
9986
9987static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009988anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
9989 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009990{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -06009991 switch (kind) {
9992 case PyUnicode_1BYTE_KIND:
9993 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
9994 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
9995 else
9996 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
9997 case PyUnicode_2BYTE_KIND:
9998 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
9999 case PyUnicode_4BYTE_KIND:
10000 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10001 }
10002 assert(0);
10003 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010004}
10005
Alexander Belopolsky40018472011-02-26 01:02:56 +000010006static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010007replace(PyObject *self, PyObject *str1,
10008 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010009{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010010 PyObject *u;
10011 char *sbuf = PyUnicode_DATA(self);
10012 char *buf1 = PyUnicode_DATA(str1);
10013 char *buf2 = PyUnicode_DATA(str2);
10014 int srelease = 0, release1 = 0, release2 = 0;
10015 int skind = PyUnicode_KIND(self);
10016 int kind1 = PyUnicode_KIND(str1);
10017 int kind2 = PyUnicode_KIND(str2);
10018 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10019 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10020 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010021 int mayshrink;
10022 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010023
10024 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010025 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010026 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010027 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010028
Victor Stinner59de0ee2011-10-07 10:01:28 +020010029 if (str1 == str2)
10030 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010031 if (skind < kind1)
10032 /* substring too wide to be present */
10033 goto nothing;
10034
Victor Stinner49a0a212011-10-12 23:46:10 +020010035 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10036 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10037 /* Replacing str1 with str2 may cause a maxchar reduction in the
10038 result string. */
10039 mayshrink = (maxchar_str2 < maxchar);
Victor Stinnere6abb482012-05-02 01:15:40 +020010040 maxchar = MAX_MAXCHAR(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010041
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010042 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010043 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010044 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010045 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010046 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010047 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010048 Py_UCS4 u1, u2;
10049 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010050 Py_ssize_t index, pos;
10051 char *src;
10052
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010053 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010054 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10055 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010056 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010057 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010058 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010059 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010060 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010061 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010062 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010063
10064 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10065 index = 0;
10066 src = sbuf;
10067 while (--maxcount)
10068 {
10069 pos++;
10070 src += pos * PyUnicode_KIND(self);
10071 slen -= pos;
10072 index += pos;
10073 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10074 if (pos < 0)
10075 break;
10076 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10077 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010078 }
10079 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010080 int rkind = skind;
10081 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010082 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010083
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010084 if (kind1 < rkind) {
10085 /* widen substring */
10086 buf1 = _PyUnicode_AsKind(str1, rkind);
10087 if (!buf1) goto error;
10088 release1 = 1;
10089 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010090 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010091 if (i < 0)
10092 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010093 if (rkind > kind2) {
10094 /* widen replacement */
10095 buf2 = _PyUnicode_AsKind(str2, rkind);
10096 if (!buf2) goto error;
10097 release2 = 1;
10098 }
10099 else if (rkind < kind2) {
10100 /* widen self and buf1 */
10101 rkind = kind2;
10102 if (release1) PyMem_Free(buf1);
10103 sbuf = _PyUnicode_AsKind(self, rkind);
10104 if (!sbuf) goto error;
10105 srelease = 1;
10106 buf1 = _PyUnicode_AsKind(str1, rkind);
10107 if (!buf1) goto error;
10108 release1 = 1;
10109 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010110 u = PyUnicode_New(slen, maxchar);
10111 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010112 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010113 assert(PyUnicode_KIND(u) == rkind);
10114 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010115
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010116 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010117 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010118 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010119 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010120 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010121 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010122
10123 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010124 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010125 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010126 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010127 if (i == -1)
10128 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010129 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010130 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010131 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010132 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010133 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010134 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010135 }
10136 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010137 Py_ssize_t n, i, j, ires;
10138 Py_ssize_t product, new_size;
10139 int rkind = skind;
10140 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010142 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010143 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010144 buf1 = _PyUnicode_AsKind(str1, rkind);
10145 if (!buf1) goto error;
10146 release1 = 1;
10147 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010148 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010149 if (n == 0)
10150 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010152 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 buf2 = _PyUnicode_AsKind(str2, rkind);
10154 if (!buf2) goto error;
10155 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010156 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010158 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 rkind = kind2;
10160 sbuf = _PyUnicode_AsKind(self, rkind);
10161 if (!sbuf) goto error;
10162 srelease = 1;
10163 if (release1) PyMem_Free(buf1);
10164 buf1 = _PyUnicode_AsKind(str1, rkind);
10165 if (!buf1) goto error;
10166 release1 = 1;
10167 }
10168 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10169 PyUnicode_GET_LENGTH(str1))); */
10170 product = n * (len2-len1);
10171 if ((product / (len2-len1)) != n) {
10172 PyErr_SetString(PyExc_OverflowError,
10173 "replace string is too long");
10174 goto error;
10175 }
10176 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010177 if (new_size == 0) {
10178 Py_INCREF(unicode_empty);
10179 u = unicode_empty;
10180 goto done;
10181 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010182 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10183 PyErr_SetString(PyExc_OverflowError,
10184 "replace string is too long");
10185 goto error;
10186 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010187 u = PyUnicode_New(new_size, maxchar);
10188 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010189 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010190 assert(PyUnicode_KIND(u) == rkind);
10191 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010192 ires = i = 0;
10193 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010194 while (n-- > 0) {
10195 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010196 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010197 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010198 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010199 if (j == -1)
10200 break;
10201 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010202 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010203 memcpy(res + rkind * ires,
10204 sbuf + rkind * i,
10205 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010206 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010207 }
10208 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010209 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010210 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010211 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010212 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010213 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010214 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010216 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010218 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010219 memcpy(res + rkind * ires,
10220 sbuf + rkind * i,
10221 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010222 }
10223 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010224 /* interleave */
10225 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010226 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010227 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010228 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010230 if (--n <= 0)
10231 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010232 memcpy(res + rkind * ires,
10233 sbuf + rkind * i,
10234 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010235 ires++;
10236 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010237 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010238 memcpy(res + rkind * ires,
10239 sbuf + rkind * i,
10240 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010241 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010242 }
10243
10244 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010245 unicode_adjust_maxchar(&u);
10246 if (u == NULL)
10247 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010248 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010249
10250 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010251 if (srelease)
10252 PyMem_FREE(sbuf);
10253 if (release1)
10254 PyMem_FREE(buf1);
10255 if (release2)
10256 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010257 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010258 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010259
Benjamin Peterson29060642009-01-31 22:14:21 +000010260 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010261 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010262 if (srelease)
10263 PyMem_FREE(sbuf);
10264 if (release1)
10265 PyMem_FREE(buf1);
10266 if (release2)
10267 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010268 return unicode_result_unchanged(self);
10269
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 error:
10271 if (srelease && sbuf)
10272 PyMem_FREE(sbuf);
10273 if (release1 && buf1)
10274 PyMem_FREE(buf1);
10275 if (release2 && buf2)
10276 PyMem_FREE(buf2);
10277 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010278}
10279
10280/* --- Unicode Object Methods --------------------------------------------- */
10281
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010282PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010283 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010284\n\
10285Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010286characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010287
10288static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010289unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010290{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010291 if (PyUnicode_READY(self) == -1)
10292 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010293 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010294}
10295
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010296PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010297 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010298\n\
10299Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010300have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010301
10302static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010303unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010304{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010305 if (PyUnicode_READY(self) == -1)
10306 return NULL;
10307 if (PyUnicode_GET_LENGTH(self) == 0)
10308 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010309 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010310}
10311
Benjamin Petersond5890c82012-01-14 13:23:30 -050010312PyDoc_STRVAR(casefold__doc__,
10313 "S.casefold() -> str\n\
10314\n\
10315Return a version of S suitable for caseless comparisons.");
10316
10317static PyObject *
10318unicode_casefold(PyObject *self)
10319{
10320 if (PyUnicode_READY(self) == -1)
10321 return NULL;
10322 if (PyUnicode_IS_ASCII(self))
10323 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010324 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010325}
10326
10327
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010328/* Argument converter. Coerces to a single unicode character */
10329
10330static int
10331convert_uc(PyObject *obj, void *addr)
10332{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010333 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010334 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010335
Benjamin Peterson14339b62009-01-31 16:36:08 +000010336 uniobj = PyUnicode_FromObject(obj);
10337 if (uniobj == NULL) {
10338 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010339 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010340 return 0;
10341 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010343 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010344 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010345 Py_DECREF(uniobj);
10346 return 0;
10347 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010348 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010349 Py_DECREF(uniobj);
10350 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010351}
10352
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010353PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010354 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010355\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010356Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010357done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010358
10359static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010360unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010361{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010362 Py_ssize_t marg, left;
10363 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010364 Py_UCS4 fillchar = ' ';
10365
Victor Stinnere9a29352011-10-01 02:14:59 +020010366 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010367 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010368
Benjamin Petersonbac79492012-01-14 13:34:47 -050010369 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010370 return NULL;
10371
Victor Stinnerc4b49542011-12-11 22:44:26 +010010372 if (PyUnicode_GET_LENGTH(self) >= width)
10373 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010374
Victor Stinnerc4b49542011-12-11 22:44:26 +010010375 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010376 left = marg / 2 + (marg & width & 1);
10377
Victor Stinner9310abb2011-10-05 00:59:23 +020010378 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010379}
10380
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010381/* This function assumes that str1 and str2 are readied by the caller. */
10382
Marc-André Lemburge5034372000-08-08 08:04:29 +000010383static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010384unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010385{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010386 int kind1, kind2;
10387 void *data1, *data2;
10388 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010389
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390 kind1 = PyUnicode_KIND(str1);
10391 kind2 = PyUnicode_KIND(str2);
10392 data1 = PyUnicode_DATA(str1);
10393 data2 = PyUnicode_DATA(str2);
10394 len1 = PyUnicode_GET_LENGTH(str1);
10395 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010396
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010397 for (i = 0; i < len1 && i < len2; ++i) {
10398 Py_UCS4 c1, c2;
10399 c1 = PyUnicode_READ(kind1, data1, i);
10400 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010401
10402 if (c1 != c2)
10403 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010404 }
10405
10406 return (len1 < len2) ? -1 : (len1 != len2);
10407}
10408
Alexander Belopolsky40018472011-02-26 01:02:56 +000010409int
10410PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010411{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010412 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10413 if (PyUnicode_READY(left) == -1 ||
10414 PyUnicode_READY(right) == -1)
10415 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010416 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010417 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010418 PyErr_Format(PyExc_TypeError,
10419 "Can't compare %.100s and %.100s",
10420 left->ob_type->tp_name,
10421 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010422 return -1;
10423}
10424
Martin v. Löwis5b222132007-06-10 09:51:05 +000010425int
10426PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10427{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010428 Py_ssize_t i;
10429 int kind;
10430 void *data;
10431 Py_UCS4 chr;
10432
Victor Stinner910337b2011-10-03 03:20:16 +020010433 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010434 if (PyUnicode_READY(uni) == -1)
10435 return -1;
10436 kind = PyUnicode_KIND(uni);
10437 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010438 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10440 if (chr != str[i])
10441 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010442 /* This check keeps Python strings that end in '\0' from comparing equal
10443 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010444 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010445 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010446 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010447 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010448 return 0;
10449}
10450
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010451
Benjamin Peterson29060642009-01-31 22:14:21 +000010452#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010453 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010454
Alexander Belopolsky40018472011-02-26 01:02:56 +000010455PyObject *
10456PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010457{
10458 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010459
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010460 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10461 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010462 if (PyUnicode_READY(left) == -1 ||
10463 PyUnicode_READY(right) == -1)
10464 return NULL;
10465 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10466 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010467 if (op == Py_EQ) {
10468 Py_INCREF(Py_False);
10469 return Py_False;
10470 }
10471 if (op == Py_NE) {
10472 Py_INCREF(Py_True);
10473 return Py_True;
10474 }
10475 }
10476 if (left == right)
10477 result = 0;
10478 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010479 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010480
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010481 /* Convert the return value to a Boolean */
10482 switch (op) {
10483 case Py_EQ:
10484 v = TEST_COND(result == 0);
10485 break;
10486 case Py_NE:
10487 v = TEST_COND(result != 0);
10488 break;
10489 case Py_LE:
10490 v = TEST_COND(result <= 0);
10491 break;
10492 case Py_GE:
10493 v = TEST_COND(result >= 0);
10494 break;
10495 case Py_LT:
10496 v = TEST_COND(result == -1);
10497 break;
10498 case Py_GT:
10499 v = TEST_COND(result == 1);
10500 break;
10501 default:
10502 PyErr_BadArgument();
10503 return NULL;
10504 }
10505 Py_INCREF(v);
10506 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010507 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010508
Brian Curtindfc80e32011-08-10 20:28:54 -050010509 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010510}
10511
Alexander Belopolsky40018472011-02-26 01:02:56 +000010512int
10513PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010514{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010515 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010516 int kind1, kind2, kind;
10517 void *buf1, *buf2;
10518 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010519 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010520
10521 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010522 sub = PyUnicode_FromObject(element);
10523 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010524 PyErr_Format(PyExc_TypeError,
10525 "'in <string>' requires string as left operand, not %s",
10526 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010527 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010528 }
10529
Thomas Wouters477c8d52006-05-27 19:21:47 +000010530 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010531 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010532 Py_DECREF(sub);
10533 return -1;
10534 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010535 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10536 Py_DECREF(sub);
10537 Py_DECREF(str);
10538 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010539
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010540 kind1 = PyUnicode_KIND(str);
10541 kind2 = PyUnicode_KIND(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010542 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010543 buf1 = PyUnicode_DATA(str);
10544 buf2 = PyUnicode_DATA(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010545 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010546 if (kind2 > kind) {
10547 Py_DECREF(sub);
10548 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010549 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010550 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010010551 buf2 = _PyUnicode_AsKind(sub, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010552 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010553 if (!buf2) {
10554 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010555 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010556 return -1;
10557 }
10558 len1 = PyUnicode_GET_LENGTH(str);
10559 len2 = PyUnicode_GET_LENGTH(sub);
10560
Benjamin Petersonead6b532011-12-20 17:23:42 -060010561 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010562 case PyUnicode_1BYTE_KIND:
10563 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10564 break;
10565 case PyUnicode_2BYTE_KIND:
10566 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10567 break;
10568 case PyUnicode_4BYTE_KIND:
10569 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10570 break;
10571 default:
10572 result = -1;
10573 assert(0);
10574 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010575
10576 Py_DECREF(str);
10577 Py_DECREF(sub);
10578
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010579 if (kind2 != kind)
10580 PyMem_Free(buf2);
10581
Guido van Rossum403d68b2000-03-13 15:55:09 +000010582 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010583}
10584
Guido van Rossumd57fd912000-03-10 22:53:23 +000010585/* Concat to string or Unicode object giving a new Unicode object. */
10586
Alexander Belopolsky40018472011-02-26 01:02:56 +000010587PyObject *
10588PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010589{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010590 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010591 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010592 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010593
10594 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010595 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010596 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010597 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010598 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010599 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010600 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010601
10602 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010603 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010604 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010605 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010606 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010607 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010608 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010609 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010610 }
10611
Victor Stinner488fa492011-12-12 00:01:39 +010010612 u_len = PyUnicode_GET_LENGTH(u);
10613 v_len = PyUnicode_GET_LENGTH(v);
10614 if (u_len > PY_SSIZE_T_MAX - v_len) {
10615 PyErr_SetString(PyExc_OverflowError,
10616 "strings are too large to concat");
10617 goto onError;
10618 }
10619 new_len = u_len + v_len;
10620
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010621 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010622 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Victor Stinnere6abb482012-05-02 01:15:40 +020010623 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624
Guido van Rossumd57fd912000-03-10 22:53:23 +000010625 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010626 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010627 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010628 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010629 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
10630 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010631 Py_DECREF(u);
10632 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010633 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010634 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010635
Benjamin Peterson29060642009-01-31 22:14:21 +000010636 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010637 Py_XDECREF(u);
10638 Py_XDECREF(v);
10639 return NULL;
10640}
10641
Walter Dörwald1ab83302007-05-18 17:15:44 +000010642void
Victor Stinner23e56682011-10-03 03:54:37 +020010643PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010644{
Victor Stinner23e56682011-10-03 03:54:37 +020010645 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010646 Py_UCS4 maxchar, maxchar2;
10647 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010648
10649 if (p_left == NULL) {
10650 if (!PyErr_Occurred())
10651 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010652 return;
10653 }
Victor Stinner23e56682011-10-03 03:54:37 +020010654 left = *p_left;
10655 if (right == NULL || !PyUnicode_Check(left)) {
10656 if (!PyErr_Occurred())
10657 PyErr_BadInternalCall();
10658 goto error;
10659 }
10660
Benjamin Petersonbac79492012-01-14 13:34:47 -050010661 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010662 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050010663 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020010664 goto error;
10665
Victor Stinner488fa492011-12-12 00:01:39 +010010666 /* Shortcuts */
10667 if (left == unicode_empty) {
10668 Py_DECREF(left);
10669 Py_INCREF(right);
10670 *p_left = right;
10671 return;
10672 }
10673 if (right == unicode_empty)
10674 return;
10675
10676 left_len = PyUnicode_GET_LENGTH(left);
10677 right_len = PyUnicode_GET_LENGTH(right);
10678 if (left_len > PY_SSIZE_T_MAX - right_len) {
10679 PyErr_SetString(PyExc_OverflowError,
10680 "strings are too large to concat");
10681 goto error;
10682 }
10683 new_len = left_len + right_len;
10684
10685 if (unicode_modifiable(left)
10686 && PyUnicode_CheckExact(right)
10687 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020010688 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10689 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010690 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010691 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010010692 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
10693 {
10694 /* append inplace */
10695 if (unicode_resize(p_left, new_len) != 0) {
10696 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10697 * deallocated so it cannot be put back into
10698 * 'variable'. The MemoryError is raised when there
10699 * is no value in 'variable', which might (very
10700 * remotely) be a cause of incompatibilities.
10701 */
10702 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020010703 }
Victor Stinner488fa492011-12-12 00:01:39 +010010704 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerd3f08822012-05-29 12:57:52 +020010705 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020010706 }
Victor Stinner488fa492011-12-12 00:01:39 +010010707 else {
10708 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
10709 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Victor Stinnere6abb482012-05-02 01:15:40 +020010710 maxchar = MAX_MAXCHAR(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020010711
Victor Stinner488fa492011-12-12 00:01:39 +010010712 /* Concat the two Unicode strings */
10713 res = PyUnicode_New(new_len, maxchar);
10714 if (res == NULL)
10715 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020010716 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
10717 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010010718 Py_DECREF(left);
10719 *p_left = res;
10720 }
10721 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010722 return;
10723
10724error:
Victor Stinner488fa492011-12-12 00:01:39 +010010725 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010726}
10727
10728void
10729PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10730{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010731 PyUnicode_Append(pleft, right);
10732 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010733}
10734
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010735PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010736 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010737\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010738Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010739string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010740interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010741
10742static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010743unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010744{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010745 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010746 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010747 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010748 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010749 int kind1, kind2, kind;
10750 void *buf1, *buf2;
10751 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010752
Jesus Ceaac451502011-04-20 17:09:23 +020010753 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10754 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010755 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010756
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010757 kind1 = PyUnicode_KIND(self);
10758 kind2 = PyUnicode_KIND(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040010759 if (kind2 > kind1)
10760 return PyLong_FromLong(0);
10761 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010762 buf1 = PyUnicode_DATA(self);
10763 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010764 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010765 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010766 if (!buf2) {
10767 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010768 return NULL;
10769 }
10770 len1 = PyUnicode_GET_LENGTH(self);
10771 len2 = PyUnicode_GET_LENGTH(substring);
10772
10773 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060010774 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010775 case PyUnicode_1BYTE_KIND:
10776 iresult = ucs1lib_count(
10777 ((Py_UCS1*)buf1) + start, end - start,
10778 buf2, len2, PY_SSIZE_T_MAX
10779 );
10780 break;
10781 case PyUnicode_2BYTE_KIND:
10782 iresult = ucs2lib_count(
10783 ((Py_UCS2*)buf1) + start, end - start,
10784 buf2, len2, PY_SSIZE_T_MAX
10785 );
10786 break;
10787 case PyUnicode_4BYTE_KIND:
10788 iresult = ucs4lib_count(
10789 ((Py_UCS4*)buf1) + start, end - start,
10790 buf2, len2, PY_SSIZE_T_MAX
10791 );
10792 break;
10793 default:
10794 assert(0); iresult = 0;
10795 }
10796
10797 result = PyLong_FromSsize_t(iresult);
10798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010799 if (kind2 != kind)
10800 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010801
10802 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010803
Guido van Rossumd57fd912000-03-10 22:53:23 +000010804 return result;
10805}
10806
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010807PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010808 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010809\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010810Encode S using the codec registered for encoding. Default encoding\n\
10811is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010812handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010813a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10814'xmlcharrefreplace' as well as any other name registered with\n\
10815codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010816
10817static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010818unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010819{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010820 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010821 char *encoding = NULL;
10822 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010823
Benjamin Peterson308d6372009-09-18 21:42:35 +000010824 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10825 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010826 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010827 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010828}
10829
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010830PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010831 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010832\n\
10833Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010834If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010835
10836static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010837unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010838{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010839 Py_ssize_t i, j, line_pos, src_len, incr;
10840 Py_UCS4 ch;
10841 PyObject *u;
10842 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010843 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010844 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010845 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010846
10847 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010848 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010849
Antoine Pitrou22425222011-10-04 19:10:51 +020010850 if (PyUnicode_READY(self) == -1)
10851 return NULL;
10852
Thomas Wouters7e474022000-07-16 12:04:32 +000010853 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010854 src_len = PyUnicode_GET_LENGTH(self);
10855 i = j = line_pos = 0;
10856 kind = PyUnicode_KIND(self);
10857 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010858 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010859 for (; i < src_len; i++) {
10860 ch = PyUnicode_READ(kind, src_data, i);
10861 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010862 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010863 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010864 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010865 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010866 goto overflow;
10867 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010868 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010869 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010870 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010871 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010872 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010873 goto overflow;
10874 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010875 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010876 if (ch == '\n' || ch == '\r')
10877 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010878 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010879 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010010880 if (!found)
10881 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010882
Guido van Rossumd57fd912000-03-10 22:53:23 +000010883 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010884 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010885 if (!u)
10886 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010887 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010888
Antoine Pitroue71d5742011-10-04 15:55:09 +020010889 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010890
Antoine Pitroue71d5742011-10-04 15:55:09 +020010891 for (; i < src_len; i++) {
10892 ch = PyUnicode_READ(kind, src_data, i);
10893 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010894 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010895 incr = tabsize - (line_pos % tabsize);
10896 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010010897 FILL(kind, dest_data, ' ', j, incr);
10898 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010899 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010900 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010901 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010902 line_pos++;
10903 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010904 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010905 if (ch == '\n' || ch == '\r')
10906 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010907 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010908 }
10909 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010010910 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010911
Antoine Pitroue71d5742011-10-04 15:55:09 +020010912 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010913 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10914 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010915}
10916
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010917PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010918 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010919\n\
10920Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010921such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010922arguments start and end are interpreted as in slice notation.\n\
10923\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010924Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010925
10926static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010927unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010928{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010929 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010930 Py_ssize_t start;
10931 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010932 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010933
Jesus Ceaac451502011-04-20 17:09:23 +020010934 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10935 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010936 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010937
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010938 if (PyUnicode_READY(self) == -1)
10939 return NULL;
10940 if (PyUnicode_READY(substring) == -1)
10941 return NULL;
10942
Victor Stinner7931d9a2011-11-04 00:22:48 +010010943 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010944
10945 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010946
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010947 if (result == -2)
10948 return NULL;
10949
Christian Heimes217cfd12007-12-02 14:31:20 +000010950 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010951}
10952
10953static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010954unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010955{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010956 void *data;
10957 enum PyUnicode_Kind kind;
10958 Py_UCS4 ch;
10959 PyObject *res;
10960
10961 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
10962 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010963 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020010964 }
10965 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
10966 PyErr_SetString(PyExc_IndexError, "string index out of range");
10967 return NULL;
10968 }
10969 kind = PyUnicode_KIND(self);
10970 data = PyUnicode_DATA(self);
10971 ch = PyUnicode_READ(kind, data, index);
10972 if (ch < 256)
10973 return get_latin1_char(ch);
10974
10975 res = PyUnicode_New(1, ch);
10976 if (res == NULL)
10977 return NULL;
10978 kind = PyUnicode_KIND(res);
10979 data = PyUnicode_DATA(res);
10980 PyUnicode_WRITE(kind, data, 0, ch);
10981 assert(_PyUnicode_CheckConsistency(res, 1));
10982 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010983}
10984
Guido van Rossumc2504932007-09-18 19:42:40 +000010985/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010010986 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000010987static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010988unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010989{
Guido van Rossumc2504932007-09-18 19:42:40 +000010990 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010010991 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010992
Benjamin Petersonf6622c82012-04-09 14:53:07 -040010993#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050010994 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040010995#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010996 if (_PyUnicode_HASH(self) != -1)
10997 return _PyUnicode_HASH(self);
10998 if (PyUnicode_READY(self) == -1)
10999 return -1;
11000 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011001 /*
11002 We make the hash of the empty string be 0, rather than using
11003 (prefix ^ suffix), since this slightly obfuscates the hash secret
11004 */
11005 if (len == 0) {
11006 _PyUnicode_HASH(self) = 0;
11007 return 0;
11008 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011009
11010 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011011#define HASH(P) \
11012 x ^= (Py_uhash_t) *P << 7; \
11013 while (--len >= 0) \
11014 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011015
Georg Brandl2fb477c2012-02-21 00:33:36 +010011016 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011017 switch (PyUnicode_KIND(self)) {
11018 case PyUnicode_1BYTE_KIND: {
11019 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11020 HASH(c);
11021 break;
11022 }
11023 case PyUnicode_2BYTE_KIND: {
11024 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11025 HASH(s);
11026 break;
11027 }
11028 default: {
11029 Py_UCS4 *l;
11030 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11031 "Impossible switch case in unicode_hash");
11032 l = PyUnicode_4BYTE_DATA(self);
11033 HASH(l);
11034 break;
11035 }
11036 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011037 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11038 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011039
Guido van Rossumc2504932007-09-18 19:42:40 +000011040 if (x == -1)
11041 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011042 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011043 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011045#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011046
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011047PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011048 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011049\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011050Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011051
11052static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011053unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011054{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011055 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011056 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011057 Py_ssize_t start;
11058 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011059
Jesus Ceaac451502011-04-20 17:09:23 +020011060 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11061 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011062 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011063
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011064 if (PyUnicode_READY(self) == -1)
11065 return NULL;
11066 if (PyUnicode_READY(substring) == -1)
11067 return NULL;
11068
Victor Stinner7931d9a2011-11-04 00:22:48 +010011069 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011070
11071 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011072
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011073 if (result == -2)
11074 return NULL;
11075
Guido van Rossumd57fd912000-03-10 22:53:23 +000011076 if (result < 0) {
11077 PyErr_SetString(PyExc_ValueError, "substring not found");
11078 return NULL;
11079 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011080
Christian Heimes217cfd12007-12-02 14:31:20 +000011081 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011082}
11083
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011084PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011085 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011086\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011087Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011088at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011089
11090static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011091unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011092{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011093 Py_ssize_t i, length;
11094 int kind;
11095 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011096 int cased;
11097
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011098 if (PyUnicode_READY(self) == -1)
11099 return NULL;
11100 length = PyUnicode_GET_LENGTH(self);
11101 kind = PyUnicode_KIND(self);
11102 data = PyUnicode_DATA(self);
11103
Guido van Rossumd57fd912000-03-10 22:53:23 +000011104 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011105 if (length == 1)
11106 return PyBool_FromLong(
11107 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011108
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011109 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011110 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011111 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011112
Guido van Rossumd57fd912000-03-10 22:53:23 +000011113 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011114 for (i = 0; i < length; i++) {
11115 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011116
Benjamin Peterson29060642009-01-31 22:14:21 +000011117 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11118 return PyBool_FromLong(0);
11119 else if (!cased && Py_UNICODE_ISLOWER(ch))
11120 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011121 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011122 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011123}
11124
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011125PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011126 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011127\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011128Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011129at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011130
11131static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011132unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011133{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011134 Py_ssize_t i, length;
11135 int kind;
11136 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011137 int cased;
11138
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011139 if (PyUnicode_READY(self) == -1)
11140 return NULL;
11141 length = PyUnicode_GET_LENGTH(self);
11142 kind = PyUnicode_KIND(self);
11143 data = PyUnicode_DATA(self);
11144
Guido van Rossumd57fd912000-03-10 22:53:23 +000011145 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011146 if (length == 1)
11147 return PyBool_FromLong(
11148 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011149
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011150 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011151 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011152 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011153
Guido van Rossumd57fd912000-03-10 22:53:23 +000011154 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011155 for (i = 0; i < length; i++) {
11156 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011157
Benjamin Peterson29060642009-01-31 22:14:21 +000011158 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11159 return PyBool_FromLong(0);
11160 else if (!cased && Py_UNICODE_ISUPPER(ch))
11161 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011162 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011163 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011164}
11165
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011166PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011167 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011168\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011169Return True if S is a titlecased string and there is at least one\n\
11170character in S, i.e. upper- and titlecase characters may only\n\
11171follow uncased characters and lowercase characters only cased ones.\n\
11172Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173
11174static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011175unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011176{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011177 Py_ssize_t i, length;
11178 int kind;
11179 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011180 int cased, previous_is_cased;
11181
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011182 if (PyUnicode_READY(self) == -1)
11183 return NULL;
11184 length = PyUnicode_GET_LENGTH(self);
11185 kind = PyUnicode_KIND(self);
11186 data = PyUnicode_DATA(self);
11187
Guido van Rossumd57fd912000-03-10 22:53:23 +000011188 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011189 if (length == 1) {
11190 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11191 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11192 (Py_UNICODE_ISUPPER(ch) != 0));
11193 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011194
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011195 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011196 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011197 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011198
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199 cased = 0;
11200 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011201 for (i = 0; i < length; i++) {
11202 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011203
Benjamin Peterson29060642009-01-31 22:14:21 +000011204 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11205 if (previous_is_cased)
11206 return PyBool_FromLong(0);
11207 previous_is_cased = 1;
11208 cased = 1;
11209 }
11210 else if (Py_UNICODE_ISLOWER(ch)) {
11211 if (!previous_is_cased)
11212 return PyBool_FromLong(0);
11213 previous_is_cased = 1;
11214 cased = 1;
11215 }
11216 else
11217 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011219 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011220}
11221
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011222PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011223 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011225Return True if all characters in S are whitespace\n\
11226and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011227
11228static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011229unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011231 Py_ssize_t i, length;
11232 int kind;
11233 void *data;
11234
11235 if (PyUnicode_READY(self) == -1)
11236 return NULL;
11237 length = PyUnicode_GET_LENGTH(self);
11238 kind = PyUnicode_KIND(self);
11239 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011240
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011242 if (length == 1)
11243 return PyBool_FromLong(
11244 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011245
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011246 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011247 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011248 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011249
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011250 for (i = 0; i < length; i++) {
11251 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011252 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011253 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011254 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011255 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011256}
11257
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011258PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011259 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011260\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011261Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011262and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011263
11264static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011265unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011266{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011267 Py_ssize_t i, length;
11268 int kind;
11269 void *data;
11270
11271 if (PyUnicode_READY(self) == -1)
11272 return NULL;
11273 length = PyUnicode_GET_LENGTH(self);
11274 kind = PyUnicode_KIND(self);
11275 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011276
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011277 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011278 if (length == 1)
11279 return PyBool_FromLong(
11280 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011281
11282 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011283 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011284 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011285
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011286 for (i = 0; i < length; i++) {
11287 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011288 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011289 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011290 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011291}
11292
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011293PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011294 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011295\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011296Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011297and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011298
11299static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011300unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011301{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011302 int kind;
11303 void *data;
11304 Py_ssize_t len, i;
11305
11306 if (PyUnicode_READY(self) == -1)
11307 return NULL;
11308
11309 kind = PyUnicode_KIND(self);
11310 data = PyUnicode_DATA(self);
11311 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011312
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011313 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011314 if (len == 1) {
11315 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11316 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11317 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011318
11319 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011320 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011321 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011322
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011323 for (i = 0; i < len; i++) {
11324 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011325 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011326 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011327 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011328 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011329}
11330
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011331PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011332 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011333\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011334Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011335False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011336
11337static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011338unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011339{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011340 Py_ssize_t i, length;
11341 int kind;
11342 void *data;
11343
11344 if (PyUnicode_READY(self) == -1)
11345 return NULL;
11346 length = PyUnicode_GET_LENGTH(self);
11347 kind = PyUnicode_KIND(self);
11348 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011349
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011351 if (length == 1)
11352 return PyBool_FromLong(
11353 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011354
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011355 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011356 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011357 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011358
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011359 for (i = 0; i < length; i++) {
11360 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011361 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011362 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011363 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011364}
11365
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011366PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011367 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011368\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011369Return True if all characters in S are digits\n\
11370and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011371
11372static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011373unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011374{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011375 Py_ssize_t i, length;
11376 int kind;
11377 void *data;
11378
11379 if (PyUnicode_READY(self) == -1)
11380 return NULL;
11381 length = PyUnicode_GET_LENGTH(self);
11382 kind = PyUnicode_KIND(self);
11383 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011384
Guido van Rossumd57fd912000-03-10 22:53:23 +000011385 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011386 if (length == 1) {
11387 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11388 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11389 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011390
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011391 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011392 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011393 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011394
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011395 for (i = 0; i < length; i++) {
11396 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011397 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011399 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011400}
11401
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011402PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011403 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011404\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011405Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011406False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407
11408static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011409unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011410{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011411 Py_ssize_t i, length;
11412 int kind;
11413 void *data;
11414
11415 if (PyUnicode_READY(self) == -1)
11416 return NULL;
11417 length = PyUnicode_GET_LENGTH(self);
11418 kind = PyUnicode_KIND(self);
11419 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011422 if (length == 1)
11423 return PyBool_FromLong(
11424 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011425
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011426 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011427 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011428 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011429
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011430 for (i = 0; i < length; i++) {
11431 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011432 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011434 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435}
11436
Martin v. Löwis47383402007-08-15 07:32:56 +000011437int
11438PyUnicode_IsIdentifier(PyObject *self)
11439{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011440 int kind;
11441 void *data;
11442 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011443 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011444
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011445 if (PyUnicode_READY(self) == -1) {
11446 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011447 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011448 }
11449
11450 /* Special case for empty strings */
11451 if (PyUnicode_GET_LENGTH(self) == 0)
11452 return 0;
11453 kind = PyUnicode_KIND(self);
11454 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011455
11456 /* PEP 3131 says that the first character must be in
11457 XID_Start and subsequent characters in XID_Continue,
11458 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011459 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011460 letters, digits, underscore). However, given the current
11461 definition of XID_Start and XID_Continue, it is sufficient
11462 to check just for these, except that _ must be allowed
11463 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011464 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011465 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011466 return 0;
11467
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011468 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011469 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011470 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011471 return 1;
11472}
11473
11474PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011475 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011476\n\
11477Return True if S is a valid identifier according\n\
11478to the language definition.");
11479
11480static PyObject*
11481unicode_isidentifier(PyObject *self)
11482{
11483 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11484}
11485
Georg Brandl559e5d72008-06-11 18:37:52 +000011486PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011487 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011488\n\
11489Return True if all characters in S are considered\n\
11490printable in repr() or S is empty, False otherwise.");
11491
11492static PyObject*
11493unicode_isprintable(PyObject *self)
11494{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011495 Py_ssize_t i, length;
11496 int kind;
11497 void *data;
11498
11499 if (PyUnicode_READY(self) == -1)
11500 return NULL;
11501 length = PyUnicode_GET_LENGTH(self);
11502 kind = PyUnicode_KIND(self);
11503 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011504
11505 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011506 if (length == 1)
11507 return PyBool_FromLong(
11508 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011509
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011510 for (i = 0; i < length; i++) {
11511 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011512 Py_RETURN_FALSE;
11513 }
11514 }
11515 Py_RETURN_TRUE;
11516}
11517
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011518PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011519 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520\n\
11521Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011522iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011523
11524static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011525unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011526{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011527 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011528}
11529
Martin v. Löwis18e16552006-02-15 17:27:45 +000011530static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011531unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011533 if (PyUnicode_READY(self) == -1)
11534 return -1;
11535 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011536}
11537
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011538PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011539 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011541Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011542done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011543
11544static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011545unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011546{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011547 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011548 Py_UCS4 fillchar = ' ';
11549
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011550 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011551 return NULL;
11552
Benjamin Petersonbac79492012-01-14 13:34:47 -050011553 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011554 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555
Victor Stinnerc4b49542011-12-11 22:44:26 +010011556 if (PyUnicode_GET_LENGTH(self) >= width)
11557 return unicode_result_unchanged(self);
11558
11559 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560}
11561
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011562PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011563 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011565Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011566
11567static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011568unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011570 if (PyUnicode_READY(self) == -1)
11571 return NULL;
11572 if (PyUnicode_IS_ASCII(self))
11573 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011574 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011575}
11576
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011577#define LEFTSTRIP 0
11578#define RIGHTSTRIP 1
11579#define BOTHSTRIP 2
11580
11581/* Arrays indexed by above */
11582static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11583
11584#define STRIPNAME(i) (stripformat[i]+3)
11585
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011586/* externally visible for str.strip(unicode) */
11587PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011588_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011589{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011590 void *data;
11591 int kind;
11592 Py_ssize_t i, j, len;
11593 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011594
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011595 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11596 return NULL;
11597
11598 kind = PyUnicode_KIND(self);
11599 data = PyUnicode_DATA(self);
11600 len = PyUnicode_GET_LENGTH(self);
11601 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11602 PyUnicode_DATA(sepobj),
11603 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011604
Benjamin Peterson14339b62009-01-31 16:36:08 +000011605 i = 0;
11606 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011607 while (i < len &&
11608 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011609 i++;
11610 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011611 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011612
Benjamin Peterson14339b62009-01-31 16:36:08 +000011613 j = len;
11614 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011615 do {
11616 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011617 } while (j >= i &&
11618 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011619 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011620 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011621
Victor Stinner7931d9a2011-11-04 00:22:48 +010011622 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011623}
11624
11625PyObject*
11626PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11627{
11628 unsigned char *data;
11629 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011630 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011631
Victor Stinnerde636f32011-10-01 03:55:54 +020011632 if (PyUnicode_READY(self) == -1)
11633 return NULL;
11634
Victor Stinner684d5fd2012-05-03 02:32:34 +020011635 length = PyUnicode_GET_LENGTH(self);
11636 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011637
Victor Stinner684d5fd2012-05-03 02:32:34 +020011638 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011639 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011640
Victor Stinnerde636f32011-10-01 03:55:54 +020011641 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011642 PyErr_SetString(PyExc_IndexError, "string index out of range");
11643 return NULL;
11644 }
Victor Stinner684d5fd2012-05-03 02:32:34 +020011645 if (start >= length || end < start) {
Victor Stinner3a7f7972012-05-03 03:36:40 +020011646 Py_INCREF(unicode_empty);
11647 return unicode_empty;
Victor Stinner684d5fd2012-05-03 02:32:34 +020011648 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020011649
Victor Stinner684d5fd2012-05-03 02:32:34 +020011650 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020011651 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020011652 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020011653 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020011654 }
11655 else {
11656 kind = PyUnicode_KIND(self);
11657 data = PyUnicode_1BYTE_DATA(self);
11658 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011659 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011660 length);
11661 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011662}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011663
11664static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011665do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011666{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011667 int kind;
11668 void *data;
11669 Py_ssize_t len, i, j;
11670
11671 if (PyUnicode_READY(self) == -1)
11672 return NULL;
11673
11674 kind = PyUnicode_KIND(self);
11675 data = PyUnicode_DATA(self);
11676 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011677
Benjamin Peterson14339b62009-01-31 16:36:08 +000011678 i = 0;
11679 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011680 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011681 i++;
11682 }
11683 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011684
Benjamin Peterson14339b62009-01-31 16:36:08 +000011685 j = len;
11686 if (striptype != LEFTSTRIP) {
11687 do {
11688 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011689 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011690 j++;
11691 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011692
Victor Stinner7931d9a2011-11-04 00:22:48 +010011693 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011694}
11695
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011696
11697static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011698do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011699{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011700 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011701
Benjamin Peterson14339b62009-01-31 16:36:08 +000011702 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11703 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011704
Benjamin Peterson14339b62009-01-31 16:36:08 +000011705 if (sep != NULL && sep != Py_None) {
11706 if (PyUnicode_Check(sep))
11707 return _PyUnicode_XStrip(self, striptype, sep);
11708 else {
11709 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011710 "%s arg must be None or str",
11711 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011712 return NULL;
11713 }
11714 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011715
Benjamin Peterson14339b62009-01-31 16:36:08 +000011716 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011717}
11718
11719
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011720PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011721 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011722\n\
11723Return a copy of the string S with leading and trailing\n\
11724whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011725If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011726
11727static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011728unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011729{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011730 if (PyTuple_GET_SIZE(args) == 0)
11731 return do_strip(self, BOTHSTRIP); /* Common case */
11732 else
11733 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011734}
11735
11736
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011737PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011738 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011739\n\
11740Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011741If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011742
11743static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011744unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011745{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011746 if (PyTuple_GET_SIZE(args) == 0)
11747 return do_strip(self, LEFTSTRIP); /* Common case */
11748 else
11749 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011750}
11751
11752
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011753PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011754 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011755\n\
11756Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011757If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011758
11759static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011760unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011761{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011762 if (PyTuple_GET_SIZE(args) == 0)
11763 return do_strip(self, RIGHTSTRIP); /* Common case */
11764 else
11765 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011766}
11767
11768
Guido van Rossumd57fd912000-03-10 22:53:23 +000011769static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011770unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011771{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011772 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011773 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774
Georg Brandl222de0f2009-04-12 12:01:50 +000011775 if (len < 1) {
11776 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011777 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011778 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011779
Victor Stinnerc4b49542011-12-11 22:44:26 +010011780 /* no repeat, return original string */
11781 if (len == 1)
11782 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000011783
Benjamin Petersonbac79492012-01-14 13:34:47 -050011784 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011785 return NULL;
11786
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011787 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011788 PyErr_SetString(PyExc_OverflowError,
11789 "repeated string is too long");
11790 return NULL;
11791 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011792 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011793
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011794 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011795 if (!u)
11796 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011797 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011799 if (PyUnicode_GET_LENGTH(str) == 1) {
11800 const int kind = PyUnicode_KIND(str);
11801 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010011802 if (kind == PyUnicode_1BYTE_KIND) {
11803 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011804 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010011805 }
11806 else if (kind == PyUnicode_2BYTE_KIND) {
11807 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011808 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010011809 ucs2[n] = fill_char;
11810 } else {
11811 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
11812 assert(kind == PyUnicode_4BYTE_KIND);
11813 for (n = 0; n < len; ++n)
11814 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011815 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011816 }
11817 else {
11818 /* number of characters copied this far */
11819 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011820 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011821 char *to = (char *) PyUnicode_DATA(u);
11822 Py_MEMCPY(to, PyUnicode_DATA(str),
11823 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011824 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011825 n = (done <= nchars-done) ? done : nchars-done;
11826 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011827 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011828 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011829 }
11830
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011831 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011832 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011833}
11834
Alexander Belopolsky40018472011-02-26 01:02:56 +000011835PyObject *
11836PyUnicode_Replace(PyObject *obj,
11837 PyObject *subobj,
11838 PyObject *replobj,
11839 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011840{
11841 PyObject *self;
11842 PyObject *str1;
11843 PyObject *str2;
11844 PyObject *result;
11845
11846 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011847 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011848 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011849 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011850 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011851 Py_DECREF(self);
11852 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011853 }
11854 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011855 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011856 Py_DECREF(self);
11857 Py_DECREF(str1);
11858 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011859 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011860 if (PyUnicode_READY(self) == -1 ||
11861 PyUnicode_READY(str1) == -1 ||
11862 PyUnicode_READY(str2) == -1)
11863 result = NULL;
11864 else
11865 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866 Py_DECREF(self);
11867 Py_DECREF(str1);
11868 Py_DECREF(str2);
11869 return result;
11870}
11871
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011872PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011873 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011874\n\
11875Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011876old replaced by new. If the optional argument count is\n\
11877given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011878
11879static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011880unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011881{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011882 PyObject *str1;
11883 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011884 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885 PyObject *result;
11886
Martin v. Löwis18e16552006-02-15 17:27:45 +000011887 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011888 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060011889 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011890 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011891 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011892 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011893 return NULL;
11894 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011895 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011896 Py_DECREF(str1);
11897 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011898 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060011899 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
11900 result = NULL;
11901 else
11902 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011903
11904 Py_DECREF(str1);
11905 Py_DECREF(str2);
11906 return result;
11907}
11908
Alexander Belopolsky40018472011-02-26 01:02:56 +000011909static PyObject *
11910unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011911{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011912 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011913 Py_ssize_t isize;
11914 Py_ssize_t osize, squote, dquote, i, o;
11915 Py_UCS4 max, quote;
11916 int ikind, okind;
11917 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011918
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011919 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011920 return NULL;
11921
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011922 isize = PyUnicode_GET_LENGTH(unicode);
11923 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011924
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011925 /* Compute length of output, quote characters, and
11926 maximum character */
11927 osize = 2; /* quotes */
11928 max = 127;
11929 squote = dquote = 0;
11930 ikind = PyUnicode_KIND(unicode);
11931 for (i = 0; i < isize; i++) {
11932 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11933 switch (ch) {
11934 case '\'': squote++; osize++; break;
11935 case '"': dquote++; osize++; break;
11936 case '\\': case '\t': case '\r': case '\n':
11937 osize += 2; break;
11938 default:
11939 /* Fast-path ASCII */
11940 if (ch < ' ' || ch == 0x7f)
11941 osize += 4; /* \xHH */
11942 else if (ch < 0x7f)
11943 osize++;
11944 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11945 osize++;
11946 max = ch > max ? ch : max;
11947 }
11948 else if (ch < 0x100)
11949 osize += 4; /* \xHH */
11950 else if (ch < 0x10000)
11951 osize += 6; /* \uHHHH */
11952 else
11953 osize += 10; /* \uHHHHHHHH */
11954 }
11955 }
11956
11957 quote = '\'';
11958 if (squote) {
11959 if (dquote)
11960 /* Both squote and dquote present. Use squote,
11961 and escape them */
11962 osize += squote;
11963 else
11964 quote = '"';
11965 }
11966
11967 repr = PyUnicode_New(osize, max);
11968 if (repr == NULL)
11969 return NULL;
11970 okind = PyUnicode_KIND(repr);
11971 odata = PyUnicode_DATA(repr);
11972
11973 PyUnicode_WRITE(okind, odata, 0, quote);
11974 PyUnicode_WRITE(okind, odata, osize-1, quote);
11975
11976 for (i = 0, o = 1; i < isize; i++) {
11977 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011978
11979 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011980 if ((ch == quote) || (ch == '\\')) {
11981 PyUnicode_WRITE(okind, odata, o++, '\\');
11982 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011983 continue;
11984 }
11985
Benjamin Peterson29060642009-01-31 22:14:21 +000011986 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011987 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011988 PyUnicode_WRITE(okind, odata, o++, '\\');
11989 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011990 }
11991 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011992 PyUnicode_WRITE(okind, odata, o++, '\\');
11993 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011994 }
11995 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011996 PyUnicode_WRITE(okind, odata, o++, '\\');
11997 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011998 }
11999
12000 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012001 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012002 PyUnicode_WRITE(okind, odata, o++, '\\');
12003 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012004 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12005 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012006 }
12007
Georg Brandl559e5d72008-06-11 18:37:52 +000012008 /* Copy ASCII characters as-is */
12009 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012010 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012011 }
12012
Benjamin Peterson29060642009-01-31 22:14:21 +000012013 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012014 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012015 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012016 (categories Z* and C* except ASCII space)
12017 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012018 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012019 PyUnicode_WRITE(okind, odata, o++, '\\');
Georg Brandl559e5d72008-06-11 18:37:52 +000012020 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012021 if (ch <= 0xff) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012022 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012023 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12024 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012025 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012026 /* Map 16-bit characters to '\uxxxx' */
12027 else if (ch <= 0xffff) {
12028 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012029 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12030 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12031 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12032 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012033 }
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012034 /* Map 21-bit characters to '\U00xxxxxx' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012035 else {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012036 PyUnicode_WRITE(okind, odata, o++, 'U');
12037 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12038 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12039 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12040 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
Victor Stinnerf5cff562011-10-14 02:13:11 +020012041 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12042 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12043 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12044 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012045 }
12046 }
12047 /* Copy characters as-is */
12048 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012049 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012050 }
12051 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012052 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012053 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012054 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012055 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012056}
12057
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012058PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012059 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012060\n\
12061Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012062such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012063arguments start and end are interpreted as in slice notation.\n\
12064\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012065Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012066
12067static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012068unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012069{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012070 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012071 Py_ssize_t start;
12072 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012073 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012074
Jesus Ceaac451502011-04-20 17:09:23 +020012075 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12076 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012077 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012078
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012079 if (PyUnicode_READY(self) == -1)
12080 return NULL;
12081 if (PyUnicode_READY(substring) == -1)
12082 return NULL;
12083
Victor Stinner7931d9a2011-11-04 00:22:48 +010012084 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012085
12086 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012088 if (result == -2)
12089 return NULL;
12090
Christian Heimes217cfd12007-12-02 14:31:20 +000012091 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012092}
12093
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012094PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012095 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012096\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012097Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012098
12099static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012100unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012101{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012102 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012103 Py_ssize_t start;
12104 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012105 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012106
Jesus Ceaac451502011-04-20 17:09:23 +020012107 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12108 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012109 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012110
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012111 if (PyUnicode_READY(self) == -1)
12112 return NULL;
12113 if (PyUnicode_READY(substring) == -1)
12114 return NULL;
12115
Victor Stinner7931d9a2011-11-04 00:22:48 +010012116 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012117
12118 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012119
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012120 if (result == -2)
12121 return NULL;
12122
Guido van Rossumd57fd912000-03-10 22:53:23 +000012123 if (result < 0) {
12124 PyErr_SetString(PyExc_ValueError, "substring not found");
12125 return NULL;
12126 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012127
Christian Heimes217cfd12007-12-02 14:31:20 +000012128 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012129}
12130
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012131PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012132 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012133\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012134Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012135done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012136
12137static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012138unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012139{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012140 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012141 Py_UCS4 fillchar = ' ';
12142
Victor Stinnere9a29352011-10-01 02:14:59 +020012143 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012144 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012145
Benjamin Petersonbac79492012-01-14 13:34:47 -050012146 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012147 return NULL;
12148
Victor Stinnerc4b49542011-12-11 22:44:26 +010012149 if (PyUnicode_GET_LENGTH(self) >= width)
12150 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012151
Victor Stinnerc4b49542011-12-11 22:44:26 +010012152 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012153}
12154
Alexander Belopolsky40018472011-02-26 01:02:56 +000012155PyObject *
12156PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012157{
12158 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012159
Guido van Rossumd57fd912000-03-10 22:53:23 +000012160 s = PyUnicode_FromObject(s);
12161 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012162 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012163 if (sep != NULL) {
12164 sep = PyUnicode_FromObject(sep);
12165 if (sep == NULL) {
12166 Py_DECREF(s);
12167 return NULL;
12168 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012169 }
12170
Victor Stinner9310abb2011-10-05 00:59:23 +020012171 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012172
12173 Py_DECREF(s);
12174 Py_XDECREF(sep);
12175 return result;
12176}
12177
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012178PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012179 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012180\n\
12181Return a list of the words in S, using sep as the\n\
12182delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012183splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012184whitespace string is a separator and empty strings are\n\
12185removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012186
12187static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012188unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012189{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012190 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012191 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012192 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012193
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012194 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12195 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012196 return NULL;
12197
12198 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012199 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012200 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012201 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012202 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012203 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012204}
12205
Thomas Wouters477c8d52006-05-27 19:21:47 +000012206PyObject *
12207PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12208{
12209 PyObject* str_obj;
12210 PyObject* sep_obj;
12211 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012212 int kind1, kind2, kind;
12213 void *buf1 = NULL, *buf2 = NULL;
12214 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012215
12216 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012217 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012218 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012219 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012220 if (!sep_obj) {
12221 Py_DECREF(str_obj);
12222 return NULL;
12223 }
12224 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12225 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012226 Py_DECREF(str_obj);
12227 return NULL;
12228 }
12229
Victor Stinner14f8f022011-10-05 20:58:25 +020012230 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012231 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012232 kind = Py_MAX(kind1, kind2);
12233 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012234 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012235 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012236 if (!buf1)
12237 goto onError;
12238 buf2 = PyUnicode_DATA(sep_obj);
12239 if (kind2 != kind)
12240 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12241 if (!buf2)
12242 goto onError;
12243 len1 = PyUnicode_GET_LENGTH(str_obj);
12244 len2 = PyUnicode_GET_LENGTH(sep_obj);
12245
Benjamin Petersonead6b532011-12-20 17:23:42 -060012246 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012247 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012248 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12249 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12250 else
12251 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012252 break;
12253 case PyUnicode_2BYTE_KIND:
12254 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12255 break;
12256 case PyUnicode_4BYTE_KIND:
12257 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12258 break;
12259 default:
12260 assert(0);
12261 out = 0;
12262 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012263
12264 Py_DECREF(sep_obj);
12265 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012266 if (kind1 != kind)
12267 PyMem_Free(buf1);
12268 if (kind2 != kind)
12269 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012270
12271 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012272 onError:
12273 Py_DECREF(sep_obj);
12274 Py_DECREF(str_obj);
12275 if (kind1 != kind && buf1)
12276 PyMem_Free(buf1);
12277 if (kind2 != kind && buf2)
12278 PyMem_Free(buf2);
12279 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012280}
12281
12282
12283PyObject *
12284PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12285{
12286 PyObject* str_obj;
12287 PyObject* sep_obj;
12288 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012289 int kind1, kind2, kind;
12290 void *buf1 = NULL, *buf2 = NULL;
12291 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012292
12293 str_obj = PyUnicode_FromObject(str_in);
12294 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012295 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012296 sep_obj = PyUnicode_FromObject(sep_in);
12297 if (!sep_obj) {
12298 Py_DECREF(str_obj);
12299 return NULL;
12300 }
12301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012302 kind1 = PyUnicode_KIND(str_in);
12303 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012304 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012305 buf1 = PyUnicode_DATA(str_in);
12306 if (kind1 != kind)
12307 buf1 = _PyUnicode_AsKind(str_in, kind);
12308 if (!buf1)
12309 goto onError;
12310 buf2 = PyUnicode_DATA(sep_obj);
12311 if (kind2 != kind)
12312 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12313 if (!buf2)
12314 goto onError;
12315 len1 = PyUnicode_GET_LENGTH(str_obj);
12316 len2 = PyUnicode_GET_LENGTH(sep_obj);
12317
Benjamin Petersonead6b532011-12-20 17:23:42 -060012318 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012319 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012320 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12321 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12322 else
12323 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012324 break;
12325 case PyUnicode_2BYTE_KIND:
12326 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12327 break;
12328 case PyUnicode_4BYTE_KIND:
12329 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12330 break;
12331 default:
12332 assert(0);
12333 out = 0;
12334 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012335
12336 Py_DECREF(sep_obj);
12337 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012338 if (kind1 != kind)
12339 PyMem_Free(buf1);
12340 if (kind2 != kind)
12341 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012342
12343 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012344 onError:
12345 Py_DECREF(sep_obj);
12346 Py_DECREF(str_obj);
12347 if (kind1 != kind && buf1)
12348 PyMem_Free(buf1);
12349 if (kind2 != kind && buf2)
12350 PyMem_Free(buf2);
12351 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012352}
12353
12354PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012355 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012356\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012357Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012358the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012359found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012360
12361static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012362unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012363{
Victor Stinner9310abb2011-10-05 00:59:23 +020012364 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012365}
12366
12367PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012368 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012369\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012370Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012371the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012372separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012373
12374static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012375unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012376{
Victor Stinner9310abb2011-10-05 00:59:23 +020012377 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012378}
12379
Alexander Belopolsky40018472011-02-26 01:02:56 +000012380PyObject *
12381PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012382{
12383 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012384
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012385 s = PyUnicode_FromObject(s);
12386 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012387 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012388 if (sep != NULL) {
12389 sep = PyUnicode_FromObject(sep);
12390 if (sep == NULL) {
12391 Py_DECREF(s);
12392 return NULL;
12393 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012394 }
12395
Victor Stinner9310abb2011-10-05 00:59:23 +020012396 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012397
12398 Py_DECREF(s);
12399 Py_XDECREF(sep);
12400 return result;
12401}
12402
12403PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012404 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012405\n\
12406Return a list of the words in S, using sep as the\n\
12407delimiter string, starting at the end of the string and\n\
12408working to the front. If maxsplit is given, at most maxsplit\n\
12409splits are done. If sep is not specified, any whitespace string\n\
12410is a separator.");
12411
12412static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012413unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012414{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012415 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012416 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012417 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012418
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012419 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12420 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012421 return NULL;
12422
12423 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012424 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012425 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012426 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012427 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012428 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012429}
12430
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012431PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012432 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012433\n\
12434Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012435Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012436is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012437
12438static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012439unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012440{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012441 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012442 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012443
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012444 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12445 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012446 return NULL;
12447
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012448 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012449}
12450
12451static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012452PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012453{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012454 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012455}
12456
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012457PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012458 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012459\n\
12460Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012461and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012462
12463static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012464unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012465{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012466 if (PyUnicode_READY(self) == -1)
12467 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012468 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012469}
12470
Georg Brandlceee0772007-11-27 23:48:05 +000012471PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012472 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012473\n\
12474Return a translation table usable for str.translate().\n\
12475If there is only one argument, it must be a dictionary mapping Unicode\n\
12476ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012477Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012478If there are two arguments, they must be strings of equal length, and\n\
12479in the resulting dictionary, each character in x will be mapped to the\n\
12480character at the same position in y. If there is a third argument, it\n\
12481must be a string, whose characters will be mapped to None in the result.");
12482
12483static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012484unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012485{
12486 PyObject *x, *y = NULL, *z = NULL;
12487 PyObject *new = NULL, *key, *value;
12488 Py_ssize_t i = 0;
12489 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012490
Georg Brandlceee0772007-11-27 23:48:05 +000012491 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12492 return NULL;
12493 new = PyDict_New();
12494 if (!new)
12495 return NULL;
12496 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012497 int x_kind, y_kind, z_kind;
12498 void *x_data, *y_data, *z_data;
12499
Georg Brandlceee0772007-11-27 23:48:05 +000012500 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012501 if (!PyUnicode_Check(x)) {
12502 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12503 "be a string if there is a second argument");
12504 goto err;
12505 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012506 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012507 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12508 "arguments must have equal length");
12509 goto err;
12510 }
12511 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012512 x_kind = PyUnicode_KIND(x);
12513 y_kind = PyUnicode_KIND(y);
12514 x_data = PyUnicode_DATA(x);
12515 y_data = PyUnicode_DATA(y);
12516 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12517 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012518 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012519 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012520 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012521 if (!value) {
12522 Py_DECREF(key);
12523 goto err;
12524 }
Georg Brandlceee0772007-11-27 23:48:05 +000012525 res = PyDict_SetItem(new, key, value);
12526 Py_DECREF(key);
12527 Py_DECREF(value);
12528 if (res < 0)
12529 goto err;
12530 }
12531 /* create entries for deleting chars in z */
12532 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012533 z_kind = PyUnicode_KIND(z);
12534 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012535 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012536 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012537 if (!key)
12538 goto err;
12539 res = PyDict_SetItem(new, key, Py_None);
12540 Py_DECREF(key);
12541 if (res < 0)
12542 goto err;
12543 }
12544 }
12545 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012546 int kind;
12547 void *data;
12548
Georg Brandlceee0772007-11-27 23:48:05 +000012549 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012550 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012551 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12552 "to maketrans it must be a dict");
12553 goto err;
12554 }
12555 /* copy entries into the new dict, converting string keys to int keys */
12556 while (PyDict_Next(x, &i, &key, &value)) {
12557 if (PyUnicode_Check(key)) {
12558 /* convert string keys to integer keys */
12559 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012560 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012561 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12562 "table must be of length 1");
12563 goto err;
12564 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012565 kind = PyUnicode_KIND(key);
12566 data = PyUnicode_DATA(key);
12567 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012568 if (!newkey)
12569 goto err;
12570 res = PyDict_SetItem(new, newkey, value);
12571 Py_DECREF(newkey);
12572 if (res < 0)
12573 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012574 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012575 /* just keep integer keys */
12576 if (PyDict_SetItem(new, key, value) < 0)
12577 goto err;
12578 } else {
12579 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12580 "be strings or integers");
12581 goto err;
12582 }
12583 }
12584 }
12585 return new;
12586 err:
12587 Py_DECREF(new);
12588 return NULL;
12589}
12590
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012591PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012592 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012593\n\
12594Return a copy of the string S, where all characters have been mapped\n\
12595through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012596Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012597Unmapped characters are left untouched. Characters mapped to None\n\
12598are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012599
12600static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012601unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012602{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012603 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012604}
12605
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012606PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012607 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012608\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012609Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012610
12611static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012612unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012613{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012614 if (PyUnicode_READY(self) == -1)
12615 return NULL;
12616 if (PyUnicode_IS_ASCII(self))
12617 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012618 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012619}
12620
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012621PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012622 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012623\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012624Pad a numeric string S with zeros on the left, to fill a field\n\
12625of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626
12627static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012628unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012629{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012630 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012631 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012632 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012633 int kind;
12634 void *data;
12635 Py_UCS4 chr;
12636
Martin v. Löwis18e16552006-02-15 17:27:45 +000012637 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012638 return NULL;
12639
Benjamin Petersonbac79492012-01-14 13:34:47 -050012640 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012641 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012642
Victor Stinnerc4b49542011-12-11 22:44:26 +010012643 if (PyUnicode_GET_LENGTH(self) >= width)
12644 return unicode_result_unchanged(self);
12645
12646 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012647
12648 u = pad(self, fill, 0, '0');
12649
Walter Dörwald068325e2002-04-15 13:36:47 +000012650 if (u == NULL)
12651 return NULL;
12652
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012653 kind = PyUnicode_KIND(u);
12654 data = PyUnicode_DATA(u);
12655 chr = PyUnicode_READ(kind, data, fill);
12656
12657 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012658 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012659 PyUnicode_WRITE(kind, data, 0, chr);
12660 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012661 }
12662
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012663 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012664 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012665}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012666
12667#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012668static PyObject *
12669unicode__decimal2ascii(PyObject *self)
12670{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012671 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012672}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012673#endif
12674
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012675PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012676 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012677\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012678Return True if S starts with the specified prefix, False otherwise.\n\
12679With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012680With optional end, stop comparing S at that position.\n\
12681prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012682
12683static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012684unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012685 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012686{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012687 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012688 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012689 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012690 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012691 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012692
Jesus Ceaac451502011-04-20 17:09:23 +020012693 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012694 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012695 if (PyTuple_Check(subobj)) {
12696 Py_ssize_t i;
12697 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012698 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012699 if (substring == NULL)
12700 return NULL;
12701 result = tailmatch(self, substring, start, end, -1);
12702 Py_DECREF(substring);
12703 if (result) {
12704 Py_RETURN_TRUE;
12705 }
12706 }
12707 /* nothing matched */
12708 Py_RETURN_FALSE;
12709 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012710 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012711 if (substring == NULL) {
12712 if (PyErr_ExceptionMatches(PyExc_TypeError))
12713 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12714 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012715 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012716 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012717 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012718 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012719 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012720}
12721
12722
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012723PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012724 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012725\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012726Return True if S ends with the specified suffix, False otherwise.\n\
12727With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012728With optional end, stop comparing S at that position.\n\
12729suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012730
12731static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012732unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012733 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012734{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012735 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012736 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012737 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012738 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012739 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012740
Jesus Ceaac451502011-04-20 17:09:23 +020012741 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012742 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012743 if (PyTuple_Check(subobj)) {
12744 Py_ssize_t i;
12745 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012746 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012747 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012748 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012749 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012750 result = tailmatch(self, substring, start, end, +1);
12751 Py_DECREF(substring);
12752 if (result) {
12753 Py_RETURN_TRUE;
12754 }
12755 }
12756 Py_RETURN_FALSE;
12757 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012758 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012759 if (substring == NULL) {
12760 if (PyErr_ExceptionMatches(PyExc_TypeError))
12761 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12762 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012763 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012764 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012765 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012766 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012767 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012768}
12769
Victor Stinner202fdca2012-05-07 12:47:02 +020012770Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012771_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012772{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012773 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012774 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
12775 writer->data = PyUnicode_DATA(writer->buffer);
12776 writer->kind = PyUnicode_KIND(writer->buffer);
12777}
12778
Victor Stinnerd3f08822012-05-29 12:57:52 +020012779void
12780_PyUnicodeWriter_Init(_PyUnicodeWriter *writer, Py_ssize_t min_length)
Victor Stinner202fdca2012-05-07 12:47:02 +020012781{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012782 memset(writer, 0, sizeof(*writer));
12783#ifdef Py_DEBUG
12784 writer->kind = 5; /* invalid kind */
12785#endif
12786 writer->min_length = Py_MAX(min_length, 100);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012787 writer->overallocate = (min_length > 0);
Victor Stinner202fdca2012-05-07 12:47:02 +020012788}
12789
Victor Stinnerd3f08822012-05-29 12:57:52 +020012790int
12791_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
12792 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020012793{
12794 Py_ssize_t newlen;
12795 PyObject *newbuffer;
12796
Victor Stinnerd3f08822012-05-29 12:57:52 +020012797 assert(length > 0);
12798
Victor Stinner202fdca2012-05-07 12:47:02 +020012799 if (length > PY_SSIZE_T_MAX - writer->pos) {
12800 PyErr_NoMemory();
12801 return -1;
12802 }
12803 newlen = writer->pos + length;
12804
Victor Stinnerd3f08822012-05-29 12:57:52 +020012805 if (writer->buffer == NULL) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012806 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012807 /* overallocate 25% to limit the number of resize */
12808 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12809 newlen += newlen / 4;
12810 if (newlen < writer->min_length)
12811 newlen = writer->min_length;
12812 }
12813 writer->buffer = PyUnicode_New(newlen, maxchar);
12814 if (writer->buffer == NULL)
12815 return -1;
12816 _PyUnicodeWriter_Update(writer);
12817 return 0;
12818 }
Victor Stinner202fdca2012-05-07 12:47:02 +020012819
Victor Stinnerd3f08822012-05-29 12:57:52 +020012820 if (newlen > writer->size) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012821 if (writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012822 /* overallocate 25% to limit the number of resize */
12823 if (newlen <= (PY_SSIZE_T_MAX - newlen / 4))
12824 newlen += newlen / 4;
12825 if (newlen < writer->min_length)
12826 newlen = writer->min_length;
12827 }
12828
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012829 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020012830 /* resize + widen */
12831 newbuffer = PyUnicode_New(newlen, maxchar);
12832 if (newbuffer == NULL)
12833 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012834 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12835 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020012836 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012837 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020012838 }
12839 else {
12840 newbuffer = resize_compact(writer->buffer, newlen);
12841 if (newbuffer == NULL)
12842 return -1;
12843 }
12844 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012845 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012846 }
12847 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012848 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012849 newbuffer = PyUnicode_New(writer->size, maxchar);
12850 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020012851 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012852 _PyUnicode_FastCopyCharacters(newbuffer, 0,
12853 writer->buffer, 0, writer->pos);
12854 Py_DECREF(writer->buffer);
12855 writer->buffer = newbuffer;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012856 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020012857 }
12858 return 0;
12859}
12860
Victor Stinnerd3f08822012-05-29 12:57:52 +020012861int
12862_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
12863{
12864 Py_UCS4 maxchar;
12865 Py_ssize_t len;
12866
12867 if (PyUnicode_READY(str) == -1)
12868 return -1;
12869 len = PyUnicode_GET_LENGTH(str);
12870 if (len == 0)
12871 return 0;
12872 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
12873 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012874 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012875 Py_INCREF(str);
12876 writer->buffer = str;
12877 _PyUnicodeWriter_Update(writer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012878 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020012879 writer->size = 0;
12880 writer->pos += len;
12881 return 0;
12882 }
12883 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
12884 return -1;
12885 }
12886 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
12887 str, 0, len);
12888 writer->pos += len;
12889 return 0;
12890}
12891
12892PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012893_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012894{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012895 if (writer->pos == 0) {
12896 Py_XDECREF(writer->buffer);
12897 Py_INCREF(unicode_empty);
12898 return unicode_empty;
12899 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020012900 if (writer->readonly) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020012901 assert(PyUnicode_GET_LENGTH(writer->buffer) == writer->pos);
12902 return writer->buffer;
12903 }
12904 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
12905 PyObject *newbuffer;
12906 newbuffer = resize_compact(writer->buffer, writer->pos);
12907 if (newbuffer == NULL) {
12908 Py_DECREF(writer->buffer);
12909 return NULL;
12910 }
12911 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020012912 }
Victor Stinnerf59c28c2012-05-09 03:24:14 +020012913 assert(_PyUnicode_CheckConsistency(writer->buffer, 1));
Victor Stinner202fdca2012-05-07 12:47:02 +020012914 return writer->buffer;
12915}
12916
Victor Stinnerd3f08822012-05-29 12:57:52 +020012917void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020012918_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020012919{
12920 Py_CLEAR(writer->buffer);
12921}
12922
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012923#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012924
12925PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012926 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012927\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012928Return a formatted version of S, using substitutions from args and kwargs.\n\
12929The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012930
Eric Smith27bbca62010-11-04 17:06:58 +000012931PyDoc_STRVAR(format_map__doc__,
12932 "S.format_map(mapping) -> str\n\
12933\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012934Return a formatted version of S, using substitutions from mapping.\n\
12935The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012936
Eric Smith4a7d76d2008-05-30 18:10:19 +000012937static PyObject *
12938unicode__format__(PyObject* self, PyObject* args)
12939{
Victor Stinnerd3f08822012-05-29 12:57:52 +020012940 PyObject *format_spec;
12941 _PyUnicodeWriter writer;
12942 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012943
12944 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12945 return NULL;
12946
Victor Stinnerd3f08822012-05-29 12:57:52 +020012947 if (PyUnicode_READY(self) == -1)
12948 return NULL;
12949 _PyUnicodeWriter_Init(&writer, 0);
12950 ret = _PyUnicode_FormatAdvancedWriter(&writer,
12951 self, format_spec, 0,
12952 PyUnicode_GET_LENGTH(format_spec));
12953 if (ret == -1) {
12954 _PyUnicodeWriter_Dealloc(&writer);
12955 return NULL;
12956 }
12957 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000012958}
12959
Eric Smith8c663262007-08-25 02:26:07 +000012960PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012961 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012962\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012963Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012964
12965static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012966unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012967{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012968 Py_ssize_t size;
12969
12970 /* If it's a compact object, account for base structure +
12971 character data. */
12972 if (PyUnicode_IS_COMPACT_ASCII(v))
12973 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12974 else if (PyUnicode_IS_COMPACT(v))
12975 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012976 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012977 else {
12978 /* If it is a two-block object, account for base object, and
12979 for character block if present. */
12980 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012981 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012982 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012983 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012984 }
12985 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012986 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012987 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012988 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012989 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012990 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012991
12992 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012993}
12994
12995PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012996 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012997
12998static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012999unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013000{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013001 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013002 if (!copy)
13003 return NULL;
13004 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013005}
13006
Guido van Rossumd57fd912000-03-10 22:53:23 +000013007static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013008 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013009 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013010 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13011 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013012 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13013 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013014 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013015 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13016 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13017 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13018 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13019 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013020 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013021 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13022 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13023 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013024 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013025 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13026 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13027 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013028 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013029 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013030 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013031 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013032 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13033 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13034 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13035 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13036 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13037 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13038 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13039 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13040 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13041 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13042 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13043 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13044 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13045 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013046 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013047 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013048 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013049 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013050 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013051 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013052 {"maketrans", (PyCFunction) unicode_maketrans,
13053 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013054 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013055#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013056 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013057 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013058#endif
13059
Benjamin Peterson14339b62009-01-31 16:36:08 +000013060 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013061 {NULL, NULL}
13062};
13063
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013064static PyObject *
13065unicode_mod(PyObject *v, PyObject *w)
13066{
Brian Curtindfc80e32011-08-10 20:28:54 -050013067 if (!PyUnicode_Check(v))
13068 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013069 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013070}
13071
13072static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013073 0, /*nb_add*/
13074 0, /*nb_subtract*/
13075 0, /*nb_multiply*/
13076 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013077};
13078
Guido van Rossumd57fd912000-03-10 22:53:23 +000013079static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013080 (lenfunc) unicode_length, /* sq_length */
13081 PyUnicode_Concat, /* sq_concat */
13082 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13083 (ssizeargfunc) unicode_getitem, /* sq_item */
13084 0, /* sq_slice */
13085 0, /* sq_ass_item */
13086 0, /* sq_ass_slice */
13087 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013088};
13089
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013090static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013091unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013092{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013093 if (PyUnicode_READY(self) == -1)
13094 return NULL;
13095
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013096 if (PyIndex_Check(item)) {
13097 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013098 if (i == -1 && PyErr_Occurred())
13099 return NULL;
13100 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013101 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013102 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013103 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013104 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013105 PyObject *result;
13106 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013107 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013108 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013109
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013110 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013111 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013112 return NULL;
13113 }
13114
13115 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013116 Py_INCREF(unicode_empty);
13117 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013118 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013119 slicelength == PyUnicode_GET_LENGTH(self)) {
13120 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013121 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013122 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013123 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013124 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013125 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013126 src_kind = PyUnicode_KIND(self);
13127 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013128 if (!PyUnicode_IS_ASCII(self)) {
13129 kind_limit = kind_maxchar_limit(src_kind);
13130 max_char = 0;
13131 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13132 ch = PyUnicode_READ(src_kind, src_data, cur);
13133 if (ch > max_char) {
13134 max_char = ch;
13135 if (max_char >= kind_limit)
13136 break;
13137 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013138 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013139 }
Victor Stinner55c99112011-10-13 01:17:06 +020013140 else
13141 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013142 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013143 if (result == NULL)
13144 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013145 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013146 dest_data = PyUnicode_DATA(result);
13147
13148 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013149 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13150 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013151 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013152 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013153 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013154 } else {
13155 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13156 return NULL;
13157 }
13158}
13159
13160static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013161 (lenfunc)unicode_length, /* mp_length */
13162 (binaryfunc)unicode_subscript, /* mp_subscript */
13163 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013164};
13165
Guido van Rossumd57fd912000-03-10 22:53:23 +000013166
Guido van Rossumd57fd912000-03-10 22:53:23 +000013167/* Helpers for PyUnicode_Format() */
13168
13169static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013170getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013171{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013172 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013173 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013174 (*p_argidx)++;
13175 if (arglen < 0)
13176 return args;
13177 else
13178 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013179 }
13180 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013181 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013182 return NULL;
13183}
13184
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013185/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013186
Victor Stinnerd3f08822012-05-29 12:57:52 +020013187static int
13188formatfloat(PyObject *v, int flags, int prec, int type,
13189 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013190{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013191 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013192 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013193 Py_ssize_t len;
Tim Petersced69f82003-09-16 20:30:58 +000013194
Guido van Rossumd57fd912000-03-10 22:53:23 +000013195 x = PyFloat_AsDouble(v);
13196 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013197 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013198
Guido van Rossumd57fd912000-03-10 22:53:23 +000013199 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013200 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013201
Eric Smith0923d1d2009-04-16 20:16:10 +000013202 p = PyOS_double_to_string(x, type, prec,
13203 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013204 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013205 return -1;
13206 len = strlen(p);
13207 if (writer) {
13208 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13209 return -1;
Victor Stinner184252a2012-06-16 02:57:41 +020013210 unicode_write_cstr(writer->buffer, writer->pos, p, len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013211 writer->pos += len;
13212 }
13213 else
13214 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013215 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013216 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013217}
13218
Victor Stinnerd0880d52012-04-27 23:40:13 +020013219/* formatlong() emulates the format codes d, u, o, x and X, and
13220 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13221 * Python's regular ints.
13222 * Return value: a new PyUnicodeObject*, or NULL if error.
13223 * The output string is of the form
13224 * "-"? ("0x" | "0X")? digit+
13225 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13226 * set in flags. The case of hex digits will be correct,
13227 * There will be at least prec digits, zero-filled on the left if
13228 * necessary to get that many.
13229 * val object to be converted
13230 * flags bitmask of format flags; only F_ALT is looked at
13231 * prec minimum number of digits; 0-fill on left if needed
13232 * type a character in [duoxX]; u acts the same as d
13233 *
13234 * CAUTION: o, x and X conversions on regular ints can never
13235 * produce a '-' sign, but can for Python's unbounded ints.
13236 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013237static PyObject*
13238formatlong(PyObject *val, int flags, int prec, int type)
13239{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013240 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013241 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013242 Py_ssize_t i;
13243 int sign; /* 1 if '-', else 0 */
13244 int len; /* number of characters */
13245 Py_ssize_t llen;
13246 int numdigits; /* len == numnondigits + numdigits */
13247 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013248
Victor Stinnerd0880d52012-04-27 23:40:13 +020013249 /* Avoid exceeding SSIZE_T_MAX */
13250 if (prec > INT_MAX-3) {
13251 PyErr_SetString(PyExc_OverflowError,
13252 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013253 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013254 }
13255
13256 assert(PyLong_Check(val));
13257
13258 switch (type) {
13259 case 'd':
13260 case 'u':
13261 /* Special-case boolean: we want 0/1 */
Victor Stinnerb11d91d2012-04-28 00:25:34 +020013262 if (PyBool_Check(val))
13263 result = PyNumber_ToBase(val, 10);
13264 else
13265 result = Py_TYPE(val)->tp_str(val);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013266 break;
13267 case 'o':
13268 numnondigits = 2;
13269 result = PyNumber_ToBase(val, 8);
13270 break;
13271 case 'x':
13272 case 'X':
13273 numnondigits = 2;
13274 result = PyNumber_ToBase(val, 16);
13275 break;
13276 default:
13277 assert(!"'type' not in [duoxX]");
13278 }
13279 if (!result)
13280 return NULL;
13281
13282 assert(unicode_modifiable(result));
13283 assert(PyUnicode_IS_READY(result));
13284 assert(PyUnicode_IS_ASCII(result));
13285
13286 /* To modify the string in-place, there can only be one reference. */
13287 if (Py_REFCNT(result) != 1) {
13288 PyErr_BadInternalCall();
13289 return NULL;
13290 }
13291 buf = PyUnicode_DATA(result);
13292 llen = PyUnicode_GET_LENGTH(result);
13293 if (llen > INT_MAX) {
13294 PyErr_SetString(PyExc_ValueError,
13295 "string too large in _PyBytes_FormatLong");
13296 return NULL;
13297 }
13298 len = (int)llen;
13299 sign = buf[0] == '-';
13300 numnondigits += sign;
13301 numdigits = len - numnondigits;
13302 assert(numdigits > 0);
13303
13304 /* Get rid of base marker unless F_ALT */
13305 if (((flags & F_ALT) == 0 &&
13306 (type == 'o' || type == 'x' || type == 'X'))) {
13307 assert(buf[sign] == '0');
13308 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13309 buf[sign+1] == 'o');
13310 numnondigits -= 2;
13311 buf += 2;
13312 len -= 2;
13313 if (sign)
13314 buf[0] = '-';
13315 assert(len == numnondigits + numdigits);
13316 assert(numdigits > 0);
13317 }
13318
13319 /* Fill with leading zeroes to meet minimum width. */
13320 if (prec > numdigits) {
13321 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13322 numnondigits + prec);
13323 char *b1;
13324 if (!r1) {
13325 Py_DECREF(result);
13326 return NULL;
13327 }
13328 b1 = PyBytes_AS_STRING(r1);
13329 for (i = 0; i < numnondigits; ++i)
13330 *b1++ = *buf++;
13331 for (i = 0; i < prec - numdigits; i++)
13332 *b1++ = '0';
13333 for (i = 0; i < numdigits; i++)
13334 *b1++ = *buf++;
13335 *b1 = '\0';
13336 Py_DECREF(result);
13337 result = r1;
13338 buf = PyBytes_AS_STRING(result);
13339 len = numnondigits + prec;
13340 }
13341
13342 /* Fix up case for hex conversions. */
13343 if (type == 'X') {
13344 /* Need to convert all lower case letters to upper case.
13345 and need to convert 0x to 0X (and -0x to -0X). */
13346 for (i = 0; i < len; i++)
13347 if (buf[i] >= 'a' && buf[i] <= 'x')
13348 buf[i] -= 'a'-'A';
13349 }
13350 if (!PyUnicode_Check(result) || len != PyUnicode_GET_LENGTH(result)) {
13351 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013352 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013353 Py_DECREF(result);
13354 result = unicode;
13355 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013356 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013357}
13358
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013359static Py_UCS4
13360formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013361{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013362 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013363 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013364 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013365 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013366 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013367 goto onError;
13368 }
13369 else {
13370 /* Integer input truncated to a character */
13371 long x;
13372 x = PyLong_AsLong(v);
13373 if (x == -1 && PyErr_Occurred())
13374 goto onError;
13375
Victor Stinner8faf8212011-12-08 22:14:11 +010013376 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013377 PyErr_SetString(PyExc_OverflowError,
13378 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013379 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013380 }
13381
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013382 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013383 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013384
Benjamin Peterson29060642009-01-31 22:14:21 +000013385 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013386 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013387 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013388 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013389}
13390
Alexander Belopolsky40018472011-02-26 01:02:56 +000013391PyObject *
13392PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013393{
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013394 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013395 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013396 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013397 PyObject *temp = NULL;
13398 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013399 PyObject *uformat;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013400 void *fmt;
13401 enum PyUnicode_Kind kind, fmtkind;
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013402 _PyUnicodeWriter writer;
Victor Stinneree4544c2012-05-09 22:24:08 +020013403 Py_ssize_t sublen;
13404 Py_UCS4 maxchar;
Tim Petersced69f82003-09-16 20:30:58 +000013405
Guido van Rossumd57fd912000-03-10 22:53:23 +000013406 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013407 PyErr_BadInternalCall();
13408 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013409 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013410 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013411 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013412 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013413 if (PyUnicode_READY(uformat) == -1)
13414 Py_DECREF(uformat);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013415
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013416 fmt = PyUnicode_DATA(uformat);
13417 fmtkind = PyUnicode_KIND(uformat);
13418 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13419 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013420
Victor Stinnerd3f08822012-05-29 12:57:52 +020013421 _PyUnicodeWriter_Init(&writer, fmtcnt + 100);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013422
Guido van Rossumd57fd912000-03-10 22:53:23 +000013423 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013424 arglen = PyTuple_Size(args);
13425 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013426 }
13427 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013428 arglen = -1;
13429 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013430 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013431 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013432 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013433 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013434
13435 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013436 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013437 Py_ssize_t nonfmtpos;
13438 nonfmtpos = fmtpos++;
13439 while (fmtcnt >= 0 &&
13440 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13441 fmtpos++;
13442 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013443 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013444 if (fmtcnt < 0)
13445 fmtpos--;
Victor Stinneree4544c2012-05-09 22:24:08 +020013446 sublen = fmtpos - nonfmtpos;
13447 maxchar = _PyUnicode_FindMaxChar(uformat,
13448 nonfmtpos, nonfmtpos + sublen);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013449 if (_PyUnicodeWriter_Prepare(&writer, sublen, maxchar) == -1)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013450 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013451
Victor Stinnerd3f08822012-05-29 12:57:52 +020013452 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13453 uformat, nonfmtpos, sublen);
Victor Stinneree4544c2012-05-09 22:24:08 +020013454 writer.pos += sublen;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013455 }
13456 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013457 /* Got a format specifier */
13458 int flags = 0;
13459 Py_ssize_t width = -1;
13460 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013461 Py_UCS4 c = '\0';
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013462 Py_UCS4 fill;
13463 int sign;
13464 Py_UCS4 signchar;
Benjamin Peterson29060642009-01-31 22:14:21 +000013465 int isnumok;
13466 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013467 void *pbuf = NULL;
13468 Py_ssize_t pindex, len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013469 Py_UCS4 bufmaxchar;
13470 Py_ssize_t buflen;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013471
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013472 fmtpos++;
Victor Stinner438106b2012-05-02 00:41:57 +020013473 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13474 if (c == '(') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013475 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013476 Py_ssize_t keylen;
13477 PyObject *key;
13478 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013479
Benjamin Peterson29060642009-01-31 22:14:21 +000013480 if (dict == NULL) {
13481 PyErr_SetString(PyExc_TypeError,
13482 "format requires a mapping");
13483 goto onError;
13484 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013485 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013486 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013487 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013488 /* Skip over balanced parentheses */
13489 while (pcount > 0 && --fmtcnt >= 0) {
Victor Stinnerbff7c962012-05-03 01:44:59 +020013490 c = PyUnicode_READ(fmtkind, fmt, fmtpos);
13491 if (c == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013492 --pcount;
Victor Stinnerbff7c962012-05-03 01:44:59 +020013493 else if (c == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013494 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013495 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013496 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013497 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013498 if (fmtcnt < 0 || pcount > 0) {
13499 PyErr_SetString(PyExc_ValueError,
13500 "incomplete format key");
13501 goto onError;
13502 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013503 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013504 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013505 if (key == NULL)
13506 goto onError;
13507 if (args_owned) {
13508 Py_DECREF(args);
13509 args_owned = 0;
13510 }
13511 args = PyObject_GetItem(dict, key);
13512 Py_DECREF(key);
13513 if (args == NULL) {
13514 goto onError;
13515 }
13516 args_owned = 1;
13517 arglen = -1;
13518 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013519 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013520 while (--fmtcnt >= 0) {
Victor Stinner438106b2012-05-02 00:41:57 +020013521 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
13522 switch (c) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013523 case '-': flags |= F_LJUST; continue;
13524 case '+': flags |= F_SIGN; continue;
13525 case ' ': flags |= F_BLANK; continue;
13526 case '#': flags |= F_ALT; continue;
13527 case '0': flags |= F_ZERO; continue;
13528 }
13529 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013530 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013531 if (c == '*') {
13532 v = getnextarg(args, arglen, &argidx);
13533 if (v == NULL)
13534 goto onError;
13535 if (!PyLong_Check(v)) {
13536 PyErr_SetString(PyExc_TypeError,
13537 "* wants int");
13538 goto onError;
13539 }
13540 width = PyLong_AsLong(v);
13541 if (width == -1 && PyErr_Occurred())
13542 goto onError;
13543 if (width < 0) {
13544 flags |= F_LJUST;
13545 width = -width;
13546 }
13547 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013548 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013549 }
13550 else if (c >= '0' && c <= '9') {
13551 width = c - '0';
13552 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013553 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013554 if (c < '0' || c > '9')
13555 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013556 /* Since c is unsigned, the RHS would end up as unsigned,
13557 mixing signed and unsigned comparison. Since c is between
13558 '0' and '9', casting to int is safe. */
13559 if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013560 PyErr_SetString(PyExc_ValueError,
13561 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013562 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013563 }
13564 width = width*10 + (c - '0');
13565 }
13566 }
13567 if (c == '.') {
13568 prec = 0;
13569 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013570 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013571 if (c == '*') {
13572 v = getnextarg(args, arglen, &argidx);
13573 if (v == NULL)
13574 goto onError;
13575 if (!PyLong_Check(v)) {
13576 PyErr_SetString(PyExc_TypeError,
13577 "* wants int");
13578 goto onError;
13579 }
13580 prec = PyLong_AsLong(v);
13581 if (prec == -1 && PyErr_Occurred())
13582 goto onError;
13583 if (prec < 0)
13584 prec = 0;
13585 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013586 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013587 }
13588 else if (c >= '0' && c <= '9') {
13589 prec = c - '0';
13590 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013591 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013592 if (c < '0' || c > '9')
13593 break;
Martin v. Löwisb05c0732012-05-15 13:45:49 +020013594 if (prec > (INT_MAX - ((int)c - '0')) / 10) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013595 PyErr_SetString(PyExc_ValueError,
13596 "prec too big");
13597 goto onError;
13598 }
13599 prec = prec*10 + (c - '0');
13600 }
13601 }
13602 } /* prec */
13603 if (fmtcnt >= 0) {
13604 if (c == 'h' || c == 'l' || c == 'L') {
13605 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013606 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013607 }
13608 }
13609 if (fmtcnt < 0) {
13610 PyErr_SetString(PyExc_ValueError,
13611 "incomplete format");
13612 goto onError;
13613 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013614 if (fmtcnt == 0)
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013615 writer.overallocate = 0;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013616
13617 if (c == '%') {
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013618 if (_PyUnicodeWriter_Prepare(&writer, 1, '%') == -1)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013619 goto onError;
Victor Stinneree4544c2012-05-09 22:24:08 +020013620 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '%');
13621 writer.pos += 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013622 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013623 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013624
Victor Stinneraff3cc62012-04-30 05:19:21 +020013625 v = getnextarg(args, arglen, &argidx);
13626 if (v == NULL)
13627 goto onError;
13628
Benjamin Peterson29060642009-01-31 22:14:21 +000013629 sign = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013630 signchar = '\0';
Benjamin Peterson29060642009-01-31 22:14:21 +000013631 fill = ' ';
13632 switch (c) {
13633
Benjamin Peterson29060642009-01-31 22:14:21 +000013634 case 's':
13635 case 'r':
13636 case 'a':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013637 if (PyLong_CheckExact(v) && width == -1 && prec == -1) {
13638 /* Fast path */
13639 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13640 goto onError;
13641 goto nextarg;
13642 }
13643
Victor Stinner808fc0a2010-03-22 12:50:40 +000013644 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013645 temp = v;
13646 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013647 }
13648 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013649 if (c == 's')
13650 temp = PyObject_Str(v);
13651 else if (c == 'r')
13652 temp = PyObject_Repr(v);
13653 else
13654 temp = PyObject_ASCII(v);
Benjamin Peterson29060642009-01-31 22:14:21 +000013655 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013656 break;
13657
13658 case 'i':
13659 case 'd':
13660 case 'u':
13661 case 'o':
13662 case 'x':
13663 case 'X':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013664 if (PyLong_CheckExact(v)
13665 && width == -1 && prec == -1
13666 && !(flags & (F_SIGN | F_BLANK)))
13667 {
13668 /* Fast path */
13669 switch(c)
13670 {
13671 case 'd':
13672 case 'i':
13673 case 'u':
13674 if (_PyLong_FormatWriter(&writer, v, 10, flags & F_ALT) == -1)
13675 goto onError;
13676 goto nextarg;
13677 case 'x':
13678 if (_PyLong_FormatWriter(&writer, v, 16, flags & F_ALT) == -1)
13679 goto onError;
13680 goto nextarg;
13681 case 'o':
13682 if (_PyLong_FormatWriter(&writer, v, 8, flags & F_ALT) == -1)
13683 goto onError;
13684 goto nextarg;
13685 default:
13686 break;
13687 }
13688 }
13689
Benjamin Peterson29060642009-01-31 22:14:21 +000013690 isnumok = 0;
13691 if (PyNumber_Check(v)) {
13692 PyObject *iobj=NULL;
13693
13694 if (PyLong_Check(v)) {
13695 iobj = v;
13696 Py_INCREF(iobj);
13697 }
13698 else {
13699 iobj = PyNumber_Long(v);
13700 }
13701 if (iobj!=NULL) {
13702 if (PyLong_Check(iobj)) {
13703 isnumok = 1;
Victor Stinneraff3cc62012-04-30 05:19:21 +020013704 sign = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013705 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013706 Py_DECREF(iobj);
Benjamin Peterson29060642009-01-31 22:14:21 +000013707 }
13708 else {
13709 Py_DECREF(iobj);
13710 }
13711 }
13712 }
13713 if (!isnumok) {
13714 PyErr_Format(PyExc_TypeError,
13715 "%%%c format: a number is required, "
13716 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13717 goto onError;
13718 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013719 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013720 fill = '0';
13721 break;
13722
13723 case 'e':
13724 case 'E':
13725 case 'f':
13726 case 'F':
13727 case 'g':
13728 case 'G':
Victor Stinnerd3f08822012-05-29 12:57:52 +020013729 if (width == -1 && prec == -1
13730 && !(flags & (F_SIGN | F_BLANK)))
13731 {
13732 /* Fast path */
13733 if (formatfloat(v, flags, prec, c, NULL, &writer) == -1)
13734 goto onError;
13735 goto nextarg;
13736 }
13737
Benjamin Peterson29060642009-01-31 22:14:21 +000013738 sign = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013739 if (flags & F_ZERO)
Benjamin Peterson29060642009-01-31 22:14:21 +000013740 fill = '0';
Victor Stinnerd3f08822012-05-29 12:57:52 +020013741 if (formatfloat(v, flags, prec, c, &temp, NULL) == -1)
13742 temp = NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000013743 break;
13744
13745 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013746 {
13747 Py_UCS4 ch = formatchar(v);
13748 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013749 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013750 if (width == -1 && prec == -1) {
13751 /* Fast path */
13752 if (_PyUnicodeWriter_Prepare(&writer, 1, ch) == -1)
13753 goto onError;
13754 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch);
13755 writer.pos += 1;
13756 goto nextarg;
13757 }
Victor Stinnerb5c3ea32012-05-02 00:29:36 +020013758 temp = PyUnicode_FromOrdinal(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +000013759 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013760 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013761
13762 default:
13763 PyErr_Format(PyExc_ValueError,
13764 "unsupported format character '%c' (0x%x) "
13765 "at index %zd",
13766 (31<=c && c<=126) ? (char)c : '?',
13767 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013768 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013769 goto onError;
13770 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020013771 if (temp == NULL)
13772 goto onError;
13773 assert (PyUnicode_Check(temp));
Victor Stinnerd3f08822012-05-29 12:57:52 +020013774
13775 if (width == -1 && prec == -1
13776 && !(flags & (F_SIGN | F_BLANK)))
13777 {
13778 /* Fast path */
13779 if (_PyUnicodeWriter_WriteStr(&writer, temp) == -1)
13780 goto onError;
13781 goto nextarg;
13782 }
13783
Victor Stinneraff3cc62012-04-30 05:19:21 +020013784 if (PyUnicode_READY(temp) == -1) {
13785 Py_CLEAR(temp);
13786 goto onError;
13787 }
13788 kind = PyUnicode_KIND(temp);
13789 pbuf = PyUnicode_DATA(temp);
13790 len = PyUnicode_GET_LENGTH(temp);
13791
13792 if (c == 's' || c == 'r' || c == 'a') {
13793 if (prec >= 0 && len > prec)
13794 len = prec;
13795 }
13796
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013797 /* pbuf is initialized here. */
13798 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013799 if (sign) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013800 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
13801 if (ch == '-' || ch == '+') {
13802 signchar = ch;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013803 len--;
13804 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013805 }
13806 else if (flags & F_SIGN)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013807 signchar = '+';
Benjamin Peterson29060642009-01-31 22:14:21 +000013808 else if (flags & F_BLANK)
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013809 signchar = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +000013810 else
13811 sign = 0;
13812 }
13813 if (width < len)
13814 width = len;
Victor Stinneree4544c2012-05-09 22:24:08 +020013815
13816 /* Compute the length and maximum character of the
13817 written characters */
13818 bufmaxchar = 127;
13819 if (!(flags & F_LJUST)) {
13820 if (sign) {
13821 if ((width-1) > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013822 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013823 }
13824 else {
13825 if (width > len)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013826 bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
Victor Stinneree4544c2012-05-09 22:24:08 +020013827 }
13828 }
13829 maxchar = _PyUnicode_FindMaxChar(temp, 0, pindex+len);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013830 bufmaxchar = MAX_MAXCHAR(bufmaxchar, maxchar);
Victor Stinneree4544c2012-05-09 22:24:08 +020013831
13832 buflen = width;
13833 if (sign && len == width)
13834 buflen++;
13835
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013836 if (_PyUnicodeWriter_Prepare(&writer, buflen, bufmaxchar) == -1)
Victor Stinneree4544c2012-05-09 22:24:08 +020013837 goto onError;
13838
13839 /* Write characters */
Benjamin Peterson29060642009-01-31 22:14:21 +000013840 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013841 if (fill != ' ') {
Victor Stinneree4544c2012-05-09 22:24:08 +020013842 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13843 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013844 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013845 if (width > len)
13846 width--;
13847 }
13848 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013849 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013850 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013851 if (fill != ' ') {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013852 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13853 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13854 writer.pos += 2;
13855 pindex += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +000013856 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013857 width -= 2;
13858 if (width < 0)
13859 width = 0;
13860 len -= 2;
13861 }
13862 if (width > len && !(flags & F_LJUST)) {
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013863 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013864 FILL(writer.kind, writer.data, fill, writer.pos, sublen);
13865 writer.pos += sublen;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013866 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013867 }
13868 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013869 if (sign) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013870 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, signchar);
13871 writer.pos += 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013872 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013873 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013874 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13875 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013876 PyUnicode_WRITE(writer.kind, writer.data, writer.pos, '0');
13877 PyUnicode_WRITE(writer.kind, writer.data, writer.pos+1, c);
13878 writer.pos += 2;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013879 pindex += 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013880 }
13881 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013882
Victor Stinnerc9d369f2012-06-16 02:22:37 +020013883 if (len) {
13884 _PyUnicode_FastCopyCharacters(writer.buffer, writer.pos,
13885 temp, pindex, len);
13886 writer.pos += len;
13887 }
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013888 if (width > len) {
Victor Stinneree4544c2012-05-09 22:24:08 +020013889 sublen = width - len;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020013890 FILL(writer.kind, writer.data, ' ', writer.pos, sublen);
13891 writer.pos += sublen;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013892 }
Victor Stinneree4544c2012-05-09 22:24:08 +020013893
Victor Stinnerd3f08822012-05-29 12:57:52 +020013894nextarg:
Benjamin Peterson29060642009-01-31 22:14:21 +000013895 if (dict && (argidx < arglen) && c != '%') {
13896 PyErr_SetString(PyExc_TypeError,
13897 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013898 goto onError;
13899 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013900 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013901 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013902 } /* until end */
13903 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013904 PyErr_SetString(PyExc_TypeError,
13905 "not all arguments converted during string formatting");
13906 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013907 }
13908
13909 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013910 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013911 }
13912 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013913 Py_XDECREF(temp);
13914 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013915 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013916
Benjamin Peterson29060642009-01-31 22:14:21 +000013917 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013918 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013919 Py_XDECREF(temp);
13920 Py_XDECREF(second);
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013921 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013922 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013923 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013924 }
13925 return NULL;
13926}
13927
Jeremy Hylton938ace62002-07-17 16:30:39 +000013928static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013929unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13930
Tim Peters6d6c1a32001-08-02 04:15:00 +000013931static PyObject *
13932unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13933{
Benjamin Peterson29060642009-01-31 22:14:21 +000013934 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013935 static char *kwlist[] = {"object", "encoding", "errors", 0};
13936 char *encoding = NULL;
13937 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013938
Benjamin Peterson14339b62009-01-31 16:36:08 +000013939 if (type != &PyUnicode_Type)
13940 return unicode_subtype_new(type, args, kwds);
13941 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013942 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013943 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013944 if (x == NULL) {
13945 Py_INCREF(unicode_empty);
13946 return unicode_empty;
13947 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013948 if (encoding == NULL && errors == NULL)
13949 return PyObject_Str(x);
13950 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013951 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013952}
13953
Guido van Rossume023fe02001-08-30 03:12:59 +000013954static PyObject *
13955unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13956{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013957 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013958 Py_ssize_t length, char_size;
13959 int share_wstr, share_utf8;
13960 unsigned int kind;
13961 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013962
Benjamin Peterson14339b62009-01-31 16:36:08 +000013963 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013964
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013965 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013966 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013967 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013968 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050013969 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013970 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013971 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013972 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013973
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013974 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013975 if (self == NULL) {
13976 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013977 return NULL;
13978 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013979 kind = PyUnicode_KIND(unicode);
13980 length = PyUnicode_GET_LENGTH(unicode);
13981
13982 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013983#ifdef Py_DEBUG
13984 _PyUnicode_HASH(self) = -1;
13985#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013986 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013987#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013988 _PyUnicode_STATE(self).interned = 0;
13989 _PyUnicode_STATE(self).kind = kind;
13990 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013991 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013992 _PyUnicode_STATE(self).ready = 1;
13993 _PyUnicode_WSTR(self) = NULL;
13994 _PyUnicode_UTF8_LENGTH(self) = 0;
13995 _PyUnicode_UTF8(self) = NULL;
13996 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013997 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013998
13999 share_utf8 = 0;
14000 share_wstr = 0;
14001 if (kind == PyUnicode_1BYTE_KIND) {
14002 char_size = 1;
14003 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14004 share_utf8 = 1;
14005 }
14006 else if (kind == PyUnicode_2BYTE_KIND) {
14007 char_size = 2;
14008 if (sizeof(wchar_t) == 2)
14009 share_wstr = 1;
14010 }
14011 else {
14012 assert(kind == PyUnicode_4BYTE_KIND);
14013 char_size = 4;
14014 if (sizeof(wchar_t) == 4)
14015 share_wstr = 1;
14016 }
14017
14018 /* Ensure we won't overflow the length. */
14019 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14020 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014021 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014022 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014023 data = PyObject_MALLOC((length + 1) * char_size);
14024 if (data == NULL) {
14025 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014026 goto onError;
14027 }
14028
Victor Stinnerc3c74152011-10-02 20:39:55 +020014029 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014030 if (share_utf8) {
14031 _PyUnicode_UTF8_LENGTH(self) = length;
14032 _PyUnicode_UTF8(self) = data;
14033 }
14034 if (share_wstr) {
14035 _PyUnicode_WSTR_LENGTH(self) = length;
14036 _PyUnicode_WSTR(self) = (wchar_t *)data;
14037 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014038
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014039 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014040 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014041 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014042#ifdef Py_DEBUG
14043 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14044#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014045 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014046 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014047
14048onError:
14049 Py_DECREF(unicode);
14050 Py_DECREF(self);
14051 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014052}
14053
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014054PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000014055 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014056\n\
Collin Winterd474ce82007-08-07 19:42:11 +000014057Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000014058encoding defaults to the current default string encoding.\n\
14059errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014060
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014061static PyObject *unicode_iter(PyObject *seq);
14062
Guido van Rossumd57fd912000-03-10 22:53:23 +000014063PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014064 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014065 "str", /* tp_name */
14066 sizeof(PyUnicodeObject), /* tp_size */
14067 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014068 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014069 (destructor)unicode_dealloc, /* tp_dealloc */
14070 0, /* tp_print */
14071 0, /* tp_getattr */
14072 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014073 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014074 unicode_repr, /* tp_repr */
14075 &unicode_as_number, /* tp_as_number */
14076 &unicode_as_sequence, /* tp_as_sequence */
14077 &unicode_as_mapping, /* tp_as_mapping */
14078 (hashfunc) unicode_hash, /* tp_hash*/
14079 0, /* tp_call*/
14080 (reprfunc) unicode_str, /* tp_str */
14081 PyObject_GenericGetAttr, /* tp_getattro */
14082 0, /* tp_setattro */
14083 0, /* tp_as_buffer */
14084 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014085 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014086 unicode_doc, /* tp_doc */
14087 0, /* tp_traverse */
14088 0, /* tp_clear */
14089 PyUnicode_RichCompare, /* tp_richcompare */
14090 0, /* tp_weaklistoffset */
14091 unicode_iter, /* tp_iter */
14092 0, /* tp_iternext */
14093 unicode_methods, /* tp_methods */
14094 0, /* tp_members */
14095 0, /* tp_getset */
14096 &PyBaseObject_Type, /* tp_base */
14097 0, /* tp_dict */
14098 0, /* tp_descr_get */
14099 0, /* tp_descr_set */
14100 0, /* tp_dictoffset */
14101 0, /* tp_init */
14102 0, /* tp_alloc */
14103 unicode_new, /* tp_new */
14104 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014105};
14106
14107/* Initialize the Unicode implementation */
14108
Victor Stinner3a50e702011-10-18 21:21:00 +020014109int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014110{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014111 int i;
14112
Thomas Wouters477c8d52006-05-27 19:21:47 +000014113 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014114 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014115 0x000A, /* LINE FEED */
14116 0x000D, /* CARRIAGE RETURN */
14117 0x001C, /* FILE SEPARATOR */
14118 0x001D, /* GROUP SEPARATOR */
14119 0x001E, /* RECORD SEPARATOR */
14120 0x0085, /* NEXT LINE */
14121 0x2028, /* LINE SEPARATOR */
14122 0x2029, /* PARAGRAPH SEPARATOR */
14123 };
14124
Fred Drakee4315f52000-05-09 19:53:39 +000014125 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014126 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014127 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014128 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014129 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014130
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014131 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014132 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014133 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014134 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014135
14136 /* initialize the linebreak bloom filter */
14137 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014138 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014139 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014140
14141 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014142
14143#ifdef HAVE_MBCS
14144 winver.dwOSVersionInfoSize = sizeof(winver);
14145 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14146 PyErr_SetFromWindowsErr(0);
14147 return -1;
14148 }
14149#endif
14150 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014151}
14152
14153/* Finalize the Unicode implementation */
14154
Christian Heimesa156e092008-02-16 07:38:31 +000014155int
14156PyUnicode_ClearFreeList(void)
14157{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014158 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014159}
14160
Guido van Rossumd57fd912000-03-10 22:53:23 +000014161void
Thomas Wouters78890102000-07-22 19:25:51 +000014162_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014163{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014164 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014165
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014166 Py_XDECREF(unicode_empty);
14167 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014168
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014169 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014170 if (unicode_latin1[i]) {
14171 Py_DECREF(unicode_latin1[i]);
14172 unicode_latin1[i] = NULL;
14173 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014174 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014175 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014176 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014177}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014178
Walter Dörwald16807132007-05-25 13:52:07 +000014179void
14180PyUnicode_InternInPlace(PyObject **p)
14181{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014182 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014183 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014184#ifdef Py_DEBUG
14185 assert(s != NULL);
14186 assert(_PyUnicode_CHECK(s));
14187#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014188 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014189 return;
14190#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014191 /* If it's a subclass, we don't really know what putting
14192 it in the interned dict might do. */
14193 if (!PyUnicode_CheckExact(s))
14194 return;
14195 if (PyUnicode_CHECK_INTERNED(s))
14196 return;
14197 if (interned == NULL) {
14198 interned = PyDict_New();
14199 if (interned == NULL) {
14200 PyErr_Clear(); /* Don't leave an exception */
14201 return;
14202 }
14203 }
14204 /* It might be that the GetItem call fails even
14205 though the key is present in the dictionary,
14206 namely when this happens during a stack overflow. */
14207 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014208 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014209 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014210
Benjamin Peterson29060642009-01-31 22:14:21 +000014211 if (t) {
14212 Py_INCREF(t);
14213 Py_DECREF(*p);
14214 *p = t;
14215 return;
14216 }
Walter Dörwald16807132007-05-25 13:52:07 +000014217
Benjamin Peterson14339b62009-01-31 16:36:08 +000014218 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014219 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014220 PyErr_Clear();
14221 PyThreadState_GET()->recursion_critical = 0;
14222 return;
14223 }
14224 PyThreadState_GET()->recursion_critical = 0;
14225 /* The two references in interned are not counted by refcnt.
14226 The deallocator will take care of this */
14227 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014228 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014229}
14230
14231void
14232PyUnicode_InternImmortal(PyObject **p)
14233{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014234 PyUnicode_InternInPlace(p);
14235 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014236 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014237 Py_INCREF(*p);
14238 }
Walter Dörwald16807132007-05-25 13:52:07 +000014239}
14240
14241PyObject *
14242PyUnicode_InternFromString(const char *cp)
14243{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014244 PyObject *s = PyUnicode_FromString(cp);
14245 if (s == NULL)
14246 return NULL;
14247 PyUnicode_InternInPlace(&s);
14248 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014249}
14250
Alexander Belopolsky40018472011-02-26 01:02:56 +000014251void
14252_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014253{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014254 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014255 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014256 Py_ssize_t i, n;
14257 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014258
Benjamin Peterson14339b62009-01-31 16:36:08 +000014259 if (interned == NULL || !PyDict_Check(interned))
14260 return;
14261 keys = PyDict_Keys(interned);
14262 if (keys == NULL || !PyList_Check(keys)) {
14263 PyErr_Clear();
14264 return;
14265 }
Walter Dörwald16807132007-05-25 13:52:07 +000014266
Benjamin Peterson14339b62009-01-31 16:36:08 +000014267 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14268 detector, interned unicode strings are not forcibly deallocated;
14269 rather, we give them their stolen references back, and then clear
14270 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014271
Benjamin Peterson14339b62009-01-31 16:36:08 +000014272 n = PyList_GET_SIZE(keys);
14273 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014274 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014275 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014276 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014277 if (PyUnicode_READY(s) == -1) {
14278 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014279 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014280 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014281 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014282 case SSTATE_NOT_INTERNED:
14283 /* XXX Shouldn't happen */
14284 break;
14285 case SSTATE_INTERNED_IMMORTAL:
14286 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014287 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014288 break;
14289 case SSTATE_INTERNED_MORTAL:
14290 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014291 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014292 break;
14293 default:
14294 Py_FatalError("Inconsistent interned string state.");
14295 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014296 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014297 }
14298 fprintf(stderr, "total size of all interned strings: "
14299 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14300 "mortal/immortal\n", mortal_size, immortal_size);
14301 Py_DECREF(keys);
14302 PyDict_Clear(interned);
14303 Py_DECREF(interned);
14304 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014305}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014306
14307
14308/********************* Unicode Iterator **************************/
14309
14310typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014311 PyObject_HEAD
14312 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014313 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014314} unicodeiterobject;
14315
14316static void
14317unicodeiter_dealloc(unicodeiterobject *it)
14318{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014319 _PyObject_GC_UNTRACK(it);
14320 Py_XDECREF(it->it_seq);
14321 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014322}
14323
14324static int
14325unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14326{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014327 Py_VISIT(it->it_seq);
14328 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014329}
14330
14331static PyObject *
14332unicodeiter_next(unicodeiterobject *it)
14333{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014334 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014335
Benjamin Peterson14339b62009-01-31 16:36:08 +000014336 assert(it != NULL);
14337 seq = it->it_seq;
14338 if (seq == NULL)
14339 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014340 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014341
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014342 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14343 int kind = PyUnicode_KIND(seq);
14344 void *data = PyUnicode_DATA(seq);
14345 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14346 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014347 if (item != NULL)
14348 ++it->it_index;
14349 return item;
14350 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014351
Benjamin Peterson14339b62009-01-31 16:36:08 +000014352 Py_DECREF(seq);
14353 it->it_seq = NULL;
14354 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014355}
14356
14357static PyObject *
14358unicodeiter_len(unicodeiterobject *it)
14359{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014360 Py_ssize_t len = 0;
14361 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014362 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014363 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014364}
14365
14366PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14367
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014368static PyObject *
14369unicodeiter_reduce(unicodeiterobject *it)
14370{
14371 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014372 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014373 it->it_seq, it->it_index);
14374 } else {
14375 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14376 if (u == NULL)
14377 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014378 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014379 }
14380}
14381
14382PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14383
14384static PyObject *
14385unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14386{
14387 Py_ssize_t index = PyLong_AsSsize_t(state);
14388 if (index == -1 && PyErr_Occurred())
14389 return NULL;
14390 if (index < 0)
14391 index = 0;
14392 it->it_index = index;
14393 Py_RETURN_NONE;
14394}
14395
14396PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14397
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014398static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014399 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014400 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014401 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14402 reduce_doc},
14403 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14404 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014405 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014406};
14407
14408PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014409 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14410 "str_iterator", /* tp_name */
14411 sizeof(unicodeiterobject), /* tp_basicsize */
14412 0, /* tp_itemsize */
14413 /* methods */
14414 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14415 0, /* tp_print */
14416 0, /* tp_getattr */
14417 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014418 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014419 0, /* tp_repr */
14420 0, /* tp_as_number */
14421 0, /* tp_as_sequence */
14422 0, /* tp_as_mapping */
14423 0, /* tp_hash */
14424 0, /* tp_call */
14425 0, /* tp_str */
14426 PyObject_GenericGetAttr, /* tp_getattro */
14427 0, /* tp_setattro */
14428 0, /* tp_as_buffer */
14429 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14430 0, /* tp_doc */
14431 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14432 0, /* tp_clear */
14433 0, /* tp_richcompare */
14434 0, /* tp_weaklistoffset */
14435 PyObject_SelfIter, /* tp_iter */
14436 (iternextfunc)unicodeiter_next, /* tp_iternext */
14437 unicodeiter_methods, /* tp_methods */
14438 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014439};
14440
14441static PyObject *
14442unicode_iter(PyObject *seq)
14443{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014444 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014445
Benjamin Peterson14339b62009-01-31 16:36:08 +000014446 if (!PyUnicode_Check(seq)) {
14447 PyErr_BadInternalCall();
14448 return NULL;
14449 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014450 if (PyUnicode_READY(seq) == -1)
14451 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014452 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14453 if (it == NULL)
14454 return NULL;
14455 it->it_index = 0;
14456 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014457 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014458 _PyObject_GC_TRACK(it);
14459 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014460}
14461
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014462
14463size_t
14464Py_UNICODE_strlen(const Py_UNICODE *u)
14465{
14466 int res = 0;
14467 while(*u++)
14468 res++;
14469 return res;
14470}
14471
14472Py_UNICODE*
14473Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14474{
14475 Py_UNICODE *u = s1;
14476 while ((*u++ = *s2++));
14477 return s1;
14478}
14479
14480Py_UNICODE*
14481Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14482{
14483 Py_UNICODE *u = s1;
14484 while ((*u++ = *s2++))
14485 if (n-- == 0)
14486 break;
14487 return s1;
14488}
14489
14490Py_UNICODE*
14491Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14492{
14493 Py_UNICODE *u1 = s1;
14494 u1 += Py_UNICODE_strlen(u1);
14495 Py_UNICODE_strcpy(u1, s2);
14496 return s1;
14497}
14498
14499int
14500Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14501{
14502 while (*s1 && *s2 && *s1 == *s2)
14503 s1++, s2++;
14504 if (*s1 && *s2)
14505 return (*s1 < *s2) ? -1 : +1;
14506 if (*s1)
14507 return 1;
14508 if (*s2)
14509 return -1;
14510 return 0;
14511}
14512
14513int
14514Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14515{
14516 register Py_UNICODE u1, u2;
14517 for (; n != 0; n--) {
14518 u1 = *s1;
14519 u2 = *s2;
14520 if (u1 != u2)
14521 return (u1 < u2) ? -1 : +1;
14522 if (u1 == '\0')
14523 return 0;
14524 s1++;
14525 s2++;
14526 }
14527 return 0;
14528}
14529
14530Py_UNICODE*
14531Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14532{
14533 const Py_UNICODE *p;
14534 for (p = s; *p; p++)
14535 if (*p == c)
14536 return (Py_UNICODE*)p;
14537 return NULL;
14538}
14539
14540Py_UNICODE*
14541Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14542{
14543 const Py_UNICODE *p;
14544 p = s + Py_UNICODE_strlen(s);
14545 while (p != s) {
14546 p--;
14547 if (*p == c)
14548 return (Py_UNICODE*)p;
14549 }
14550 return NULL;
14551}
Victor Stinner331ea922010-08-10 16:37:20 +000014552
Victor Stinner71133ff2010-09-01 23:43:53 +000014553Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014554PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014555{
Victor Stinner577db2c2011-10-11 22:12:48 +020014556 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014557 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014558
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014559 if (!PyUnicode_Check(unicode)) {
14560 PyErr_BadArgument();
14561 return NULL;
14562 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014563 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014564 if (u == NULL)
14565 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014566 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014567 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014568 PyErr_NoMemory();
14569 return NULL;
14570 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014571 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014572 size *= sizeof(Py_UNICODE);
14573 copy = PyMem_Malloc(size);
14574 if (copy == NULL) {
14575 PyErr_NoMemory();
14576 return NULL;
14577 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014578 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014579 return copy;
14580}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014581
Georg Brandl66c221e2010-10-14 07:04:07 +000014582/* A _string module, to export formatter_parser and formatter_field_name_split
14583 to the string.Formatter class implemented in Python. */
14584
14585static PyMethodDef _string_methods[] = {
14586 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14587 METH_O, PyDoc_STR("split the argument as a field name")},
14588 {"formatter_parser", (PyCFunction) formatter_parser,
14589 METH_O, PyDoc_STR("parse the argument as a format string")},
14590 {NULL, NULL}
14591};
14592
14593static struct PyModuleDef _string_module = {
14594 PyModuleDef_HEAD_INIT,
14595 "_string",
14596 PyDoc_STR("string helper module"),
14597 0,
14598 _string_methods,
14599 NULL,
14600 NULL,
14601 NULL,
14602 NULL
14603};
14604
14605PyMODINIT_FUNC
14606PyInit__string(void)
14607{
14608 return PyModule_Create(&_string_module);
14609}
14610
14611
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014612#ifdef __cplusplus
14613}
14614#endif